Distinguish errors when constructing SSH agent client
Marco Ricci

Marco Ricci commited on 2024-06-30 16:37:52
Zeige 2 geänderte Dateien mit 10 Einfügungen und 11 Löschungen.


If we cannot connect to the SSH agent, if it is because we cannot
determine its address, then raise a `KeyError`, otherwise pass the
original `OSError` through, instead of blindly converting everything to
`RuntimeError`.
... ...
@@ -56,6 +56,13 @@ class SSHAgentClient:
56 56
                 gives ample time for agent connections forwarded via
57 57
                 SSH on high-latency networks (e.g. Tor).
58 58
 
59
+        Raises:
60
+            KeyError:
61
+                The `SSH_AUTH_SOCK` environment was not found.
62
+            OSError:
63
+                There was an error setting up a socket connection to the
64
+                agent.
65
+
59 66
         """
60 67
         if socket is not None:
61 68
             self._connection = socket
... ...
@@ -69,19 +76,11 @@ class SSHAgentClient:
69 76
             # from coverage.
70 77
             if e.errno != errno.ENOTCONN:  # pragma: no cover
71 78
                 raise
72
-            try:
79
+            if 'SSH_AUTH_SOCK' not in os.environ:
80
+                raise KeyError('SSH_AUTH_SOCK environment variable')
73 81
             ssh_auth_sock = os.environ['SSH_AUTH_SOCK']
74
-            except KeyError as e:
75
-                raise RuntimeError(
76
-                    "Can't find running ssh-agent: missing SSH_AUTH_SOCK"
77
-                ) from e
78 82
             self._connection.settimeout(timeout)
79
-            try:
80 83
             self._connection.connect(ssh_auth_sock)
81
-            except FileNotFoundError as e:
82
-                raise RuntimeError(
83
-                    "Can't find running ssh-agent: unusable SSH_AUTH_SOCK"
84
-                ) from e
85 84
 
86 85
     def __enter__(self) -> Self:
87 86
         """Close socket connection upon context manager completion."""
... ...
@@ -36,7 +36,7 @@ class TestStaticFunctionality:
36 36
     def test_200_constructor_no_running_agent(self, monkeypatch):
37 37
         monkeypatch.delenv('SSH_AUTH_SOCK', raising=False)
38 38
         sock = socket.socket(family=socket.AF_UNIX)
39
-        with pytest.raises(RuntimeError,
39
+        with pytest.raises(KeyError,
40 40
                            match='SSH_AUTH_SOCK environment variable'):
41 41
             ssh_agent_client.SSHAgentClient(socket=sock)
42 42
 
43 43