Debian Codegraph @

tests/test_acme.py

raw
1 """Test ACME handler functionality."""
2
3 from socket import gaierror
4 from unittest.mock import Mock, patch
5
6 from acme import messages
7 import pytest
8 from requests.exceptions import RequestException
9
10 from hass_nabucasa import Cloud
11 from hass_nabucasa.acme import (
12 AcmeChallengeError,
13 AcmeClientError,
14 AcmeHandler,
15 AcmeJWSVerificationError,
16 _raise_if_jws_verification_failed,
17 )
18
19
20 @pytest.mark.parametrize(
21 "error",
22 [
23 messages.Error(
24 typ="urn:ietf:params:acme:error:malformed",
25 detail="JWS verification error",
26 ),
27 messages.Error(
28 typ="urn:ietf:params:acme:error:malformed",
29 detail="Unable to validate JWS",
30 ),
31 messages.Error(
32 typ="urn:ietf:params:acme:error:malformed",
33 detail="Unable to validate JWS :: Invalid Content-Type header on",
34 ),
35 ],
36 )
37 def test_raise_if_jws_verification_failed_should_raise(error):
38 """Test _raise_if_jws_verification_failed raises exception for JWS errors."""
39 with pytest.raises(AcmeJWSVerificationError, match="JWS verification failed"):
40 _raise_if_jws_verification_failed(error)
41
42
43 @pytest.mark.parametrize(
44 "error",
45 [
46 messages.Error(
47 typ="urn:ietf:params:acme:error:malformed",
48 detail="Some other malformed reason",
49 ),
50 messages.Error(
51 typ="about:blank",
52 detail="JWS verification error",
53 ),
54 ValueError("Some other error"),
55 ],
56 )
57 def test_raise_if_jws_verification_failed_should_not_raise(error):
58 """Test _raise_if_jws_verification_failed does not raise for non-JWS errors."""
59 _raise_if_jws_verification_failed(error)
60
61
62 def test_acme_handler_create_client_jws_error_existing_registration(
63 cloud: Cloud,
64 ) -> None:
65 """Test _create_client handles JWS error when registration exists."""
66 handler = AcmeHandler(cloud, ["test.example.com"], "[email protected]", Mock())
67
68 registration_data = '{"uri": "https://acme-v99.api.letsencrypt.org/acme/acct/1"}'
69
70 with (
71 patch("hass_nabucasa.acme.client.ClientV2") as mock_clientv2,
72 patch("hass_nabucasa.acme.client.ClientNetwork"),
73 patch("pathlib.Path.exists", return_value=True),
74 patch("pathlib.Path.read_text", return_value=registration_data),
75 patch("pathlib.Path.unlink"),
76 patch(
77 "hass_nabucasa.acme.messages.RegistrationResource.json_loads"
78 ) as mock_json_loads,
79 patch.object(handler, "_load_account_key"),
80 ):
81 mock_regr = Mock()
82 mock_regr.uri = "https://acme-v99.api.letsencrypt.org/acme/acct/1"
83 mock_json_loads.return_value = mock_regr
84
85 handler._account_jwk = Mock()
86
87 jws_error = messages.Error(
88 typ="urn:ietf:params:acme:error:malformed",
89 detail="JWS verification error",
90 )
91
92 mock_clientv2.get_directory.side_effect = jws_error
93
94 with pytest.raises(AcmeJWSVerificationError):
95 handler._create_client()
96
97
98 @pytest.mark.parametrize(
99 "error_detail,error_location",
100 [
101 ("Unable to validate JWS", "get_directory"),
102 ("JWS verification error", "new_account"),
103 ],
104 )
105 def test_acme_handler_create_client_jws_error_no_registration(
106 cloud: Cloud,
107 error_detail: str,
108 error_location: str,
109 ) -> None:
110 """Test _create_client handles JWS errors when no registration exists."""
111 handler = AcmeHandler(cloud, ["test.example.com"], "[email protected]", Mock())
112
113 with (
114 patch("hass_nabucasa.acme.client.ClientV2") as mock_clientv2,
115 patch("hass_nabucasa.acme.client.ClientNetwork"),
116 patch("pathlib.Path.exists", return_value=False),
117 patch.object(handler, "_load_account_key"),
118 patch("pathlib.Path.write_text"),
119 patch("pathlib.Path.chmod"),
120 ):
121 handler._account_jwk = Mock()
122
123 jws_error = messages.Error(
124 typ="urn:ietf:params:acme:error:malformed",
125 detail=error_detail,
126 )
127
128 if error_location == "get_directory":
129 mock_clientv2.get_directory.side_effect = jws_error
130 else:
131 mock_directory = Mock()
132 mock_directory.meta.terms_of_service = "https://example.com/tos"
133 mock_clientv2.get_directory.return_value = mock_directory
134
135 mock_client_instance = Mock()
136 mock_client_instance.directory = mock_directory
137 mock_clientv2.return_value = mock_client_instance
138 mock_client_instance.new_account.side_effect = jws_error
139
140 with pytest.raises(AcmeJWSVerificationError):
141 handler._create_client()
142
143
144 @pytest.mark.parametrize(
145 ("exception_type", "exception_args"),
146 [
147 (gaierror, ("getaddrinfo failed",)),
148 (RequestException, ("Connection timeout",)),
149 ],
150 )
151 def test_acme_handler_create_client_network_errors(
152 cloud: Cloud,
153 exception_type: type[Exception],
154 exception_args: tuple,
155 ) -> None:
156 """Test _create_client handles network errors (gaierror, RequestException)."""
157 handler = AcmeHandler(cloud, ["test.example.com"], "[email protected]", Mock())
158
159 with (
160 patch("hass_nabucasa.acme.client.ClientV2") as mock_clientv2,
161 patch("hass_nabucasa.acme.client.ClientNetwork"),
162 patch("pathlib.Path.exists", return_value=False),
163 patch.object(handler, "_load_account_key"),
164 ):
165 handler._account_jwk = Mock()
166
167 # Simulate network error during directory retrieval
168 mock_clientv2.get_directory.side_effect = exception_type(*exception_args)
169
170 with pytest.raises(AcmeClientError, match="Can't connect to ACME server"):
171 handler._create_client()
172
173
174 @pytest.mark.parametrize(
175 ("exception_type", "exception_args"),
176 [
177 (gaierror, ("DNS resolution failed",)),
178 (RequestException, ("Network unreachable",)),
179 ],
180 )
181 def test_acme_handler_create_order_network_errors(
182 cloud: Cloud,
183 exception_type: type[Exception],
184 exception_args: tuple,
185 ) -> None:
186 """Test _create_order handles network errors (gaierror, RequestException)."""
187 handler = AcmeHandler(cloud, ["test.example.com"], "[email protected]", Mock())
188
189 mock_client = Mock()
190 handler._acme_client = mock_client
191
192 # Simulate network error during order creation
193 mock_client.new_order.side_effect = exception_type(*exception_args)
194
195 with pytest.raises(AcmeChallengeError, match="Can't order a new ACME challenge"):
196 handler._create_order(b"test_csr")
197
198
199 @pytest.mark.parametrize(
200 ("exception_type", "exception_args"),
201 [
202 (gaierror, ("DNS lookup failed",)),
203 (RequestException, ("Connection error",)),
204 ],
205 )
206 def test_acme_handler_answer_challenge_network_errors(
207 cloud: Cloud,
208 exception_type: type[Exception],
209 exception_args: tuple,
210 ) -> None:
211 """Test _answer_challenge handles network errors (gaierror, RequestException)."""
212 handler = AcmeHandler(cloud, ["test.example.com"], "[email protected]", Mock())
213
214 mock_client = Mock()
215 handler._acme_client = mock_client
216
217 mock_challenge_handler = Mock()
218 mock_challenge_handler.challenge = Mock()
219 mock_challenge_handler.response = Mock()
220
221 # Simulate network error during challenge answer
222 mock_client.answer_challenge.side_effect = exception_type(*exception_args)
223
224 with pytest.raises(AcmeChallengeError, match="Can't accept ACME challenge"):
225 handler._answer_challenge(mock_challenge_handler)
226
227
228 @pytest.mark.parametrize(
229 ("exception_type", "exception_args"),
230 [
231 (gaierror, ("Connection error",)),
232 (RequestException, ("Timeout during poll",)),
233 ],
234 )
235 def test_acme_handler_deactivate_account_network_errors(
236 cloud: Cloud,
237 exception_type: type[Exception],
238 exception_args: tuple,
239 ) -> None:
240 """Test _deactivate_account handles network errors (gaierror, RequestException)."""
241 handler = AcmeHandler(cloud, ["test.example.com"], "[email protected]", Mock())
242
243 mock_client = Mock()
244 handler._acme_client = mock_client
245
246 registration_data = '{"uri": "https://acme-v99.api.letsencrypt.org/acme/acct/1"}'
247
248 with (
249 patch("pathlib.Path.exists", return_value=True),
250 patch("pathlib.Path.read_text", return_value=registration_data),
251 patch(
252 "hass_nabucasa.acme.messages.RegistrationResource.json_loads"
253 ) as mock_json_loads,
254 ):
255 mock_regr = Mock()
256 mock_json_loads.return_value = mock_regr
257
258 # Simulate network error during account deactivation
259 mock_client.deactivate_registration.side_effect = exception_type(
260 *exception_args
261 )
262
263 with pytest.raises(AcmeClientError, match="Can't deactivate account"):
264 handler._deactivate_account()