s2auth 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. s2auth/__init__.py +3 -0
  2. s2auth/client/__init__.py +25 -0
  3. s2auth/client/connection_store.py +16 -0
  4. s2auth/client/dao.py +97 -0
  5. s2auth/client/main.py +7 -0
  6. s2auth/client/pairing.py +411 -0
  7. s2auth/client/pairing_core.py +504 -0
  8. s2auth/client/settings.py +43 -0
  9. s2auth/common/__init__.py +19 -0
  10. s2auth/common/connection_initiation.py +26 -0
  11. s2auth/common/exceptions.py +92 -0
  12. s2auth/common/hmac.py +228 -0
  13. s2auth/common/model/__init__.py +60 -0
  14. s2auth/common/model/s2_connect_common.py +62 -0
  15. s2auth/common/model/s2_connect_pairing.py +177 -0
  16. s2auth/common/model/s2_connect_session_init.py +98 -0
  17. s2auth/common/model/s2_connect_wan_endpoint_registry.py +78 -0
  18. s2auth/py.typed +0 -0
  19. s2auth/reference/__init__.py +0 -0
  20. s2auth/reference/client/main.py +249 -0
  21. s2auth/reference/server/__init__.py +0 -0
  22. s2auth/reference/server/connection.py +75 -0
  23. s2auth/reference/server/context.py +96 -0
  24. s2auth/reference/server/hooks.py +21 -0
  25. s2auth/reference/server/logging.py +51 -0
  26. s2auth/reference/server/main.py +106 -0
  27. s2auth/reference/server/pairing.py +248 -0
  28. s2auth/reference/server/run.py +45 -0
  29. s2auth/reference/server/versions.py +26 -0
  30. s2auth/server/__init__.py +12 -0
  31. s2auth/server/config.py +18 -0
  32. s2auth/server/connection_initiation.py +227 -0
  33. s2auth/server/context.py +326 -0
  34. s2auth/server/db.py +18 -0
  35. s2auth/server/hooks.py +225 -0
  36. s2auth/server/models.py +19 -0
  37. s2auth/server/pairing.py +375 -0
  38. s2auth/server/settings.py +48 -0
  39. s2auth/server/storage.py +31 -0
  40. s2auth/server/token_manager.py +125 -0
  41. s2auth-0.1.0.dist-info/METADATA +582 -0
  42. s2auth-0.1.0.dist-info/RECORD +45 -0
  43. s2auth-0.1.0.dist-info/WHEEL +4 -0
  44. s2auth-0.1.0.dist-info/entry_points.txt +4 -0
  45. s2auth-0.1.0.dist-info/licenses/LICENSE.md +202 -0
@@ -0,0 +1,504 @@
1
+ """Utilities for performing the pairing process of S2 as a client.
2
+ """
3
+
4
+ import json
5
+ import logging
6
+ from base64 import b64encode
7
+ from pathlib import Path
8
+ from typing import Any, Awaitable, Callable, List, Optional, cast
9
+ from uuid import UUID
10
+
11
+ import httpx
12
+
13
+ from s2auth.client.connection_store import ConnectionStore
14
+ from s2auth.common.exceptions import S2PairingError, VerificationError
15
+ from s2auth.common.hmac import (create_challenge, create_pairing_code,
16
+ create_response, verify_response, calculate_fingerprint_from_response_certificate)
17
+ from s2auth.common.model.s2_connect_common import (CommunicationProtocol,
18
+ Deployment,
19
+ EndpointDescription,
20
+ NodeDescription, NodeId,
21
+ Role)
22
+ from s2auth.common.model.s2_connect_session_init import \
23
+ InitiateSessionPostRequest
24
+ from s2auth.common.model.s2_connect_pairing import (
25
+ ConnectionDetails, FinalizePairingPostRequest,
26
+ HmacChallengeResponse, HmacHashingAlgorithm, NodeIdAlias,
27
+ PostConnectionDetailsPostRequest, RequestConnectionDetailsPostRequest,
28
+ RequestPairingPostRequest, RequestPairingPostResponse)
29
+
30
+ LOGGER = logging.getLogger(__name__)
31
+
32
+ HttpEventHook = Callable[..., Awaitable[None]]
33
+ HttpEventHooks = dict[str, list[HttpEventHook]]
34
+
35
+
36
+ def build_httpx_verify(verify_tls: bool, ssl_certfile: str | None) -> str | bool:
37
+ if not verify_tls:
38
+ return False
39
+ if isinstance(ssl_certfile, str) and ssl_certfile.strip() == "":
40
+ return True
41
+ if ssl_certfile is None:
42
+ return True
43
+ if not Path(ssl_certfile).is_file():
44
+ raise S2PairingError(f"Certificate file '{ssl_certfile}' not found")
45
+ return ssl_certfile
46
+
47
+
48
+ async def _log_request(request: httpx.Request) -> None:
49
+ if not LOGGER.isEnabledFor(logging.DEBUG):
50
+ return
51
+ LOGGER.debug("--- HTTP REQUEST ---")
52
+ LOGGER.debug(f"Call to {request.url}")
53
+ LOGGER.debug(f"Method: {request.method}")
54
+ LOGGER.debug(f"Headers: {request.headers}")
55
+ LOGGER.debug(f"Content: {request.content}")
56
+
57
+
58
+ async def _log_response(response: httpx.Response) -> None:
59
+ if not LOGGER.isEnabledFor(logging.DEBUG):
60
+ return
61
+ await response.aread()
62
+ LOGGER.debug("--- HTTP RESPONSE ---")
63
+ LOGGER.debug(f"Headers: {response.headers}")
64
+ LOGGER.debug(f"Content: {response.text}")
65
+ LOGGER.debug("--------------------\n")
66
+
67
+
68
+ HTTPX_HOOKS: HttpEventHooks = {"request": [_log_request], "response": [_log_response]}
69
+
70
+
71
+ def _resolve_http_hooks(
72
+ http_event_hooks: HttpEventHooks | None,
73
+ ) -> HttpEventHooks | None:
74
+ # Custom hooks fully override default debug hooks when provided.
75
+ if http_event_hooks is not None:
76
+ return http_event_hooks
77
+ # Avoid default hook overhead outside debug logging.
78
+ if LOGGER.isEnabledFor(logging.DEBUG):
79
+ return HTTPX_HOOKS
80
+ return None
81
+
82
+
83
+ async def perform_pairing(pairing_uri: str,
84
+ pairing_code: str | None,
85
+ storage: ConnectionStore,
86
+ role: str,
87
+ deployment: str,
88
+ supported_s2_message_versions: List[str],
89
+ supported_communication_protocols: List[str],
90
+ supportedHmacHashingAlgorithms: List[str],
91
+ s2_client_description: NodeDescription,
92
+ domain_name: str | None,
93
+ pairingS2NodeId: Optional[str] = None,
94
+ verify_tls: bool = True,
95
+ ssl_certfile: str | None = None,
96
+ http_event_hooks: HttpEventHooks | None = None) -> bool:
97
+ """
98
+ Preform the initial pairing
99
+ Attributes:
100
+ pairing_uri: the uri of the pairing endpoint
101
+ pairing_code: the pairing code: [pairing S2 node ID]-[pairing token] or [pairing token] if no code is given
102
+ storage: The storage backend for persisting pairing information.
103
+ role: The S2 role (CEM/RM) of the client.
104
+ deployment: The deployment (WAN/LAN) of this client
105
+ supported_s2_message_versions: List of versions of the S2 messages that the client supports
106
+ supported_communication_protocols: List of communication protocols (e.g. WebSockets) that the client supports
107
+ supportedHmacHashingAlgorithms: list of the supported hmac hashing algorithms
108
+ s2_client_description: Information about this client that will be send to the server,
109
+ such as brand, model, logo URL etc. Also contains a globally unique identifier
110
+ of the S2 node this client wants to pair to a node on the server
111
+ domain_name the domain name to use in a wan deployment
112
+ verify_tls: should ssl certificates be verified
113
+ ssl_certfile: optional CA/certificate bundle path used for TLS verification
114
+ """
115
+ # Create client HMAC challenge that the server needs to solve
116
+ # Create /requestPairing request body object
117
+ # Do the HTTP request
118
+ # Check the client HMAC challenge response
119
+ # Solve the server HMAC challenge
120
+ # Depending on the client/server role in the connection initiation of other S2 node either requestConnectionDetails or postConnectionDetails
121
+ # In any case, store the connection details in the database.
122
+
123
+ httpx_verify = build_httpx_verify(verify_tls, ssl_certfile)
124
+ event_hooks = _resolve_http_hooks(http_event_hooks)
125
+
126
+ # If no id given use id from client
127
+ s2_role: Role = Role(role)
128
+ s2_deployment: Deployment = Deployment(deployment)
129
+ communication_protocols: List[CommunicationProtocol] = list(map(CommunicationProtocol, supported_communication_protocols))
130
+ supported_hmac_hashing_algorithms: List[HmacHashingAlgorithm] = list(map(HmacHashingAlgorithm, supportedHmacHashingAlgorithms))
131
+ fingerprint: bytes | None = None
132
+
133
+ if s2_deployment == Deployment.WAN and (domain_name is None or domain_name.strip() == ""):
134
+ raise S2PairingError("WAN deployment requires domain_name.")
135
+
136
+ if pairingS2NodeId is not None:
137
+ pairing_s2_node_id, pairing_token = pairingS2NodeId, pairing_code
138
+ elif pairing_code is not None and '-' in pairing_code:
139
+ # Keep backward compatibility with "alias-token" pairing codes while
140
+ # preserving hyphens in aliases (for example UUID-based aliases).
141
+ pairing_s2_node_id, pairing_token = pairing_code.rsplit('-', 1)
142
+ else:
143
+ pairing_s2_node_id, pairing_token = None, pairing_code
144
+
145
+ if not pairing_token and s2_role == Role.RM:
146
+ raise S2PairingError("Access token required for pairing RM")
147
+ elif not pairing_token:
148
+ pairing_token = create_pairing_code()
149
+
150
+ target_node_id: NodeId | None = None
151
+ target_node_alias: NodeIdAlias | None = None
152
+ if pairing_s2_node_id is not None:
153
+ try:
154
+ # UUID values should be sent as full nodeId, not nodeIdAlias.
155
+ target_node_id = NodeId(UUID(pairing_s2_node_id))
156
+ except ValueError:
157
+ if pairing_s2_node_id.isalnum():
158
+ target_node_alias = NodeIdAlias(pairing_s2_node_id)
159
+ else:
160
+ raise S2PairingError(
161
+ "pairing_s2_node_id must be either a UUID (for nodeId) or an alphanumeric alias (for nodeIdAlias)."
162
+ )
163
+
164
+ # id logic seperately in case we get something like "-pairing_token" (i.e. an empty id but still combined)
165
+ s2_node_id: str = str(pairing_s2_node_id) if pairing_s2_node_id else str(s2_client_description.id.root)
166
+
167
+ # remove any previously stored connection details for this node id
168
+ storage.remove_connection_details(s2_node_id)
169
+
170
+ client_hmac_challenge = create_challenge()
171
+ request_payload: RequestPairingPostRequest = RequestPairingPostRequest(
172
+ clientNodeDescription=s2_client_description,
173
+ clientEndpointDescription=EndpointDescription(
174
+ name=f"{s2_client_description.userDefinedName if s2_client_description.userDefinedName else s2_client_description.brand} endpoint",
175
+ logoUrl=s2_client_description.logoUrl,
176
+ deployment=s2_deployment,
177
+ ),
178
+ nodeId=target_node_id,
179
+ nodeIdAlias=target_node_alias,
180
+ supportedCommunicationProtocols=communication_protocols,
181
+ supportedS2MessageVersions=supported_s2_message_versions,
182
+ supportedHmacHashingAlgorithms=supported_hmac_hashing_algorithms,
183
+ clientHmacChallenge=client_hmac_challenge,
184
+ forcePairing=True,
185
+ )
186
+ body = request_payload.model_dump_json(exclude_none=True)
187
+ try:
188
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=event_hooks) as client:
189
+ response = await client.post(f'{pairing_uri}/requestPairing', content=body, headers={"Content-Type": "application/json"})
190
+ response.raise_for_status()
191
+ if s2_deployment == Deployment.LAN and fingerprint is None:
192
+ fingerprint = calculate_fingerprint_from_response_certificate(response)
193
+ if fingerprint is None:
194
+ raise S2PairingError(
195
+ "Could not determine LAN certificate fingerprint from /requestPairing TLS connection. "
196
+ "Provide certificate_file or enable TLS cert access in the HTTP transport."
197
+ )
198
+
199
+ pairing_response: RequestPairingPostResponse = RequestPairingPostResponse.model_validate(response.json())
200
+
201
+ LOGGER.debug("--- HMAC: verifying server's response to client challenge ---")
202
+ if not verify_response(pairing_token=pairing_token,
203
+ challenge=client_hmac_challenge,
204
+ response=pairing_response.clientHmacChallengeResponse.root,
205
+ deployment = s2_deployment,
206
+ domain_name = domain_name,
207
+ fingerprint = fingerprint,
208
+ algorithm=pairing_response.selectedHmacHashingAlgorithm):
209
+ raise VerificationError("HMAC chellange does not match")
210
+ LOGGER.debug("--- HMAC: client challenge verified OK ---\n")
211
+ assert s2_role in (Role.RM, Role.CEM)
212
+
213
+ LOGGER.debug("--- HMAC: creating response to server challenge ---")
214
+ resp: HmacChallengeResponse = HmacChallengeResponse(b64encode(
215
+ create_response(pairing_token=pairing_token,
216
+ challenge=pairing_response.serverHmacChallenge,
217
+ deployment=s2_deployment,
218
+ domain_name=domain_name,
219
+ fingerprint=fingerprint,
220
+ algorithm=pairing_response.selectedHmacHashingAlgorithm)))
221
+ LOGGER.debug("--- HMAC: server challenge response created ---\n")
222
+
223
+ connection_details_dict: dict[str, Any] = {
224
+ "pairing_server_url": pairing_uri,
225
+ "client_s2_node_id": str(s2_client_description.id.root),
226
+ "supported_s2_message_versions": supported_s2_message_versions,
227
+ "supported_communication_protocols": supported_communication_protocols,
228
+ "supported_hmac_hashing_algorithms": supportedHmacHashingAlgorithms,
229
+ "verify_tls": verify_tls,
230
+ "ssl_certfile": ssl_certfile,
231
+ }
232
+ if s2_role == Role.RM:
233
+ rm_connection_details = await request_connection_details(
234
+ pairing_uri=pairing_uri,
235
+ attempt_id=pairing_response.pairingAttemptId.root,
236
+ hmacChallangeResponse=resp,
237
+ httpx_verify=httpx_verify,
238
+ http_event_hooks=event_hooks,
239
+ )
240
+ connection_details_dict |= {
241
+ "initiate_session_url": rm_connection_details.get("initiateSessionUrl"),
242
+ "access_token": rm_connection_details.get("accessToken"),
243
+ }
244
+ else:
245
+ assert s2_role == Role.CEM
246
+ # Post connection details logic for CEM role
247
+ initiateSessionUrl: str = f"{pairing_uri}/initiateSession"
248
+ access_token = b64encode(pairing_token.encode("utf-8")).decode("ascii")
249
+ connection_details_dict |= {
250
+ "initiate_session_url": initiateSessionUrl,
251
+ "access_token": access_token,
252
+ }
253
+ cem_connection_details = {
254
+ "initiateSessionUrl": initiateSessionUrl,
255
+ "accessToken": access_token,
256
+ }
257
+ response = await post_connection_details(pairing_uri=pairing_uri,
258
+ attempt_id=pairing_response.pairingAttemptId.root,
259
+ connection_details=ConnectionDetails.model_validate(cem_connection_details),
260
+ serverHmacChallangeResponse=resp,
261
+ httpx_verify=httpx_verify,
262
+ http_event_hooks=event_hooks)
263
+
264
+ # Store connection details in the database
265
+ storage.store_connection_details(
266
+ s2_node_id,
267
+ connection_details_dict,
268
+ )
269
+ final_response = await finalize_pairing(pairing_uri=pairing_uri,
270
+ attempt_id=pairing_response.pairingAttemptId.root,
271
+ success=True,
272
+ httpx_verify=httpx_verify,
273
+ http_event_hooks=event_hooks)
274
+
275
+ return (final_response.status_code == 204)
276
+ except httpx.HTTPError as e:
277
+ # Handle HTTP error
278
+ raise S2PairingError(f"Pairing connection failed: {e}") from e
279
+
280
+
281
+ async def request_connection_details(pairing_uri: str,
282
+ attempt_id: str,
283
+ hmacChallangeResponse: HmacChallengeResponse,
284
+ httpx_verify: bool | str,
285
+ http_event_hooks: HttpEventHooks | None = None) -> dict[str, Any]:
286
+ """
287
+ Request connection details from server
288
+ Attributes:
289
+ pairing_uri: the uri of the pairing endpoint
290
+ attempt_id: a unique id of this pairing attempt
291
+ serverHmacChallangeResponse: the response to the hmac challange received from the server
292
+ httpx_verify: httpx verify parameter for TLS verification
293
+ """
294
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=_resolve_http_hooks(http_event_hooks)) as client:
295
+ payload: RequestConnectionDetailsPostRequest = RequestConnectionDetailsPostRequest(
296
+ serverHmacChallengeResponse=hmacChallangeResponse
297
+ )
298
+ body = payload.model_dump_json(exclude_none=True)
299
+ headers = add_header(token=attempt_id)
300
+ response = await client.post(
301
+ f'{pairing_uri}/requestConnectionDetails',
302
+ headers=headers,
303
+ content=body,
304
+ )
305
+ response_json = response.json()
306
+ if not isinstance(response_json, dict):
307
+ raise S2PairingError("requestConnectionDetails returned invalid JSON payload")
308
+ return cast(dict[str, Any], response_json)
309
+
310
+
311
+ async def post_connection_details(pairing_uri: str,
312
+ attempt_id: str,
313
+ connection_details: ConnectionDetails,
314
+ serverHmacChallangeResponse: HmacChallengeResponse,
315
+ httpx_verify: bool | str,
316
+ http_event_hooks: HttpEventHooks | None = None) -> None:
317
+ """
318
+ Post connection details to server
319
+ Attributes:
320
+ pairing_uri: the uri of the pairing endpoint
321
+ attempt_id: a unique id of this pairing attempt
322
+ connection_details: details object for this connection in a ConnectionDetails object
323
+ serverHmacChallangeResponse: the response to the hmac challange received from teh server
324
+ httpx_verify: httpx verify parameter for TLS verification
325
+ """
326
+ payload: PostConnectionDetailsPostRequest = PostConnectionDetailsPostRequest(
327
+ serverHmacChallengeResponse=HmacChallengeResponse(serverHmacChallangeResponse.model_dump()),
328
+ connectionDetails=connection_details,
329
+ )
330
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=_resolve_http_hooks(http_event_hooks)) as client:
331
+ body = payload.model_dump_json(exclude_none=True)
332
+ headers = add_header(token=attempt_id)
333
+ response = await client.post(
334
+ f'{pairing_uri}/postConnectionDetails',
335
+ headers=headers,
336
+ content=body,
337
+ )
338
+ response.raise_for_status()
339
+ if not response.status_code == 204:
340
+ raise S2PairingError("postConnectionDetails failed")
341
+
342
+
343
+ async def finalize_pairing(pairing_uri: str,
344
+ attempt_id: str,
345
+ httpx_verify: bool | str,
346
+ success: Optional[bool] = None,
347
+ http_event_hooks: HttpEventHooks | None = None) -> httpx.Response:
348
+ """
349
+ Finalise the pairing process: post statusthe to finalizePairing endpoint
350
+ Attributes:
351
+ pairing_uri: the uri of the pairing endpoint
352
+ attempt_id: a unique id of this pairing attempt
353
+ success: did pairing succeed
354
+ httpx_verify: httpx verify parameter for TLS verification
355
+ """
356
+ finalize_pairing_postRequest = FinalizePairingPostRequest(success=success)
357
+
358
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=_resolve_http_hooks(http_event_hooks)) as client:
359
+ body = finalize_pairing_postRequest.model_dump_json(exclude_none=True)
360
+ headers = add_header(token=attempt_id)
361
+ response = await client.post(f'{pairing_uri}/finalizePairing',
362
+ headers=headers,
363
+ content=body)
364
+ return response
365
+
366
+
367
+ async def connect(storage: ConnectionStore,
368
+ pairing_s2_node_id: str,
369
+ http_event_hooks: HttpEventHooks | None = None) -> bool:
370
+ """
371
+ Sent command to terminate the pairing
372
+ Attributes:
373
+ storage: The storage backend for persisting pairing information.
374
+ pairing_s2_node_id id of the node to unpair
375
+ """
376
+ details = storage.load_connection_details(pairing_s2_node_id)
377
+ pairing_uri = details.get("pairing_server_url", None) if details else None
378
+ access_token = details.get("access_token", None) if details else None
379
+ verify_tls = details.get("verify_tls", None) if details else None
380
+ ssl_certfile = details.get("ssl_certfile", None) if details else None
381
+ client_s2_node_id = details.get("client_s2_node_id", None) if details else None
382
+
383
+ supported_s2_message_versions = details.get("supported_s2_message_versions", None) if details else None
384
+ supported_communication_protocols = details.get("supported_communication_protocols", None) if details else None
385
+ supported_hmac_hashing_algorithms = details.get("supported_hmac_hashing_algorithms", None) if details else None
386
+
387
+ if not details or pairing_uri is None or access_token is None or verify_tls is None or client_s2_node_id is None \
388
+ or supported_s2_message_versions is None or supported_communication_protocols is None or supported_hmac_hashing_algorithms is None:
389
+ raise S2PairingError(
390
+ f"Connection details for pairing_s2_node_id '{pairing_s2_node_id}' not found or incomplete."
391
+ )
392
+
393
+ httpx_verify = build_httpx_verify(verify_tls, ssl_certfile)
394
+ event_hooks = _resolve_http_hooks(http_event_hooks)
395
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=event_hooks) as client:
396
+ init_payload: InitiateSessionPostRequest = InitiateSessionPostRequest(
397
+ clientNodeId=NodeId(UUID(client_s2_node_id)),
398
+ serverNodeId=NodeId(UUID(pairing_s2_node_id)),
399
+ supportedS2MessageVersions=supported_s2_message_versions,
400
+ supportedCommunicationProtocols=supported_communication_protocols,
401
+ )
402
+
403
+ body = init_payload.model_dump_json(exclude_none=True)
404
+ headers = add_header(token=access_token)
405
+ response = await client.post(
406
+ f'{pairing_uri}/initiateSession',
407
+ headers=headers,
408
+ content=body
409
+ )
410
+ response.raise_for_status()
411
+ access_token = response.json().get("accessToken")
412
+ selected_s2_message_version = response.json().get("selectedS2MessageVersion")
413
+ selected_communication_protocol = response.json().get("selectedCommunicationProtocol")
414
+
415
+ assert selected_s2_message_version in supported_s2_message_versions
416
+ assert selected_communication_protocol in supported_communication_protocols
417
+ assert access_token is not None, "Access token not found in response from initiateSession"
418
+ storage.store_connection_details(
419
+ pairing_s2_node_id,
420
+ {"selected_s2_message_version": selected_s2_message_version,
421
+ "selected_communication_protocol": selected_communication_protocol,
422
+ "server_node_description": response.json().get("serverNodeDescription", None),
423
+ "server_endpoint_description": response.json().get("serverEndpointDescription", None),
424
+ "access_token": access_token,
425
+ }
426
+ )
427
+ confirmation = await confirmToken(
428
+ pairing_uri,
429
+ access_token,
430
+ httpx_verify=httpx_verify,
431
+ http_event_hooks=event_hooks,
432
+ )
433
+ return confirmation.status_code == 200
434
+
435
+
436
+ async def confirmToken(pairing_uri: str,
437
+ pemding_token: str,
438
+ httpx_verify: bool | str,
439
+ http_event_hooks: HttpEventHooks | None = None) -> httpx.Response:
440
+ """
441
+ Sent confirmation the token
442
+ Attributes:
443
+ pairing_uri: the uri of the initiateConnection endpoint
444
+ storage: The storage backend for persisting pairing information.
445
+ client_s2_node_id: The s2 node id of the client
446
+ pemding_token: the pending token to send
447
+ httpx_verify: httpx verify parameter for TLS verification
448
+ """
449
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=_resolve_http_hooks(http_event_hooks)) as client:
450
+ body = '{"accessToken": "' + pemding_token + '"}'
451
+ headers = add_header(token=pemding_token)
452
+ response = await client.post(f'{pairing_uri}/confirmAccessToken',
453
+ headers=headers,
454
+ content=body)
455
+ response.raise_for_status()
456
+ return response
457
+
458
+
459
+ async def unpair(storage: ConnectionStore,
460
+ pairing_s2_node_id: str,
461
+ http_event_hooks: HttpEventHooks | None = None) -> bool:
462
+ """
463
+ Sent command to terminate the pairing
464
+ Attributes:
465
+ storage: The storage backend for persisting pairing information.
466
+ pairing_s2_node_id id of the node to unpair
467
+ """
468
+
469
+ details = storage.load_connection_details(pairing_s2_node_id)
470
+ pairing_uri = details.get("pairing_server_url", None) if details else None
471
+ access_token = details.get("access_token", None) if details else None
472
+ verify_tls = details.get("verify_tls", None) if details else None
473
+ ssl_certfile = details.get("ssl_certfile", None) if details else None
474
+ client_s2_node_id = details.get("client_s2_node_id", None) if details else None
475
+ if not details or pairing_uri is None or access_token is None or verify_tls is None:
476
+ raise S2PairingError(
477
+ f"Connection details for pairing_s2_node_id '{pairing_s2_node_id}' not found or incomplete."
478
+ )
479
+ unpair_request = {
480
+ "clientNodeId": client_s2_node_id,
481
+ "serverNodeId": pairing_s2_node_id,
482
+ }
483
+
484
+ httpx_verify = build_httpx_verify(bool(verify_tls), ssl_certfile)
485
+ async with httpx.AsyncClient(verify=httpx_verify, event_hooks=_resolve_http_hooks(http_event_hooks)) as client:
486
+ headers = add_header(token=access_token)
487
+ response = await client.post(f'{pairing_uri}/unpair',
488
+ headers=headers,
489
+ content=json.dumps(unpair_request))
490
+ response.raise_for_status()
491
+ return response.status_code == 204
492
+
493
+
494
+ def add_header(token: Optional[str] = None) -> dict[str, str]:
495
+ """
496
+ Returns an appropriate header dicti for pairing requests
497
+ Attributes:
498
+ token: security bearer token e.g. pairing_attempt_id or accessToken
499
+ """
500
+
501
+ header = {"Content-Type": "application/json"}
502
+ if token:
503
+ header["Authorization"] = f"Bearer {token}"
504
+ return header
@@ -0,0 +1,43 @@
1
+ from pydantic import Field
2
+ from pydantic_settings import BaseSettings, SettingsConfigDict
3
+
4
+ from s2auth.common.model.s2_connect_common import CommunicationProtocol, Deployment, Role
5
+ from s2auth.common.model.s2_connect_pairing import HmacHashingAlgorithm
6
+
7
+
8
+ class ClientSettings(BaseSettings):
9
+ """Settings for the high-level S2 pairing client API.
10
+
11
+ Values can be provided directly or loaded from environment variables/.env files.
12
+ """
13
+
14
+ model_config = SettingsConfigDict(
15
+ env_file=[".env", ".env.docker"],
16
+ extra="ignore",
17
+ env_nested_delimiter="__",
18
+ )
19
+
20
+ server_url: str = "http://localhost"
21
+ pairing_token: str | None = None
22
+ pairing_s2_node_id: str | None = None
23
+ client_s2_node_id: str | None = None
24
+
25
+ client_role: Role = Role.RM
26
+ client_deployment: Deployment | None = None
27
+ domain_name: str | None = None
28
+
29
+ verify_tls: bool = True
30
+ ssl_certfile: str | None = Field(default=None)
31
+ storage_db_url: str = "sqlite:///connection_details.db"
32
+
33
+ supported_s2_versions: list[str] = Field(default_factory=lambda: ["v1"])
34
+ supported_communication_protocols: list[CommunicationProtocol] = Field(
35
+ default_factory=lambda: [CommunicationProtocol.WebSocket]
36
+ )
37
+ supported_hmac_hashing_algorithms: list[HmacHashingAlgorithm] = Field(
38
+ default_factory=lambda: [HmacHashingAlgorithm.SHA256]
39
+ )
40
+
41
+ cleint_brand: str = "ExampleHeatCo"
42
+ client_device_type: str = "Heatpump"
43
+ client_model_name: str = "SmartHeatPump X200"
@@ -0,0 +1,19 @@
1
+ """Public common helpers exposed for library users."""
2
+
3
+ from s2auth.common.hmac import (
4
+ create_challenge,
5
+ create_pairing_code,
6
+ create_response,
7
+ get_supported_algorithms,
8
+ select_algorithm,
9
+ verify_response,
10
+ )
11
+
12
+ __all__ = [
13
+ "create_pairing_code",
14
+ "create_challenge",
15
+ "create_response",
16
+ "verify_response",
17
+ "get_supported_algorithms",
18
+ "select_algorithm",
19
+ ]
@@ -0,0 +1,26 @@
1
+ from typing import TypeVar
2
+
3
+ from s2auth.common.model.s2_connect_common import CommunicationProtocol
4
+
5
+
6
+ _TItemType = TypeVar("_TItemType")
7
+
8
+
9
+ def select_compatible_item(
10
+ remote_items: list[_TItemType], local_items: list[_TItemType]
11
+ ) -> _TItemType | None:
12
+ overlapping_items = set(remote_items).intersection(set(local_items))
13
+ if not overlapping_items:
14
+ return None
15
+ return next(x for x in local_items if x in overlapping_items)
16
+
17
+
18
+ def select_version(remote_versions: list[str], local_versions: list[str]) -> str | None:
19
+ return select_compatible_item(remote_versions, local_versions)
20
+
21
+
22
+ def select_protocol(
23
+ remote_protocols: list[CommunicationProtocol],
24
+ local_protocols: list[CommunicationProtocol],
25
+ ) -> CommunicationProtocol | None:
26
+ return select_compatible_item(remote_protocols, local_protocols)
@@ -0,0 +1,92 @@
1
+ from abc import ABC
2
+ from typing import ClassVar, TypeAlias, Union
3
+ from s2auth.common.model.s2_connect_pairing import ErrorMessage as PairingErrorType
4
+ from s2auth.common.model.s2_connect_session_init import (
5
+ ErrorMessage as ConnectionErrorType,
6
+ )
7
+
8
+
9
+ ErrorType: TypeAlias = Union[PairingErrorType, ConnectionErrorType]
10
+
11
+
12
+ class S2ConnectError(Exception, ABC):
13
+ """Base exception for S2 Connect errors
14
+
15
+ Subclasses must define the error_type class attribute.
16
+ """
17
+
18
+ error_type: ClassVar[ErrorType]
19
+
20
+ def __init__(self, message: str):
21
+ super().__init__(message)
22
+ self.message = message
23
+
24
+ class S2PairingError(S2ConnectError):
25
+ """Base exception for S2 pairing errors"""
26
+ pass
27
+
28
+ class S2ConnectErrorWithDetails(S2ConnectError, ABC):
29
+ """Base exception for S2 Connect errors
30
+
31
+ Subclasses must define the error_type class attribute.
32
+ """
33
+
34
+ additional_info: str
35
+
36
+ def __init__(self, message: str, additional_info: str):
37
+ super().__init__(message)
38
+ self.additional_info = additional_info
39
+
40
+
41
+ class IncompatibleHmacHashingAlgorithms(S2ConnectError):
42
+ """Raised when no common HMAC hashing algorithm is found"""
43
+
44
+ error_type = PairingErrorType.IncompatibleHmacHashingAlgorithms
45
+
46
+
47
+ class VerificationError(S2ConnectError):
48
+ """Digest verification failed"""
49
+
50
+ error_type = PairingErrorType.Other # TODO should be something else.
51
+
52
+
53
+ class AccessError(S2ConnectError):
54
+ """Permission is denied to the client. This generally results in an HTTP 401 error."""
55
+
56
+ error_type = PairingErrorType.Other # TODO should be something else.
57
+
58
+
59
+ class PairingNotCompleteError(S2ConnectError):
60
+ """Pairing was not completed successfully before initiating a connection."""
61
+
62
+ error_type = ConnectionErrorType.NoLongerPaired # TODO should be something else.
63
+
64
+
65
+ class InvalidAccessTokenError(AccessError):
66
+ """Invalid AccessToken when authenticating a new s2 connection."""
67
+
68
+ error_type = ConnectionErrorType.Other # TODO should be something else
69
+
70
+
71
+ class InvalidServerError(AccessError):
72
+ """Unknown serverNodeId was specified for this server."""
73
+
74
+ error_type = ConnectionErrorType.Other # TODO should be something else
75
+
76
+
77
+ class NoCompatibleS2ConnectVersionError(S2ConnectErrorWithDetails):
78
+ """No compatible S2Connect versions are available between the client and server."""
79
+
80
+ error_type = ConnectionErrorType.Other # TODO should be something else
81
+
82
+
83
+ class NoCompatibleS2VersionError(S2ConnectErrorWithDetails):
84
+ """No compatible S2 versions are available between the client and server."""
85
+
86
+ error_type = ConnectionErrorType.IncompatibleS2MessageVersions
87
+
88
+
89
+ class NoCompatibleCommunitcationProtocol(S2ConnectErrorWithDetails):
90
+ """No compatible communication protocols are available between the client and server."""
91
+
92
+ error_type = ConnectionErrorType.IncompatibleCommunicationProtocols