Debian Codegraph @

tests/conftest.py

raw ◀ ▶
1 Debian patch touch this file
1 import logging
2 import os
3 import shutil
4 import threading
5 from pathlib import Path
6
7 import pytest
8 from icecream import ic
9 from icecream import install as install_ic
10 from invoke.vendor.lexicon import Lexicon
11
12 from paramiko import (
13 SFTP,
14 ECDSAKey,
15 Ed25519Key,
16 PKey,
17 RSAKey,
18 SFTPServer,
19 Transport,
20 )
21
22 from ._loop import LoopSocket
23 from ._stub_sftp import StubServer, StubSFTPServer
24 from ._util import _support
25
26 # Better print() for debugging - use ic()!
27 install_ic()
28 ic.configureOutput(includeContext=True)
29
30
31 # Perform logging by default; pytest will capture and thus hide it normally,
32 # presenting it on error/failure. (But also allow turning it off when doing
33 # very pinpoint debugging - e.g. using breakpoints, so you don't want output
34 # hiding enabled, but also don't want all the logging to gum up the terminal.)
35 if not os.environ.get("DISABLE_LOGGING", False):
36 logging.basicConfig(
37 level=logging.DEBUG,
38 # Also make sure to set up timestamping for more sanity when debugging.
39 format="[%(relativeCreated)s]\t%(levelname)s:%(name)s:%(message)s",
40 datefmt="%H:%M:%S",
41 )
42
43
44 def make_sftp_folder():
45 """
46 Ensure expected target temp folder exists on the remote end.
47
48 Will clean it out if it already exists.
49 """
50 # TODO: go back to using the sftp functionality itself for folder setup so
51 # we can test against live SFTP servers again someday. (Not clear if anyone
52 # is/was using the old capability for such, though...)
53 # TODO: something that would play nicer with concurrent testing (but
54 # probably e.g. using thread ID or UUIDs or something; not the "count up
55 # until you find one not used!" crap from before...)
56 # TODO: if we want to lock ourselves even harder into localhost-only
57 # testing (probably not?) could use tempdir modules for this for improved
58 # safety. Then again...why would someone have such a folder???
59 path = os.environ.get("TEST_FOLDER", "paramiko-test-target")
60 # Forcibly nuke this directory locally, since at the moment, the below
61 # fixtures only ever run with a locally scoped stub test server.
62 shutil.rmtree(path, ignore_errors=True)
63 # Then create it anew, again locally, for the same reason.
64 os.mkdir(path)
65 return path
66
67
68 @pytest.fixture # (scope='session')
69 def sftp_server():
70 """
71 Set up an in-memory SFTP server thread. Yields the client Transport/socket.
72
73 The resulting client Transport (along with all the server components) will
74 be the same object throughout the test session; the `sftp` fixture then
75 creates new higher level client objects wrapped around the client
76 Transport, as necessary.
77 """
78 # Sockets & transports
79 socks = LoopSocket()
80 sockc = LoopSocket()
81 sockc.link(socks)
82 # TODO: reuse with new server fixture if possible
83 tc = Transport(sockc)
84 ts = Transport(socks)
85 # Auth
86 host_key = RSAKey.from_private_key_file(_support("rsa.key"))
87 ts.add_server_key(host_key)
88 # Server setup
89 event = threading.Event()
90 server = StubServer()
91 ts.set_subsystem_handler("sftp", SFTPServer, StubSFTPServer)
92 ts.start_server(event, server)
93 # Wait (so client has time to connect? Not sure. Old.)
94 event.wait(1.0)
95 # Make & yield connection.
96 tc.connect(username="slowdive", password="pygmalion")
•97 try:
98 yield tc
99 finally:
100 tc.close()
101 ts.close()
102 socks.close()
103 sockc.close()
104
105
106 @pytest.fixture
107 def sftp(sftp_server):
108 """
109 Yield an SFTP client connected to the global in-session SFTP server thread.
110 """
111 # Client setup
112 client = SFTP.from_transport(sftp_server)
113 # Work in 'remote' folder setup (as it wants to use the client)
114 # TODO: how cleanest to make this available to tests? Doing it this way is
115 # marginally less bad than the previous 'global'-using setup, but not by
116 # much?
117 client.FOLDER = make_sftp_folder()
118 # Yield client to caller
119 yield client
120 # Clean up - as in make_sftp_folder, we assume local-only exec for now.
121 shutil.rmtree(client.FOLDER, ignore_errors=True)
122
123
124 # short type, full type, class, fingerprint, optional passphrase (will imply a
125 # 2nd copy of key which is passphrased)
126 key_data = [
127 [
128 "rsa",
129 "ssh-rsa",
130 RSAKey,
131 "SHA256:OhNL391d/beeFnxxg18AwWVYTAHww+D4djEE7Co0Yng",
132 None,
133 ],
134 [
135 "rsa",
136 "rsa-sha2-512",
137 RSAKey,
138 "SHA256:44W6xS7SyDLHqSar8WCiclOLpjn7OwuGz+vQ9OQ+Eaw",
139 b"secret",
140 ],
141 [
142 "ed25519",
143 "ssh-ed25519",
144 Ed25519Key,
145 "SHA256:J6VESFdD3xSChn8y9PzWzeF+1tl892mOy2TqkMLO4ow",
146 None,
147 ],
148 [
149 "ecdsa-256",
150 "ecdsa-sha2-nistp256",
151 ECDSAKey,
152 "SHA256:BrQG04oNKUETjKCeL4ifkARASg3yxS/pUHl3wWM26Yg",
153 None,
154 ],
155 # TODO: moar?
156 ]
157
158
159 @pytest.fixture(scope="session", params=key_data, ids=lambda x: x[1])
160 def keys(request):
161 """
162 Parameterize associated tests with an object for each known type of key,
163 with attributes:
164
165 - ``short_type``: short identifier, eg ``rsa`` or ``ecdsa-256``
166 - ``full_type``: the "message style" key identifier, eg ``ssh-rsa``, or
167 ``ecdsa-sha2-nistp256``.
168 - ``path``: a pathlib Path object to the fixture key file
169 - ``pkey``: PKey object
170 - ``pkey_with_cert``: PKey object with cert loaded (if applicable)
171 - ``expected_fp``: the expected fingerprint of said key
172 - ``passphrase``: if not ``None``, the passphrase this key requires.
173 """
174 short_type, full_type, key_class, fingerprint, passphrase = request.param
175 bag = Lexicon()
176 bag.short_type = short_type
177 bag.full_type = full_type
178 filename = short_type
179 if passphrase is not None:
180 filename += "-passphrased"
181 bag.path = Path(_support(f"{filename}.key"))
182 with bag.path.open() as fd:
183 bag.pkey = key_class.from_private_key(fd, password=passphrase)
184 # Second copy for things like equality-but-not-identity testing
185 with bag.path.open() as fd:
186 bag.pkey2 = key_class.from_private_key(fd, password=passphrase)
187 bag.expected_fp = fingerprint
188 # Also tack on the cert-bearing variant for some tests
189 cert = bag.path.with_suffix(".key-cert.pub")
190 bag.pkey_with_cert = (
191 PKey.from_path(cert, password=passphrase) if cert.exists() else None
192 )
193 bag.passphrase = passphrase
194 # Safety checks
195 assert bag.pkey.fingerprint == fingerprint
196 yield bag