0a0ba0a96164e824353bf55aecdf64a013133af5
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1) # SPDX-FileCopyrightText: 2025 Marco Ricci <software@the13thletter.info>
2) #
3) # SPDX-License-Identifier: Zlib
4) 
Marco Ricci Add module docstrings for t...

Marco Ricci authored 11 months ago

5) """Tests for `derivepassphrase.ssh_agent`: basic tests."""
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

6) 
7) from __future__ import annotations
8) 
9) import base64
10) import contextlib
11) import errno
12) import importlib.metadata
13) import io
14) import os
15) import pathlib
16) import re
17) import socket
18) import sys
19) import types
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

20) from typing import TYPE_CHECKING, NamedTuple
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

21) 
22) import click
23) import hypothesis
24) import pytest
25) from hypothesis import strategies
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

26) from typing_extensions import TypeAlias
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

27) 
28) from derivepassphrase import _types, ssh_agent, vault
29) from derivepassphrase._internals import cli_helpers
30) from derivepassphrase.ssh_agent import socketprovider
31) from tests import data, machinery
32) from tests.data import callables
33) from tests.machinery import pytest as pytest_machinery
34) 
35) if TYPE_CHECKING:
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

36)     from collections.abc import Iterable, Iterator, Mapping
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

37) 
38)     from typing_extensions import Any, Buffer, Literal
39) 
40) if sys.version_info < (3, 11):
41)     from exceptiongroup import ExceptionGroup
42) 
43) 
44) class Parametrize(types.SimpleNamespace):
45)     BAD_ENTRY_POINTS = pytest.mark.parametrize(
46)         "additional_entry_points",
47)         [
48)             pytest.param(
49)                 [
50)                     importlib.metadata.EntryPoint(
51)                         name=data.faulty_entry_callable.key,
52)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
53)                         value="tests.data: faulty_entry_callable",
54)                     ),
55)                 ],
56)                 id="not-callable",
57)             ),
58)             pytest.param(
59)                 [
60)                     importlib.metadata.EntryPoint(
61)                         name=data.faulty_entry_name_exists.key,
62)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
63)                         value="tests.data: faulty_entry_name_exists",
64)                     ),
65)                 ],
66)                 id="name-already-exists",
67)             ),
68)             pytest.param(
69)                 [
70)                     importlib.metadata.EntryPoint(
71)                         name=data.faulty_entry_alias_exists.key,
72)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
73)                         value="tests.data: faulty_entry_alias_exists",
74)                     ),
75)                 ],
76)                 id="alias-already-exists",
77)             ),
78)         ],
79)     )
80)     GOOD_ENTRY_POINTS = pytest.mark.parametrize(
81)         "additional_entry_points",
82)         [
83)             pytest.param(
84)                 [
85)                     importlib.metadata.EntryPoint(
86)                         name=data.posix_entry.key,
87)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
88)                         value="tests.data: posix_entry",
89)                     ),
90)                     importlib.metadata.EntryPoint(
91)                         name=data.the_annoying_os_entry.key,
92)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
93)                         value="tests.data: the_annoying_os_entry",
94)                     ),
95)                 ],
96)                 id="existing-entries",
97)             ),
98)             pytest.param(
99)                 [
100)                     importlib.metadata.EntryPoint(
101)                         name=callables.provider_entry1.key,
102)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
103)                         value="tests.data.callables: provider_entry1",
104)                     ),
105)                     importlib.metadata.EntryPoint(
106)                         name=callables.provider_entry2.key,
107)                         group=socketprovider.SocketProvider.ENTRY_POINT_GROUP_NAME,
108)                         value="tests.data.callables: provider_entry2",
109)                     ),
110)                 ],
111)                 id="new-entries",
112)             ),
113)         ],
114)     )
115)     STUBBED_AGENT_ADDRESSES = pytest.mark.parametrize(
116)         ["address", "exception", "match"],
117)         [
118)             pytest.param(None, KeyError, "SSH_AUTH_SOCK", id="unset"),
119)             pytest.param("stub-ssh-agent:", None, "", id="standard"),
120)             pytest.param(
121)                 str(pathlib.Path("~").expanduser()),
122)                 FileNotFoundError,
123)                 os.strerror(errno.ENOENT),
124)                 id="invalid-url",
125)             ),
126)             pytest.param(
127)                 "stub-ssh-agent:EPROTONOSUPPORT",
128)                 OSError,
129)                 os.strerror(errno.EPROTONOSUPPORT),
130)                 id="protocol-not-supported",
131)             ),
132)             pytest.param(
133)                 "stub-ssh-agent:ABCDEFGHIJKLMNOPQRSTUVWXYZ",
134)                 OSError,
135)                 os.strerror(errno.EINVAL),
136)                 id="invalid-error-code",
137)             ),
138)         ],
139)     )
140)     EXISTING_REGISTRY_ENTRIES = pytest.mark.parametrize(
141)         "existing", ["posix", "the_annoying_os"]
142)     )
143)     SSH_STRING_EXCEPTIONS = pytest.mark.parametrize(
144)         ["input", "exc_type", "exc_pattern"],
145)         [
146)             pytest.param(
147)                 "some string", TypeError, "invalid payload type", id="str"
148)             ),
149)         ],
150)     )
151)     UINT32_EXCEPTIONS = pytest.mark.parametrize(
152)         ["input", "exc_type", "exc_pattern"],
153)         [
154)             pytest.param(
155)                 10000000000000000,
156)                 OverflowError,
157)                 "int too big to convert",
158)                 id="10000000000000000",
159)             ),
160)             pytest.param(
161)                 -1,
162)                 OverflowError,
163)                 "can't convert negative int to unsigned",
164)                 id="-1",
165)             ),
166)         ],
167)     )
168)     SSH_UNSTRING_EXCEPTIONS = pytest.mark.parametrize(
169)         ["input", "exc_type", "exc_pattern", "has_trailer", "parts"],
170)         [
171)             pytest.param(
172)                 b"ssh",
173)                 ValueError,
174)                 "malformed SSH byte string",
175)                 False,
176)                 None,
177)                 id="unencoded",
178)             ),
179)             pytest.param(
180)                 b"\x00\x00\x00\x08ssh-rsa",
181)                 ValueError,
182)                 "malformed SSH byte string",
183)                 False,
184)                 None,
185)                 id="truncated",
186)             ),
187)             pytest.param(
188)                 b"\x00\x00\x00\x04XXX trailing text",
189)                 ValueError,
190)                 "malformed SSH byte string",
191)                 True,
192)                 (b"XXX ", b"trailing text"),
193)                 id="trailing-data",
194)             ),
195)         ],
196)     )
197)     SSH_STRING_INPUT = pytest.mark.parametrize(
198)         ["input", "expected"],
199)         [
200)             pytest.param(
201)                 b"ssh-rsa",
202)                 b"\x00\x00\x00\x07ssh-rsa",
203)                 id="ssh-rsa",
204)             ),
205)             pytest.param(
206)                 b"ssh-ed25519",
207)                 b"\x00\x00\x00\x0bssh-ed25519",
208)                 id="ssh-ed25519",
209)             ),
210)             pytest.param(
211)                 ssh_agent.SSHAgentClient.string(b"ssh-ed25519"),
212)                 b"\x00\x00\x00\x0f\x00\x00\x00\x0bssh-ed25519",
213)                 id="string(ssh-ed25519)",
214)             ),
215)         ],
216)     )
217)     SSH_UNSTRING_INPUT = pytest.mark.parametrize(
218)         ["input", "expected"],
219)         [
220)             pytest.param(
221)                 b"\x00\x00\x00\x07ssh-rsa",
222)                 b"ssh-rsa",
223)                 id="ssh-rsa",
224)             ),
225)             pytest.param(
226)                 ssh_agent.SSHAgentClient.string(b"ssh-ed25519"),
227)                 b"ssh-ed25519",
228)                 id="ssh-ed25519",
229)             ),
230)         ],
231)     )
232)     UINT32_INPUT = pytest.mark.parametrize(
233)         ["input", "expected"],
234)         [
235)             pytest.param(16777216, b"\x01\x00\x00\x00", id="16777216"),
236)         ],
237)     )
238)     SIGN_ERROR_RESPONSES = pytest.mark.parametrize(
239)         [
240)             "key",
241)             "check",
242)             "response_code",
243)             "response",
244)             "exc_type",
245)             "exc_pattern",
246)         ],
247)         [
248)             pytest.param(
249)                 b"invalid-key",
250)                 True,
251)                 _types.SSH_AGENT.FAILURE,
252)                 b"",
253)                 KeyError,
254)                 "target SSH key not loaded into agent",
255)                 id="key-not-loaded",
256)             ),
257)             pytest.param(
258)                 data.SUPPORTED_KEYS["ed25519"].public_key_data,
259)                 True,
260)                 _types.SSH_AGENT.FAILURE,
261)                 b"",
262)                 ssh_agent.SSHAgentFailedError,
263)                 "failed to complete the request",
264)                 id="failed-to-complete",
265)             ),
266)         ],
267)     )
268)     SSH_KEY_SELECTION = pytest.mark.parametrize(
269)         ["key", "single"],
270)         [
271)             (value.public_key_data, False)
272)             for value in data.SUPPORTED_KEYS.values()
273)         ]
274)         + [(callables.list_keys_singleton()[0].key, True)],
275)         ids=[*data.SUPPORTED_KEYS.keys(), "singleton"],
276)     )
277)     SH_EXPORT_LINES = pytest.mark.parametrize(
278)         ["line", "env_name", "value"],
279)         [
280)             pytest.param(
281)                 "SSH_AUTH_SOCK=/tmp/pageant.user/pageant.27170; export SSH_AUTH_SOCK;",
282)                 "SSH_AUTH_SOCK",
283)                 "/tmp/pageant.user/pageant.27170",
284)                 id="value-export-semicolon-pageant",
285)             ),
286)             pytest.param(
287)                 "SSH_AUTH_SOCK=/tmp/ssh-3CSTC1W5M22A/agent.27270; export SSH_AUTH_SOCK;",
288)                 "SSH_AUTH_SOCK",
289)                 "/tmp/ssh-3CSTC1W5M22A/agent.27270",
290)                 id="value-export-semicolon-openssh",
291)             ),
292)             pytest.param(
293)                 "SSH_AUTH_SOCK=/tmp/pageant.user/pageant.27170; export SSH_AUTH_SOCK",
294)                 "SSH_AUTH_SOCK",
295)                 "/tmp/pageant.user/pageant.27170",
296)                 id="value-export-pageant",
297)             ),
298)             pytest.param(
299)                 "export SSH_AUTH_SOCK=/tmp/ssh-3CSTC1W5M22A/agent.27270;",
300)                 "SSH_AUTH_SOCK",
301)                 "/tmp/ssh-3CSTC1W5M22A/agent.27270",
302)                 id="export-value-semicolon-openssh",
303)             ),
304)             pytest.param(
305)                 "export SSH_AUTH_SOCK=/tmp/pageant.user/pageant.27170",
306)                 "SSH_AUTH_SOCK",
307)                 "/tmp/pageant.user/pageant.27170",
308)                 id="export-value-pageant",
309)             ),
310)             pytest.param(
311)                 "SSH_AGENT_PID=27170; export SSH_AGENT_PID;",
312)                 "SSH_AGENT_PID",
313)                 "27170",
314)                 id="pid-export-semicolon",
315)             ),
316)             pytest.param(
317)                 "SSH_AGENT_PID=27170; export SSH_AGENT_PID",
318)                 "SSH_AGENT_PID",
319)                 "27170",
320)                 id="pid-export",
321)             ),
322)             pytest.param(
323)                 "export SSH_AGENT_PID=27170;",
324)                 "SSH_AGENT_PID",
325)                 "27170",
326)                 id="export-pid-semicolon",
327)             ),
328)             pytest.param(
329)                 "export SSH_AGENT_PID=27170",
330)                 "SSH_AGENT_PID",
331)                 "27170",
332)                 id="export-pid",
333)             ),
334)             pytest.param(
335)                 "export VARIABLE=value; export OTHER_VARIABLE=other_value;",
336)                 "VARIABLE",
337)                 None,
338)                 id="export-too-much",
339)             ),
340)             pytest.param(
341)                 "VARIABLE=value",
342)                 "VARIABLE",
343)                 None,
344)                 id="no-export",
345)             ),
346)         ],
347)     )
348)     INVALID_SSH_AGENT_MESSAGES = pytest.mark.parametrize(
349)         "message",
350)         [
351)             pytest.param(b"\x00\x00\x00\x00", id="empty-message"),
352)             pytest.param(b"\x00\x00\x00\x0f\x0d", id="truncated-message"),
353)             pytest.param(
354)                 b"\x00\x00\x00\x06\x1b\x00\x00\x00\x01\xff",
355)                 id="invalid-extension-name",
356)             ),
357)             pytest.param(
358)                 b"\x00\x00\x00\x11\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
359)                 id="sign-with-trailing-data",
360)             ),
361)         ],
362)     )
363)     UNSUPPORTED_SSH_AGENT_MESSAGES = pytest.mark.parametrize(
364)         "message",
365)         [
366)             pytest.param(
367)                 ssh_agent.SSHAgentClient.string(
368)                     b"".join([
369)                         b"\x0d",
370)                         ssh_agent.SSHAgentClient.string(
371)                             data.ALL_KEYS["rsa"].public_key_data
372)                         ),
373)                         ssh_agent.SSHAgentClient.string(vault.Vault.UUID),
374)                         b"\x00\x00\x00\x02",
375)                     ])
376)                 ),
377)                 id="sign-with-flags",
378)             ),
379)             pytest.param(
380)                 ssh_agent.SSHAgentClient.string(
381)                     b"".join([
382)                         b"\x0d",
383)                         ssh_agent.SSHAgentClient.string(
384)                             data.ALL_KEYS["ed25519"].public_key_data
385)                         ),
386)                         b"\x00\x00\x00\x08\x00\x01\x02\x03\x04\x05\x06\x07",
387)                         b"\x00\x00\x00\x00",
388)                     ])
389)                 ),
390)                 id="sign-with-nonstandard-passphrase",
391)             ),
392)             pytest.param(
393)                 ssh_agent.SSHAgentClient.string(
394)                     b"".join([
395)                         b"\x0d",
396)                         ssh_agent.SSHAgentClient.string(
397)                             data.ALL_KEYS["dsa1024"].public_key_data
398)                         ),
399)                         ssh_agent.SSHAgentClient.string(vault.Vault.UUID),
400)                         b"\x00\x00\x00\x00",
401)                     ])
402)                 ),
403)                 id="sign-key-no-expected-signature",
404)             ),
405)             pytest.param(
406)                 ssh_agent.SSHAgentClient.string(
407)                     b"".join([
408)                         b"\x0d",
409)                         b"\x00\x00\x00\x00",
410)                         ssh_agent.SSHAgentClient.string(vault.Vault.UUID),
411)                         b"\x00\x00\x00\x00",
412)                     ])
413)                 ),
414)                 id="sign-key-unregistered-test-key",
415)             ),
416)         ],
417)     )
418)     PUBLIC_KEY_DATA = pytest.mark.parametrize(
419)         "public_key_struct",
420)         list(data.SUPPORTED_KEYS.values()),
421)         ids=list(data.SUPPORTED_KEYS.keys()),
422)     )
423)     REQUEST_ERROR_RESPONSES = pytest.mark.parametrize(
424)         ["request_code", "response_code", "exc_type", "exc_pattern"],
425)         [
426)             pytest.param(
427)                 _types.SSH_AGENTC.REQUEST_IDENTITIES,
428)                 _types.SSH_AGENT.SUCCESS,
429)                 ssh_agent.SSHAgentFailedError,
430)                 re.escape(
431)                     f"[Code {_types.SSH_AGENT.IDENTITIES_ANSWER.value}]"
432)                 ),
433)                 id="REQUEST_IDENTITIES-expect-SUCCESS",
434)             ),
435)         ],
436)     )
437)     TRUNCATED_AGENT_RESPONSES = pytest.mark.parametrize(
438)         "response",
439)         [
440)             b"\x00\x00",
441)             b"\x00\x00\x00\x1f some bytes missing",
442)         ],
443)         ids=["in-header", "in-body"],
444)     )
445)     LIST_KEYS_ERROR_RESPONSES = pytest.mark.parametrize(
446)         ["response_code", "response", "exc_type", "exc_pattern"],
447)         [
448)             pytest.param(
449)                 _types.SSH_AGENT.FAILURE,
450)                 b"",
451)                 ssh_agent.SSHAgentFailedError,
452)                 "failed to complete the request",
453)                 id="failed-to-complete",
454)             ),
455)             pytest.param(
456)                 _types.SSH_AGENT.IDENTITIES_ANSWER,
457)                 b"\x00\x00\x00\x01",
458)                 EOFError,
459)                 "truncated response",
460)                 id="truncated-response",
461)             ),
462)             pytest.param(
463)                 _types.SSH_AGENT.IDENTITIES_ANSWER,
464)                 b"\x00\x00\x00\x00abc",
465)                 ssh_agent.TrailingDataError,
466)                 "Overlong response",
467)                 id="overlong-response",
468)             ),
469)         ],
470)     )
471)     QUERY_EXTENSIONS_MALFORMED_RESPONSES = pytest.mark.parametrize(
472)         "response_data",
473)         [
474)             pytest.param(b"\xde\xad\xbe\xef", id="truncated"),
475)             pytest.param(
476)                 b"\x00\x00\x00\x0fwrong extension", id="wrong-extension"
477)             ),
478)             pytest.param(
479)                 b"\x00\x00\x00\x05query\xde\xad\xbe\xef", id="with-trailer"
480)             ),
481)             pytest.param(
482)                 b"\x00\x00\x00\x05query\x00\x00\x00\x04ext1\x00\x00",
483)                 id="with-extra-fields",
484)             ),
485)         ],
486)     )
487)     SUPPORTED_SSH_TEST_KEYS = pytest.mark.parametrize(
488)         ["ssh_test_key_type", "ssh_test_key"],
489)         list(data.SUPPORTED_KEYS.items()),
490)         ids=data.SUPPORTED_KEYS.keys(),
491)     )
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

492)     ALL_SSH_TEST_KEYS = pytest.mark.parametrize(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

493)         ["ssh_test_key_type", "ssh_test_key"],
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

494)         list(data.ALL_KEYS.items()),
495)         ids=data.ALL_KEYS.keys(),
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

496)     )
497)     RESOLVE_CHAINS = pytest.mark.parametrize(
498)         ["terminal", "chain"],
499)         [
500)             pytest.param("callable", ["a"], id="callable-1"),
501)             pytest.param("callable", ["a", "b", "c", "d"], id="callable-4"),
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

502)             pytest.param("alias", ["e"], id="alias-1"),
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

503)             pytest.param("alias", ["e", "f", "g", "h", "i"], id="alias-5"),
504)             pytest.param("unimplemented", ["j"], id="unimplemented-1"),
505)             pytest.param("unimplemented", ["j", "k"], id="unimplemented-2"),
506)         ],
507)     )
508) 
509) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

510) class TestStubbedSSHAgentSocketRequests:
511)     """Test the stubbed SSH agent socket: normal requests."""
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

512) 
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

513)     @contextlib.contextmanager
514)     def _get_addressed_agent(
515)         self, *, extended_agent: bool = False
516)     ) -> Iterator[machinery.StubbedSSHAgentSocketWithAddress]:
517)         agent_class: type[machinery.StubbedSSHAgentSocketWithAddress] = (
518)             machinery.StubbedSSHAgentSocketWithAddressAndDeterministicDSA
519)             if extended_agent
520)             else machinery.StubbedSSHAgentSocketWithAddress
521)         )
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

522)         with contextlib.ExitStack() as stack:
523)             monkeypatch = stack.enter_context(pytest.MonkeyPatch.context())
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

524)             monkeypatch.setenv("SSH_AUTH_SOCK", agent_class.ADDRESS)
525)             agent = stack.enter_context(agent_class())
526)             yield agent
527) 
528)     def test_query_extensions_base(self) -> None:
529)         """The base agent implements no extensions."""
530)         with self._get_addressed_agent(extended_agent=False) as agent:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

531)             assert "query" not in agent.enabled_extensions
532)             query_request = (
533)                 # SSH string header
534)                 b"\x00\x00\x00\x0a"
535)                 # request code: SSH_AGENTC_EXTENSION
536)                 b"\x1b"
537)                 # payload: SSH string "query"
538)                 b"\x00\x00\x00\x05query"
539)             )
540)             query_response = (
541)                 # SSH string header
542)                 b"\x00\x00\x00\x01"
543)                 # response code: SSH_AGENT_FAILURE
544)                 b"\x05"
545)             )
546)             agent.sendall(query_request)
547)             assert agent.recv(1000) == query_response
548) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

549)     def test_query_extensions_extended(self) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

550)         """The extended agent implements a known list of extensions."""
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

551)         with self._get_addressed_agent(extended_agent=True) as agent:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

552)             assert "query" in agent.enabled_extensions
553)             query_request = (
554)                 # SSH string header
555)                 b"\x00\x00\x00\x0a"
556)                 # request code: SSH_AGENTC_EXTENSION
557)                 b"\x1b"
558)                 # payload: SSH string "query"
559)                 b"\x00\x00\x00\x05query"
560)             )
561)             query_response = (
562)                 # SSH string header
563)                 b"\x00\x00\x00\x40"
564)                 # response code: SSH_AGENT_EXTENSION_RESPONSE
565)                 b"\x1d"
566)                 # extension response: extension type ("query")
567)                 b"\x00\x00\x00\x05query"
568)                 # supported extension #1: query
569)                 b"\x00\x00\x00\x05query"
570)                 # supported extension #2:
571)                 # list-extended@putty.projects.tartarus.org
572)                 b"\x00\x00\x00\x29list-extended@putty.projects.tartarus.org"
573)             )
574)             agent.sendall(query_request)
575)             assert agent.recv(1000) == query_response
576) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

577)     def test_request_identities(self) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

578)         """The agent implements a known list of identities."""
579)         unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
580)         with machinery.StubbedSSHAgentSocket() as agent:
581)             query_request = (
582)                 # SSH string header
583)                 b"\x00\x00\x00\x01"
584)                 # request code: SSH_AGENTC_REQUEST_IDENTITIES
585)                 b"\x0b"
586)             )
587)             agent.sendall(query_request)
588)             message_length = int.from_bytes(agent.recv(4), "big")
589)             orig_message: bytes | bytearray = bytearray(
590)                 agent.recv(message_length)
591)             )
592)             assert (
593)                 _types.SSH_AGENT(orig_message[0])
594)                 == _types.SSH_AGENT.IDENTITIES_ANSWER
595)             )
596)             identity_count = int.from_bytes(orig_message[1:5], "big")
597)             message = bytes(orig_message[5:])
598)             for _ in range(identity_count):
599)                 key, message = unstring_prefix(message)
600)                 _comment, message = unstring_prefix(message)
601)                 assert key
602)                 assert key in {
603)                     k.public_key_data for k in data.ALL_KEYS.values()
604)                 }
605)             assert not message
606) 
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

607)     def test_request_identities_extended(self) -> None:
608)         """The extended agent implements PuTTY's `list-extended` extension."""
609)         unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
610)         with self._get_addressed_agent(extended_agent=True) as agent:
611)             extension_request = (
612)                 # SSH string header
613)                 b"\x00\x00\x00\x2e"
614)                 # request code: SSH_AGENTC_REQUEST_IDENTITIES
615)                 b"\x1b"
616)                 # extension type: list-extended@putty.projects.tartarus.org
617)                 b"\x00\x00\x00\x29list-extended@putty.projects.tartarus.org"
618)                 # (no payload)
619)             )
620)             agent.sendall(extension_request)
621)             message_length = int.from_bytes(agent.recv(4), "big")
622)             orig_message: bytes | bytearray = bytearray(
623)                 agent.recv(message_length)
624)             )
625)             assert (
Marco Ricci Format and lint all files

Marco Ricci authored 11 months ago

626)                 _types.SSH_AGENT(orig_message[0]) == _types.SSH_AGENT.SUCCESS
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

627)             )
628)             identity_count = int.from_bytes(orig_message[1:5], "big")
629)             message = bytes(orig_message[5:])
630)             for _ in range(identity_count):
631)                 key, message = unstring_prefix(message)
632)                 _comment, message = unstring_prefix(message)
633)                 flags, message = unstring_prefix(message)
634)                 assert flags == b"\x00\x00\x00\x00"
635)                 assert key
636)                 assert key in {
637)                     k.public_key_data for k in data.ALL_KEYS.values()
638)                 }
639)             assert not message
640) 
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

641)     @Parametrize.SUPPORTED_SSH_TEST_KEYS
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

642)     def test_sign(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

643)         self,
644)         ssh_test_key_type: str,
645)         ssh_test_key: data.SSHTestKey,
646)     ) -> None:
647)         """The agent signs known key/message pairs."""
648)         del ssh_test_key_type
649)         spec = data.SSHTestKeyDeterministicSignatureClass.SPEC
650)         assert ssh_test_key.expected_signatures[spec].signature is not None
651)         string = ssh_agent.SSHAgentClient.string
652)         query_request = string(
653)             # request code: SSH_AGENTC_SIGN_REQUEST
654)             b"\x0d"
655)             # key: SSH string of the public key
656)             + string(ssh_test_key.public_key_data)
657)             # payload: SSH string of the vault UUID
658)             + string(vault.Vault.UUID)
659)             # signing flags (uint32, empty)
660)             + b"\x00\x00\x00\x00"
661)         )
662)         query_response = string(
663)             # response code: SSH_AGENT_SIGN_RESPONSE
664)             b"\x0e"
665)             # expected payload: the binary signature as recorded in the test key data structure
666)             + string(ssh_test_key.expected_signatures[spec].signature)
667)         )
668)         with machinery.StubbedSSHAgentSocket() as agent:
669)             agent.sendall(query_request)
670)             assert agent.recv(1000) == query_response
671) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

672) 
673) class TestStubbedSSHAgentSocketProperOperations:
674)     """Test the stubbed SSH agent socket: proper use and misuse."""
675) 
676)     def test_close_multiple(self) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

677)         """The agent can be closed repeatedly."""
678)         with machinery.StubbedSSHAgentSocket() as agent:
679)             pass
680)         with machinery.StubbedSSHAgentSocket() as agent:
681)             pass
682)         del agent
683) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

684)     def test_closed_agents_cannot_be_interacted_with(self) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

685)         """The agent can be closed repeatedly."""
686)         with machinery.StubbedSSHAgentSocket() as agent:
687)             pass
688)         query_request = (
689)             # SSH string header
690)             b"\x00\x00\x00\x0a"
691)             # request code: SSH_AGENTC_EXTENSION
692)             b"\x1b"
693)             # payload: SSH string "query"
694)             b"\x00\x00\x00\x05query"
695)         )
696)         query_response = b""
697)         with pytest.raises(
698)             ValueError,
699)             match=re.escape(machinery.StubbedSSHAgentSocket._SOCKET_IS_CLOSED),
700)         ):
701)             agent.sendall(query_request)
702)         assert agent.recv(100) == query_response
703) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

704)     def test_no_recv_without_sendall(self) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

705)         """The agent requires a message before sending a response."""
706)         with machinery.StubbedSSHAgentSocket() as agent:  # noqa: SIM117
707)             with pytest.raises(
708)                 AssertionError,
709)                 match=re.escape(
710)                     machinery.StubbedSSHAgentSocket._PROTOCOL_VIOLATION
711)                 ),
712)             ):
713)                 agent.recv(100)
714) 
715)     @Parametrize.INVALID_SSH_AGENT_MESSAGES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

716)     def test_invalid_ssh_agent_messages(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

717)         self,
718)         message: Buffer,
719)     ) -> None:
720)         """The agent responds with errors on invalid messages."""
721)         query_response = (
722)             # SSH string header
723)             b"\x00\x00\x00\x01"
724)             # response code: SSH_AGENT_FAILURE
725)             b"\x05"
726)         )
727)         with machinery.StubbedSSHAgentSocket() as agent:
728)             agent.sendall(message)
729)             assert agent.recv(100) == query_response
730) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

731) 
732) class TestStubbedSSHAgentSocketSupportedAndUnsupportedFeatures:
733)     """Test the stubbed SSH agent socket: supported/unsupported features."""
734) 
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

735)     @Parametrize.UNSUPPORTED_SSH_AGENT_MESSAGES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

736)     def test_unsupported_ssh_agent_messages(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

737)         self,
738)         message: Buffer,
739)     ) -> None:
740)         """The agent responds with errors on unsupported messages."""
741)         query_response = (
742)             # SSH string header
743)             b"\x00\x00\x00\x01"
744)             # response code: SSH_AGENT_FAILURE
745)             b"\x05"
746)         )
747)         with machinery.StubbedSSHAgentSocket() as agent:
748)             agent.sendall(message)
749)             assert agent.recv(100) == query_response
750) 
751)     @Parametrize.STUBBED_AGENT_ADDRESSES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

752)     def test_addresses(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

753)         self,
754)         address: str | None,
755)         exception: type[Exception] | None,
756)         match: str,
757)     ) -> None:
758)         """The agent accepts addresses."""
759)         with contextlib.ExitStack() as stack:
760)             monkeypatch = stack.enter_context(pytest.MonkeyPatch.context())
761)             if address:
762)                 monkeypatch.setenv("SSH_AUTH_SOCK", address)
763)             else:
764)                 monkeypatch.delenv("SSH_AUTH_SOCK", raising=False)
765)             if exception:
766)                 stack.enter_context(
767)                     pytest.raises(exception, match=re.escape(match))
768)                 )
769)             machinery.StubbedSSHAgentSocketWithAddress()
770) 
771) 
772) class TestStaticFunctionality:
773)     """Test the static functionality of the `ssh_agent` module."""
774) 
775)     @staticmethod
776)     def as_ssh_string(bytestring: bytes) -> bytes:
777)         """Return an encoded SSH string from a bytestring.
778) 
779)         This is a helper function for hypothesis data generation.
780) 
781)         """
782)         return int.to_bytes(len(bytestring), 4, "big") + bytestring
783) 
784)     @staticmethod
785)     def canonicalize1(data: bytes) -> bytes:
786)         """Return an encoded SSH string from a bytestring.
787) 
788)         This is a helper function for hypothesis testing.
789) 
790)         References:
791) 
792)           * [David R. MacIver: Another invariant to test for
793)             encoders][DECODE_ENCODE]
794) 
795)         [DECODE_ENCODE]: https://hypothesis.works/articles/canonical-serialization/
796) 
797)         """
798)         return ssh_agent.SSHAgentClient.string(
799)             ssh_agent.SSHAgentClient.unstring(data)
800)         )
801) 
802)     @staticmethod
803)     def canonicalize2(data: bytes) -> bytes:
804)         """Return an encoded SSH string from a bytestring.
805) 
806)         This is a helper function for hypothesis testing.
807) 
808)         References:
809) 
810)           * [David R. MacIver: Another invariant to test for
811)             encoders][DECODE_ENCODE]
812) 
813)         [DECODE_ENCODE]: https://hypothesis.works/articles/canonical-serialization/
814) 
815)         """
816)         unstringed, trailer = ssh_agent.SSHAgentClient.unstring_prefix(data)
817)         assert not trailer
818)         return ssh_agent.SSHAgentClient.string(unstringed)
819) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

820) 
821) class TestShellExportScriptParsing:
822)     """Test the shell export script parsing utility function."""
823) 
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

824)     @Parametrize.SH_EXPORT_LINES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

825)     def test_sh_export_line_parsing(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

826)         self, line: str, env_name: str, value: str | None
827)     ) -> None:
Marco Ricci Fix broken links in the doc...

Marco Ricci authored 11 months ago

828)         """[`tests.data.callables.parse_sh_export_line`][] works."""
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

829)         if value is not None:
830)             assert (
831)                 callables.parse_sh_export_line(line, env_name=env_name)
832)                 == value
833)             )
834)         else:
835)             with pytest.raises(ValueError, match="Cannot parse sh line:"):
836)                 callables.parse_sh_export_line(line, env_name=env_name)
837) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

838) 
839) class TestGracefulFailureForSSHAuthSock:
840)     """Test the `posix` socket provider if `SSH_AUTH_SOCK` is unset."""
841) 
Marco Ricci Remove the remaining ordina...

Marco Ricci authored 1 year ago

842)     def test_constructor_posix_no_ssh_auth_sock(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

843)         self,
844)         skip_if_no_af_unix_support: None,
845)     ) -> None:
846)         """Abort if the running agent cannot be located on POSIX."""
847)         del skip_if_no_af_unix_support
848)         posix_handler = socketprovider.SocketProvider.resolve("posix")
849)         with pytest.MonkeyPatch.context() as monkeypatch:
850)             monkeypatch.delenv("SSH_AUTH_SOCK", raising=False)
851)             with pytest.raises(
852)                 KeyError, match="SSH_AUTH_SOCK environment variable"
853)             ):
854)                 posix_handler()
855) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

856) 
857) class TestSSHProtocolDatatypes(TestStaticFunctionality):
858)     """Tests for the utility functions for the SSH protocol datatypes."""
859) 
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

860)     @Parametrize.UINT32_INPUT
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

861)     def test_uint32(self, input: int, expected: bytes | bytearray) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

862)         """`uint32` encoding works."""
863)         uint32 = ssh_agent.SSHAgentClient.uint32
864)         assert uint32(input) == expected
865) 
866)     @hypothesis.given(strategies.integers(min_value=0, max_value=0xFFFFFFFF))
867)     @hypothesis.example(0xDEADBEEF).via("manual, pre-hypothesis example")
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

868)     def test_uint32_from_number(self, num: int) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

869)         """`uint32` encoding works, starting from numbers."""
870)         uint32 = ssh_agent.SSHAgentClient.uint32
871)         assert int.from_bytes(uint32(num), "big", signed=False) == num
872) 
873)     @hypothesis.given(strategies.binary(min_size=4, max_size=4))
874)     @hypothesis.example(b"\xde\xad\xbe\xef").via(
875)         "manual, pre-hypothesis example"
876)     )
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

877)     def test_uint32_from_bytestring(self, bytestring: bytes) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

878)         """`uint32` encoding works, starting from length four byte strings."""
879)         uint32 = ssh_agent.SSHAgentClient.uint32
880)         assert (
881)             uint32(int.from_bytes(bytestring, "big", signed=False))
882)             == bytestring
883)         )
884) 
885)     @Parametrize.SSH_STRING_INPUT
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

886)     def test_string(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

887)         self, input: bytes | bytearray, expected: bytes | bytearray
888)     ) -> None:
889)         """SSH string encoding works."""
890)         string = ssh_agent.SSHAgentClient.string
891)         assert bytes(string(input)) == expected
892) 
893)     @hypothesis.given(strategies.binary(max_size=0x0001FFFF))
894)     @hypothesis.example(b"DEADBEEF" * 10000).via(
895)         "manual, pre-hypothesis example with highest order bit set"
896)     )
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

897)     def test_string_from_bytestring(self, bytestring: bytes) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

898)         """SSH string encoding works, starting from a byte string."""
899)         res = ssh_agent.SSHAgentClient.string(bytestring)
900)         assert res.startswith((b"\x00\x00", b"\x00\x01"))
901)         assert int.from_bytes(res[:4], "big", signed=False) == len(bytestring)
902)         assert res[4:] == bytestring
903) 
904)     @Parametrize.SSH_UNSTRING_INPUT
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

905)     def test_unstring(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

906)         self, input: bytes | bytearray, expected: bytes | bytearray
907)     ) -> None:
908)         """SSH string decoding works."""
909)         unstring = ssh_agent.SSHAgentClient.unstring
910)         unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
911)         assert bytes(unstring(input)) == expected
912)         assert tuple(bytes(x) for x in unstring_prefix(input)) == (
913)             expected,
914)             b"",
915)         )
916) 
917)     @hypothesis.given(strategies.binary(max_size=0x00FFFFFF))
918)     @hypothesis.example(b"\x00\x00\x00\x07ssh-rsa").via(
919)         "manual, pre-hypothesis example to attempt to detect double-decoding"
920)     )
921)     @hypothesis.example(b"\x00\x00\x00\x01").via(
922)         "detect no-op encoding via ill-formed SSH string"
923)     )
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

924)     def test_unstring_of_string_of_data(self, bytestring: bytes) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

925)         """SSH string decoding of encoded SSH strings works.
926) 
927)         References:
928) 
929)           * [David R. MacIver: The Encode/Decode invariant][ENCODE_DECODE]
930) 
931)         [ENCODE_DECODE]: https://hypothesis.works/articles/encode-decode-invariant/
932) 
933)         """
934)         string = ssh_agent.SSHAgentClient.string
935)         unstring = ssh_agent.SSHAgentClient.unstring
936)         unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
937)         encoded = string(bytestring)
938)         assert unstring(encoded) == bytestring
939)         assert unstring_prefix(encoded) == (bytestring, b"")
940)         trailing_data = b"  trailing data"
941)         encoded2 = string(bytestring) + trailing_data
942)         assert unstring_prefix(encoded2) == (bytestring, trailing_data)
943) 
944)     @hypothesis.given(
945)         strategies.binary(max_size=0x00FFFFFF).map(
946)             # Scoping issues, and the fact that staticmethod objects
947)             # (before class finalization) are not callable, necessitate
948)             # wrapping this staticmethod call in a lambda.
949)             lambda x: TestStaticFunctionality.as_ssh_string(x)  # noqa: PLW0108
950)         ),
951)     )
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

952)     def test_string_of_unstring_of_data(self, encoded: bytes) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

953)         """SSH string decoding of encoded SSH strings works.
954) 
955)         References:
956) 
957)           * [David R. MacIver: Another invariant to test for
958)             encoders][DECODE_ENCODE]
959) 
960)         [DECODE_ENCODE]: https://hypothesis.works/articles/canonical-serialization/
961) 
962)         """
963)         canonical_functions = [self.canonicalize1, self.canonicalize2]
964)         for canon1 in canonical_functions:
965)             for canon2 in canonical_functions:
966)                 assert canon1(encoded) == canon2(encoded)
967)                 assert canon1(canon2(encoded)) == canon1(encoded)
968) 
Marco Ricci Rearrange tests as per the...

Marco Ricci authored 1 year ago

969)     @Parametrize.UINT32_EXCEPTIONS
970)     def test_uint32_exceptions(
971)         self, input: int, exc_type: type[Exception], exc_pattern: str
972)     ) -> None:
973)         """`uint32` encoding fails for out-of-bound values."""
974)         uint32 = ssh_agent.SSHAgentClient.uint32
975)         with pytest.raises(exc_type, match=exc_pattern):
976)             uint32(input)
977) 
978)     @Parametrize.SSH_STRING_EXCEPTIONS
979)     def test_string_exceptions(
980)         self, input: Any, exc_type: type[Exception], exc_pattern: str
981)     ) -> None:
982)         """SSH string encoding fails for non-strings."""
983)         string = ssh_agent.SSHAgentClient.string
984)         with pytest.raises(exc_type, match=exc_pattern):
985)             string(input)
986) 
987)     @Parametrize.SSH_UNSTRING_EXCEPTIONS
988)     def test_unstring_exceptions(
989)         self,
990)         input: bytes | bytearray,
991)         exc_type: type[Exception],
992)         exc_pattern: str,
993)         has_trailer: bool,
994)         parts: tuple[bytes | bytearray, bytes | bytearray] | None,
995)     ) -> None:
996)         """SSH string decoding fails for invalid values."""
997)         unstring = ssh_agent.SSHAgentClient.unstring
998)         unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
999)         with pytest.raises(exc_type, match=exc_pattern):
1000)             unstring(input)
1001)         if has_trailer:
1002)             assert tuple(bytes(x) for x in unstring_prefix(input)) == parts
1003)         else:
1004)             with pytest.raises(exc_type, match=exc_pattern):
1005)                 unstring_prefix(input)
1006) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1007) 
1008) class TestSSHAgentSocketProviderRegistry:
1009)     """Tests for the SSH agent socket provider registry."""
1010) 
1011)     def test_resolve(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1012)         self,
1013)     ) -> None:
1014)         """Resolving entries in the socket provider registry works."""
1015)         registry = socketprovider.SocketProvider.registry
1016)         resolve = socketprovider.SocketProvider.resolve
1017)         lookup = socketprovider.SocketProvider.lookup
1018)         with pytest.MonkeyPatch.context() as monkeypatch:
1019)             monkeypatch.setitem(registry, "stub_agent", None)
1020)             assert callable(lookup("native"))
1021)             assert callable(resolve("native"))
1022)             assert lookup("stub_agent") is None
1023)             with pytest.raises(NotImplementedError):
1024)                 resolve("stub_agent")
1025) 
1026)     @Parametrize.RESOLVE_CHAINS
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1027)     def test_resolve_chains(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1028)         self,
1029)         terminal: Literal["unimplemented", "alias", "callable"],
1030)         chain: list[str],
1031)     ) -> None:
1032)         """Resolving a chain of providers works."""
1033)         registry = socketprovider.SocketProvider.registry
1034)         resolve = socketprovider.SocketProvider.resolve
1035)         lookup = socketprovider.SocketProvider.lookup
1036)         try:
1037)             implementation = resolve("native")
1038)         except NotImplementedError:  # pragma: no cover
1039)             pytest.fail("Native SSH agent socket provider is unavailable?!")
1040)         # TODO(the-13th-letter): Rewrite using structural pattern matching.
1041)         # https://the13thletter.info/derivepassphrase/latest/pycompatibility/#after-eol-py3.9
1042)         target = (
1043)             None
1044)             if terminal == "unimplemented"
1045)             else "native"
1046)             if terminal == "alias"
1047)             else implementation
1048)         )
1049)         with pytest.MonkeyPatch.context() as monkeypatch:
1050)             for link in chain:
1051)                 monkeypatch.setitem(registry, link, target)
1052)                 target = link
1053)             for link in chain:
1054)                 assert lookup(link) == (
1055)                     implementation if terminal != "unimplemented" else None
1056)                 )
1057)                 if terminal == "unimplemented":
1058)                     with pytest.raises(NotImplementedError):
1059)                         resolve(link)
1060)                 else:
1061)                     assert resolve(link) == implementation
1062) 
1063)     @hypothesis.given(
1064)         terminal=strategies.sampled_from([
1065)             "unimplemented",
1066)             "alias",
1067)             "callable",
1068)         ]),
1069)         chain=strategies.lists(
1070)             strategies.sampled_from([
1071)                 "c1",
1072)                 "c2",
1073)                 "c3",
1074)                 "c4",
1075)                 "c5",
1076)                 "c6",
1077)                 "c7",
1078)                 "c8",
1079)                 "c9",
1080)                 "c10",
1081)             ]),
1082)             min_size=1,
1083)             unique=True,
1084)         ),
1085)     )
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1086)     def test_resolve_chains2(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1087)         self,
1088)         terminal: Literal["unimplemented", "alias", "callable"],
1089)         chain: list[str],
1090)     ) -> None:
1091)         """Resolving a chain of providers works."""
1092)         registry = socketprovider.SocketProvider.registry
1093)         resolve = socketprovider.SocketProvider.resolve
1094)         lookup = socketprovider.SocketProvider.lookup
1095)         try:
1096)             implementation = resolve("native")
1097)         except NotImplementedError:  # pragma: no cover
1098)             hypothesis.note(f"{registry = }")
1099)             pytest.fail("Native SSH agent socket provider is unavailable?!")
1100)         # TODO(the-13th-letter): Rewrite using structural pattern matching.
1101)         # https://the13thletter.info/derivepassphrase/latest/pycompatibility/#after-eol-py3.9
1102)         target = (
1103)             None
1104)             if terminal == "unimplemented"
1105)             else "native"
1106)             if terminal == "alias"
1107)             else implementation
1108)         )
1109)         with pytest.MonkeyPatch.context() as monkeypatch:
1110)             for link in chain:
1111)                 monkeypatch.setitem(registry, link, target)
1112)                 target = link
1113)             for link in chain:
1114)                 assert lookup(link) == (
1115)                     implementation if terminal != "unimplemented" else None
1116)                 )
1117)                 if terminal == "unimplemented":
1118)                     with pytest.raises(NotImplementedError):
1119)                         resolve(link)
1120)                 else:
1121)                     assert resolve(link) == implementation
1122) 
1123)     @Parametrize.GOOD_ENTRY_POINTS
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1124)     def test_find_all_socket_providers(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1125)         self,
1126)         additional_entry_points: list[importlib.metadata.EntryPoint],
1127)     ) -> None:
1128)         """Finding all SSH agent socket providers works."""
1129)         resolve = socketprovider.SocketProvider.resolve
1130)         old_registry = socketprovider.SocketProvider.registry
1131)         with pytest_machinery.faked_entry_point_list(
1132)             additional_entry_points, remove_conflicting_entries=False
1133)         ) as names:
1134)             socketprovider.SocketProvider._find_all_ssh_agent_socket_providers()
1135)             for name in names:
1136)                 assert name in socketprovider.SocketProvider.registry
1137)                 assert resolve(name) in {
1138)                     callables.provider_entry_provider,
1139)                     *old_registry.values(),
1140)                 }
1141) 
1142)     @Parametrize.BAD_ENTRY_POINTS
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1143)     def test_find_all_socket_providers_errors(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1144)         self,
1145)         additional_entry_points: list[importlib.metadata.EntryPoint],
1146)     ) -> None:
1147)         """Finding faulty SSH agent socket providers raises errors."""
1148)         with contextlib.ExitStack() as stack:
1149)             stack.enter_context(
1150)                 pytest_machinery.faked_entry_point_list(
1151)                     additional_entry_points, remove_conflicting_entries=False
1152)                 )
1153)             )
1154)             stack.enter_context(pytest.raises(AssertionError))
1155)             socketprovider.SocketProvider._find_all_ssh_agent_socket_providers()
1156) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1157)     def test_already_registered(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1158)         self,
1159)     ) -> None:
1160)         """The registry forbids overwriting entries."""
1161)         registry = socketprovider.SocketProvider.registry.copy()
1162)         resolve = socketprovider.SocketProvider.resolve
1163)         register = socketprovider.SocketProvider.register
1164)         the_annoying_os = resolve("the_annoying_os")
1165)         posix = resolve("posix")
1166)         with pytest.MonkeyPatch.context() as monkeypatch:
1167)             monkeypatch.setattr(
1168)                 socketprovider.SocketProvider, "registry", registry
1169)             )
1170)             register("posix")(posix)
1171)             register("the_annoying_os")(the_annoying_os)
1172)             with pytest.raises(ValueError, match="already registered"):
1173)                 register("posix")(the_annoying_os)
1174)             with pytest.raises(ValueError, match="already registered"):
1175)                 register("the_annoying_os")(posix)
1176)             with pytest.raises(ValueError, match="already registered"):
1177)                 register("posix", "the_annoying_os_named_pipe")(posix)
1178)             with pytest.raises(ValueError, match="already registered"):
1179)                 register("the_annoying_os", "unix_domain")(the_annoying_os)
1180) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1181)     def test_resolve_non_existant_entries(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1182)         self,
1183)     ) -> None:
1184)         """Resolving a non-existant entry fails."""
1185)         new_registry = {
1186)             "posix": socketprovider.SocketProvider.registry["posix"],
1187)             "the_annoying_os": socketprovider.SocketProvider.registry[
1188)                 "the_annoying_os"
1189)             ],
1190)         }
1191)         with pytest.MonkeyPatch.context() as monkeypatch:
1192)             monkeypatch.setattr(
1193)                 socketprovider.SocketProvider, "registry", new_registry
1194)             )
1195)             with pytest.raises(socketprovider.NoSuchProviderError):
1196)                 socketprovider.SocketProvider.resolve("native")
1197) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1198)     def test_register_new_entry(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1199)         self,
1200)     ) -> None:
1201)         """Registering new entries works."""
1202) 
1203)         def socket_provider() -> _types.SSHAgentSocket:
1204)             raise AssertionError
1205) 
1206)         names = ["spam", "ham", "eggs", "parrot"]
1207)         new_registry = {
1208)             "posix": socketprovider.SocketProvider.registry["posix"],
1209)             "the_annoying_os": socketprovider.SocketProvider.registry[
1210)                 "the_annoying_os"
1211)             ],
1212)         }
1213)         with pytest.MonkeyPatch.context() as monkeypatch:
1214)             monkeypatch.setattr(
1215)                 socketprovider.SocketProvider, "registry", new_registry
1216)             )
1217)             assert not any(
1218)                 map(socketprovider.SocketProvider.registry.__contains__, names)
1219)             )
1220)             assert (
1221)                 socketprovider.SocketProvider.register(*names)(socket_provider)
1222)                 is socket_provider
1223)             )
1224)             assert all(
1225)                 map(socketprovider.SocketProvider.registry.__contains__, names)
1226)             )
1227)             assert all([
1228)                 socketprovider.SocketProvider.resolve(n) is socket_provider
1229)                 for n in names
1230)             ])
1231) 
1232)     @Parametrize.EXISTING_REGISTRY_ENTRIES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1233)     def test_register_old_entry(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1234)         self,
1235)         existing: str,
1236)     ) -> None:
1237)         """Registering old entries works."""
1238) 
1239)         provider = socketprovider.SocketProvider.resolve(existing)
1240)         new_registry = {
1241)             "posix": socketprovider.SocketProvider.registry["posix"],
1242)             "the_annoying_os": socketprovider.SocketProvider.registry[
1243)                 "the_annoying_os"
1244)             ],
1245)             "unix_domain": "posix",
1246)             "the_annoying_os_named_pipe": "the_annoying_os",
1247)         }
1248)         names = [
1249)             k
1250)             for k, v in socketprovider.SocketProvider.registry.items()
1251)             if v == existing
1252)         ]
1253)         with pytest.MonkeyPatch.context() as monkeypatch:
1254)             monkeypatch.setattr(
1255)                 socketprovider.SocketProvider, "registry", new_registry
1256)             )
1257)             assert not all(
1258)                 map(socketprovider.SocketProvider.registry.__contains__, names)
1259)             )
1260)             assert (
1261)                 socketprovider.SocketProvider.register(existing, *names)(
1262)                     provider
1263)                 )
1264)                 is provider
1265)             )
1266)             assert all(
1267)                 map(socketprovider.SocketProvider.registry.__contains__, names)
1268)             )
1269)             assert all([
1270)                 socketprovider.SocketProvider.resolve(n) is provider
1271)                 for n in [existing, *names]
1272)             ])
1273) 
1274) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1275) class TestAgentSigning:
1276)     """Test actually talking to the SSH agent: signing data."""
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1277) 
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1278)     @Parametrize.ALL_SSH_TEST_KEYS
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1279)     def test_sign_data_via_agent(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1280)         self,
1281)         ssh_agent_client_with_test_keys_loaded: ssh_agent.SSHAgentClient,
1282)         ssh_test_key_type: str,
1283)         ssh_test_key: data.SSHTestKey,
1284)     ) -> None:
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1285)         """Signing data with specific SSH keys works iff the key is suitable.
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1286) 
1287)         Single tests may abort early (skip) if the indicated key is not
1288)         loaded in the agent.  Presumably this means the key type is
1289)         unsupported.
1290) 
1291)         """
1292)         client = ssh_agent_client_with_test_keys_loaded
1293)         key_comment_pairs = {bytes(k): bytes(c) for k, c in client.list_keys()}
1294)         public_key_data = ssh_test_key.public_key_data
1295)         if public_key_data not in key_comment_pairs:  # pragma: no cover
1296)             pytest.skip(f"prerequisite {ssh_test_key_type} SSH key not loaded")
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1297)         if ssh_test_key.is_suitable():
1298)             assert (
1299)                 data.SSHTestKeyDeterministicSignatureClass.SPEC
1300)                 in ssh_test_key.expected_signatures
1301)             )
1302)             sig = ssh_test_key.expected_signatures[
1303)                 data.SSHTestKeyDeterministicSignatureClass.SPEC
1304)             ]
1305)             expected_signature = sig.signature
1306)             derived_passphrase = sig.derived_passphrase
1307)             signature = bytes(
1308)                 client.sign(payload=vault.Vault.UUID, key=public_key_data)
1309)             )
1310)             assert signature == expected_signature, (
1311)                 f"SSH signature mismatch ({ssh_test_key_type})"
1312)             )
1313)             signature2 = bytes(
1314)                 client.sign(payload=vault.Vault.UUID, key=public_key_data)
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1315)             )
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1316)             assert signature2 == expected_signature, (
1317)                 f"SSH signature mismatch ({ssh_test_key_type})"
1318)             )
1319)             assert (
1320)                 vault.Vault.phrase_from_key(public_key_data, conn=client)
1321)                 == derived_passphrase
1322)             ), f"SSH signature mismatch ({ssh_test_key_type})"
1323)         else:
1324)             assert (
1325)                 data.SSHTestKeyDeterministicSignatureClass.SPEC
1326)                 not in ssh_test_key.expected_signatures
1327)             )
1328)             assert not vault.Vault.is_suitable_ssh_key(
1329)                 public_key_data, client=None
1330)             ), f"Expected {ssh_test_key_type} key to be unsuitable in general"
1331)             if vault.Vault.is_suitable_ssh_key(
1332)                 public_key_data, client=client
1333)             ):  # pragma: no cover [external]
1334)                 potential_signatures = {
1335)                     sig_class: sig.signature
1336)                     for sig_class, sig in ssh_test_key.expected_signatures.items()
1337)                     if sig_class
1338)                     != data.SSHTestKeyDeterministicSignatureClass.SPEC
1339)                 }
1340)                 signature = bytes(
1341)                     client.sign(payload=vault.Vault.UUID, key=public_key_data)
1342)                 )
1343)                 assert signature in potential_signatures.values()
1344)             else:  # pragma: no cover [external]
1345)                 with pytest.raises(ValueError, match="unsuitable SSH key"):
1346)                     vault.Vault.phrase_from_key(public_key_data, conn=client)
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1347) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1348) 
1349) class TestSuitableKeys:
1350)     """Test actually talking to the SSH agent: determining suitable keys."""
1351) 
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1352)     @Parametrize.SSH_KEY_SELECTION
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1353)     def test_ssh_key_selector(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1354)         self,
1355)         monkeypatch: pytest.MonkeyPatch,
1356)         ssh_agent_client_with_test_keys_loaded: ssh_agent.SSHAgentClient,
1357)         key: bytes,
1358)         single: bool,
1359)     ) -> None:
1360)         """The key selector presents exactly the suitable keys.
1361) 
1362)         "Suitable" here means suitability for this SSH agent
1363)         specifically.
1364) 
1365)         """
1366)         client = ssh_agent_client_with_test_keys_loaded
1367) 
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1368)         monkeypatch.setattr(
1369)             ssh_agent.SSHAgentClient,
1370)             "list_keys",
1371)             callables.list_keys_singleton if single else callables.list_keys,
1372)         )
1373)         raw_keys_list = (
1374)             callables.list_keys_singleton()
1375)             if single
1376)             else callables.list_keys()
1377)         )
1378)         keys = [
1379)             pair.key
1380)             for pair in raw_keys_list
1381)             if vault.Vault.is_suitable_ssh_key(pair.key, client=client)
1382)         ]
1383)         n = len(keys)
1384)         if single or n == 1:
1385)             input_text = "yes\n"
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1386)             text = "Use this key? yes\n"
1387)         else:
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1388)             input_text = f"{1 + keys.index(key)}\n"
1389)             text = (
1390)                 f"Your selection? (1-{n}, leave empty to abort): {input_text}"
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1391)             )
1392)         b64_key = base64.standard_b64encode(key).decode("ASCII")
1393) 
1394)         @click.command()
1395)         def driver() -> None:
1396)             """Call [`cli_helpers.select_ssh_key`][] directly, as a command."""
1397)             key = cli_helpers.select_ssh_key(client)
1398)             click.echo(base64.standard_b64encode(key).decode("ASCII"))
1399) 
1400)         runner = machinery.CliRunner(mix_stderr=True)
1401)         result = runner.invoke(
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1402)             driver, [], input=input_text, catch_exceptions=True
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1403)         )
1404)         for snippet in ("Suitable SSH keys:\n", text, f"\n{b64_key}\n"):
1405)             assert result.clean_exit(output=snippet), "expected clean exit"
1406) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1407) 
1408) class TestConstructorFailures:
1409)     """Test actually talking to the SSH agent: constructor failures."""
1410) 
1411)     def test_constructor_bad_running_agent(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1412)         self,
1413)         running_ssh_agent: data.RunningSSHAgentInfo,
1414)     ) -> None:
1415)         """Fail if the agent address is invalid."""
1416)         with pytest.MonkeyPatch.context() as monkeypatch:
1417)             new_socket_name = (
1418)                 running_ssh_agent.socket + "~"
1419)                 if isinstance(running_ssh_agent.socket, str)
1420)                 else "<invalid//address>"
1421)             )
1422)             monkeypatch.setenv("SSH_AUTH_SOCK", new_socket_name)
1423)             with pytest.raises(OSError):  # noqa: PT011
1424)                 ssh_agent.SSHAgentClient()
1425) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1426)     def test_constructor_no_af_unix_support(self) -> None:
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1427)         """Fail without [`socket.AF_UNIX`][] support."""
1428)         assert "posix" in socketprovider.SocketProvider.registry
1429)         with pytest.MonkeyPatch.context() as monkeypatch:
1430)             monkeypatch.setenv("SSH_AUTH_SOCK", "the value doesn't matter")
1431)             monkeypatch.delattr(socket, "AF_UNIX", raising=False)
1432)             with pytest.raises(
1433)                 NotImplementedError,
1434)                 match="UNIX domain sockets",
1435)             ):
1436)                 ssh_agent.SSHAgentClient(socket="posix")
1437) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1438)     def test_no_ssh_agent_socket_provider_available(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1439)         self,
1440)     ) -> None:
1441)         """Fail if no SSH agent socket provider is available."""
1442)         with pytest.MonkeyPatch.context() as monkeypatch:
1443)             monkeypatch.setitem(
1444)                 socketprovider.SocketProvider.registry, "stub_agent", None
1445)             )
1446)             with pytest.raises(ExceptionGroup) as excinfo:
1447)                 ssh_agent.SSHAgentClient(
1448)                     socket=["stub_agent", "stub_agent", "stub_agent"]
1449)                 )
1450)             assert all([
1451)                 isinstance(e, NotImplementedError)
1452)                 for e in excinfo.value.exceptions
1453)             ])
1454) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1455) 
1456) class TestOtherConstructorFeatures:
1457)     """Test actually talking to the SSH agent: other constructor features."""
1458) 
1459)     def test_explicit_socket(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1460)         self,
1461)         spawn_ssh_agent: data.SpawnedSSHAgentInfo,
1462)     ) -> None:
1463)         conn = spawn_ssh_agent.client._connection
1464)         ssh_agent.SSHAgentClient(socket=conn)
1465) 
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1466) 
1467) class TestAgentErrorResponses:
1468)     """Test actually talking to the SSH agent: errors from the SSH agent."""
1469) 
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1470)     class Request(NamedTuple):
1471)         """A request for the SSH agent protocol.
1472) 
1473)         Attributes:
1474)             code:
1475)                 The expected request code.
1476)             payload:
1477)                 The expected payload.  Optional.
1478) 
1479)         """
1480) 
1481)         code: _types.SSH_AGENTC
1482)         """"""
1483)         payload: bytes | None
1484)         """"""
1485) 
1486)     class Response(NamedTuple):
1487)         """A response for the SSH agent protocol.
1488) 
1489)         Attributes:
1490)             code:
1491)                 The desired response code.
1492)             payload:
1493)                 The desired response payload.
1494) 
1495)         """
1496) 
1497)         code: _types.SSH_AGENT
1498)         """"""
1499)         payload: bytes
1500)         """"""
1501) 
1502)     def _make_request_stub(
1503)         self,
1504)         request_response_map: Mapping[Request, Response],
1505)         /,
1506)     ) -> data.RequestFunc:
1507)         """Return a stubbed SSH agent client `request` function.
1508) 
1509)         Args:
1510)             request_response_map:
1511)                 A map of request/response pairs.
1512) 
1513)         """
1514) 
1515)         def request(
1516)             request_code: int | _types.SSH_AGENTC,
1517)             payload: bytes | bytearray,
1518)             /,
1519)             *,
1520)             response_code: Iterable[int | _types.SSH_AGENT]
1521)             | int
1522)             | _types.SSH_AGENT
1523)             | None = None,
1524)         ) -> tuple[int, bytes | bytearray] | bytes | bytearray:
1525)             request_code = _types.SSH_AGENTC(request_code)
1526)             response_code = (
1527)                 frozenset({_types.SSH_AGENT.SUCCESS})
1528)                 if response_code is None
1529)                 else frozenset({_types.SSH_AGENT(response_code)})
1530)                 if isinstance(response_code, (int, _types.SSH_AGENT))
1531)                 else frozenset(map(_types.SSH_AGENT, response_code))
1532)             )
1533)             response_ = request_response_map.get(
1534)                 self.Request(request_code, bytes(payload))
1535)             ) or request_response_map.get(self.Request(request_code, None))
1536)             if response_ is None:  # pragma: no cover [failsafe]
1537)                 raise ssh_agent.SSHAgentFailedError(
1538)                     _types.SSH_AGENT.FAILURE.value,
1539)                     "No prepared response for the request "
1540)                     f"({request_code!r}, {payload!r})".encode(),
1541)                 )
1542)             code, response = response_
1543)             if code not in response_code:
1544)                 raise ssh_agent.SSHAgentFailedError(code.value, response)
1545)             return response
1546) 
1547)         return request
1548) 
1549)     @contextlib.contextmanager
1550)     def _setup_agent_and_request_handler(
1551)         self, request_response_map: Mapping[Request, Response], /
1552)     ) -> Iterator[tuple[pytest.MonkeyPatch, ssh_agent.SSHAgentClient]]:
1553)         # TODO(the-13th-letter): Rewrite using parenthesized
1554)         # with-statements.
1555)         # https://the13thletter.info/derivepassphrase/latest/pycompatibility/#after-eol-py3.9
1556)         with contextlib.ExitStack() as stack:
1557)             monkeypatch = stack.enter_context(pytest.MonkeyPatch.context())
1558)             client = stack.enter_context(
1559)                 ssh_agent.SSHAgentClient.ensure_agent_subcontext()
1560)             )
1561)             monkeypatch.setattr(
1562)                 client,
1563)                 "request",
1564)                 self._make_request_stub(request_response_map),
1565)             )
1566)             yield monkeypatch, client
1567) 
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1568)     @Parametrize.TRUNCATED_AGENT_RESPONSES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1569)     def test_truncated_server_response(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1570)         self,
1571)         running_ssh_agent: data.RunningSSHAgentInfo,
1572)         response: bytes,
1573)     ) -> None:
1574)         """Fail on truncated responses from the SSH agent."""
1575)         del running_ssh_agent
1576)         client = ssh_agent.SSHAgentClient()
1577)         response_stream = io.BytesIO(response)
1578) 
1579)         class PseudoSocket:
1580)             def sendall(self, *args: Any, **kwargs: Any) -> Any:  # noqa: ARG002
1581)                 return None
1582) 
1583)             def recv(self, *args: Any, **kwargs: Any) -> Any:
1584)                 return response_stream.read(*args, **kwargs)
1585) 
1586)         pseudo_socket = PseudoSocket()
1587)         with pytest.MonkeyPatch.context() as monkeypatch:
1588)             monkeypatch.setattr(client, "_connection", pseudo_socket)
1589)             with pytest.raises(EOFError):
1590)                 client.request(255, b"")
1591) 
1592)     @Parametrize.LIST_KEYS_ERROR_RESPONSES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1593)     def test_list_keys_error_responses(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1594)         self,
1595)         running_ssh_agent: data.RunningSSHAgentInfo,
1596)         response_code: _types.SSH_AGENT,
1597)         response: bytes | bytearray,
1598)         exc_type: type[Exception],
1599)         exc_pattern: str,
1600)     ) -> None:
1601)         """Fail on problems during key listing.
1602) 
1603)         Known problems:
1604) 
1605)           - The agent refuses, or otherwise indicates the operation
1606)             failed.
1607)           - The agent response is truncated.
1608)           - The agent response is overlong.
1609) 
1610)         """
1611)         del running_ssh_agent
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1612)         with self._setup_agent_and_request_handler({
1613)             self.Request(
1614)                 _types.SSH_AGENTC.REQUEST_IDENTITIES, None
1615)             ): self.Response(response_code, response),
1616)         }) as contexts:
1617)             _, client = contexts
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1618)             with pytest.raises(exc_type, match=exc_pattern):
1619)                 client.list_keys()
1620) 
1621)     @Parametrize.SIGN_ERROR_RESPONSES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1622)     def test_sign_error_responses(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1623)         self,
1624)         running_ssh_agent: data.RunningSSHAgentInfo,
1625)         key: bytes | bytearray,
1626)         check: bool,
1627)         response_code: _types.SSH_AGENT,
1628)         response: bytes | bytearray,
1629)         exc_type: type[Exception],
1630)         exc_pattern: str,
1631)     ) -> None:
1632)         """Fail on problems during signing.
1633) 
1634)         Known problems:
1635) 
1636)           - The key is not loaded into the agent.
1637)           - The agent refuses, or otherwise indicates the operation
1638)             failed.
1639) 
1640)         """
1641)         del running_ssh_agent
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1642)         Pair: TypeAlias = _types.SSHKeyCommentPair
1643)         com = b"no comment"
1644)         loaded_keys = [
1645)             Pair(v.public_key_data, com).toreadonly()
1646)             for v in data.SUPPORTED_KEYS.values()
1647)         ]
1648)         sign_payload = (
1649)             ssh_agent.SSHAgentClient.string(key)
1650)             + ssh_agent.SSHAgentClient.string(b"abc")
1651)             + ssh_agent.SSHAgentClient.uint32(0)
1652)         )
1653)         with self._setup_agent_and_request_handler({
1654)             self.Request(
1655)                 _types.SSH_AGENTC.SIGN_REQUEST, sign_payload
1656)             ): self.Response(response_code, response),
1657)         }) as contexts:
1658)             monkeypatch, client = contexts
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1659)             monkeypatch.setattr(client, "list_keys", lambda: loaded_keys)
1660)             with pytest.raises(exc_type, match=exc_pattern):
1661)                 client.sign(key, b"abc", check_if_key_loaded=check)
1662) 
1663)     @Parametrize.REQUEST_ERROR_RESPONSES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1664)     def test_request_error_responses(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1665)         self,
1666)         running_ssh_agent: data.RunningSSHAgentInfo,
1667)         request_code: _types.SSH_AGENTC,
1668)         response_code: _types.SSH_AGENT,
1669)         exc_type: type[Exception],
1670)         exc_pattern: str,
1671)     ) -> None:
1672)         """Fail on problems during signing.
1673) 
1674)         Known problems:
1675) 
1676)           - The key is not loaded into the agent.
1677)           - The agent refuses, or otherwise indicates the operation
1678)             failed.
1679) 
1680)         """
1681)         del running_ssh_agent
1682) 
1683)         # TODO(the-13th-letter): Rewrite using parenthesized
1684)         # with-statements.
1685)         # https://the13thletter.info/derivepassphrase/latest/pycompatibility/#after-eol-py3.9
1686)         with contextlib.ExitStack() as stack:
1687)             client = stack.enter_context(ssh_agent.SSHAgentClient())
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1688)             stack.enter_context(pytest.raises(exc_type, match=exc_pattern))
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1689)             client.request(request_code, b"", response_code=response_code)
1690) 
1691)     @Parametrize.QUERY_EXTENSIONS_MALFORMED_RESPONSES
Marco Ricci Regroup the CLI and SSH age...

Marco Ricci authored 1 year ago

1692)     def test_query_extensions_malformed_responses(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1693)         self,
1694)         running_ssh_agent: data.RunningSSHAgentInfo,
1695)         response_data: bytes,
1696)     ) -> None:
1697)         """Fail on malformed responses while querying extensions."""
1698)         del running_ssh_agent
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1699)         with self._setup_agent_and_request_handler({
1700)             self.Request(
Marco Ricci Ensure that `pytest` picks...

Marco Ricci authored 1 year ago

1701)                 _types.SSH_AGENTC.EXTENSION,
Marco Ricci Refactor the SSH agent tests

Marco Ricci authored 1 year ago

1702)                 ssh_agent.SSHAgentClient.string(b"query"),
1703)             ): self.Response(
1704)                 _types.SSH_AGENT.EXTENSION_RESPONSE, response_data
1705)             ),
1706)         }) as contexts:
1707)             _, client = contexts