diff --git a/HISTORY.rst b/HISTORY.rst index 1a55312..042b546 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -2,6 +2,15 @@ History ======= +1.8.0 (unreleased) +------------------ + +* Added methods for the instance secret fingerprint and for linking the instance secret with another DataMasque instance. +* Added ``rotate_instance_secret``, which replaces the instance secret with a newly generated one. +* Added ``get_current_instance_secret_links``, which returns the links that rotating the instance secret would end. + +Requires server version TBD + 1.7.0 (unreleased) ------------------ diff --git a/datamasque/client/__init__.py b/datamasque/client/__init__.py index f8ccc63..33a0cc6 100644 --- a/datamasque/client/__init__.py +++ b/datamasque/client/__init__.py @@ -20,6 +20,8 @@ DiscoveryConfigNotFoundError, FailedToStartError, IfmAuthError, + InstanceSecretLinkError, + InstanceSecretLinkErrorCode, InvalidDiscoveryConfigError, InvalidLibraryError, InvalidRulesetError, @@ -134,6 +136,16 @@ RulesetPlanPartialUpdateRequest, RulesetPlanUpdateRequest, ) +from datamasque.client.models.instance_secret import ( + InFlightSyncResult, + InstanceSecretEvent, + InstanceSecretEventId, + InstanceSecretEventKind, + InstanceSecretLinkRequest, + InstanceSecretLinkRequestVerification, + InstanceSecretLinkResponse, + InstanceSecretLinkResponseVerification, +) from datamasque.client.models.license import LicenseInfo, SwitchableLicenseMetadata from datamasque.client.models.project import ( Project, @@ -309,6 +321,16 @@ "IfmTokenInfo", "InDataDiscoveryConfig", "InDataDiscoveryRule", + "InFlightSyncResult", + "InstanceSecretEvent", + "InstanceSecretEventId", + "InstanceSecretEventKind", + "InstanceSecretLinkError", + "InstanceSecretLinkErrorCode", + "InstanceSecretLinkRequest", + "InstanceSecretLinkRequestVerification", + "InstanceSecretLinkResponse", + "InstanceSecretLinkResponseVerification", "InvalidDiscoveryConfigError", "InvalidLibraryError", "InvalidRulesetError", diff --git a/datamasque/client/base.py b/datamasque/client/base.py index d730282..c451309 100644 --- a/datamasque/client/base.py +++ b/datamasque/client/base.py @@ -73,7 +73,7 @@ def _build_session(verify_ssl: bool) -> requests.Session: # before logging on an error path, so that passwords, API tokens, and similar secrets don't # end up in user-visible logs when a request fails. # Applied to both outgoing request bodies and incoming response bodies (if JSON-parseable to a dict). -SENSITIVE_DATA_KEYS = ("password", "secret", "token", "key", "credential") +SENSITIVE_DATA_KEYS = ("password", "secret", "token", "key", "credential", "response_code") def _redact_sensitive(value: Any) -> Any: diff --git a/datamasque/client/dmclient.py b/datamasque/client/dmclient.py index 7f9914c..d2ce043 100644 --- a/datamasque/client/dmclient.py +++ b/datamasque/client/dmclient.py @@ -6,6 +6,7 @@ from datamasque.client.discovery_configs import DiscoveryConfigClient from datamasque.client.files import FileClient from datamasque.client.git import GitClient +from datamasque.client.instance_secret import InstanceSecretClient from datamasque.client.license import LicenseClient from datamasque.client.projects import ProjectClient from datamasque.client.resources import ResourceClient @@ -40,6 +41,7 @@ class DataMasqueClient( RGConfigClient, UserClient, SettingsClient, + InstanceSecretClient, ): """ Client for a DataMasque server instance. diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index ea6bd3f..b1f1e38 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -1,3 +1,4 @@ +import enum from typing import TYPE_CHECKING from requests import Response @@ -103,6 +104,51 @@ def __init__(self, message: str, *, response: Response, conflicts: "list[Resourc self.conflicts = conflicts +class InstanceSecretLinkErrorCode(enum.Enum): + """Why a step of instance secret linking failed.""" + + malformed_code = "malformed_code" + """The code is not a valid link code.""" + newer_link_format = "newer_link_format" + """The code was created by a newer version of DataMasque.""" + wrong_code_kind = "wrong_code_kind" + """A response code was given where a request code was expected, or the other way round.""" + invalid_public_key = "invalid_public_key" + """The request code contains a key that is not valid.""" + own_request = "own_request" + """The linking request was sent to the same DataMasque instance that generated it.""" + request_expired = "request_expired" + """The request code has expired. Create a new request code.""" + unknown_request = "unknown_request" + """The request that matches the response code was not found.""" + unseal_failed = "unseal_failed" + """The instance secret in the response code could not be opened.""" + invalid_secret = "invalid_secret" + """The response code contains an invalid instance secret.""" + same_secret = "same_secret" + """This DataMasque instance already has the same instance secret as the other DataMasque instance.""" + active_runs = "active_runs" + """Runs are in progress. Cancel them or wait for them to finish.""" + verification_stale = "verification_stale" + """The instance secret changed or was shared since the response code was verified. Verify the response again.""" + host_header_too_long = "host_header_too_long" + """The hostname used to access DataMasque is longer than 253 characters, the longest that DNS allows.""" + insecure_instance_secret = "insecure_instance_secret" + """The instance secret of this DataMasque instance is not secure enough to share. Rotate it, then try again.""" + + +class InstanceSecretLinkError(DataMasqueApiError): + """ + Raised when a step of instance secret linking fails, for example because a code has expired. + + The reason is on the `.code` attribute, and the message says what to do next. + """ + + def __init__(self, message: str, *, code: InstanceSecretLinkErrorCode, response: Response) -> None: + super().__init__(message, response=response) + self.code = code + + class DataMasqueTransportError(DataMasqueException): """ Raised when a request to the DataMasque server fails before any response is received. diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py new file mode 100644 index 0000000..69ec276 --- /dev/null +++ b/datamasque/client/instance_secret.py @@ -0,0 +1,215 @@ +from typing import Optional + +from requests import Response + +from datamasque.client.base import BaseClient +from datamasque.client.exceptions import InstanceSecretLinkError, InstanceSecretLinkErrorCode +from datamasque.client.models.instance_secret import ( + InFlightSyncResult, + InstanceSecretEvent, + InstanceSecretLinkRequest, + InstanceSecretLinkRequestVerification, + InstanceSecretLinkResponse, + InstanceSecretLinkResponseVerification, +) + + +class InstanceSecretClient(BaseClient): + """ + Instance secret and instance secret linking API methods, mixed into `DataMasqueClient`. + + Linking gives two DataMasque instances the same instance secret, so that they produce the same hashed output. + The joining instance creates a request code, the sharing instance accepts it and returns a response code, + and the joining instance accepts that response code and adopts the instance secret in it. + + Compare the fingerprints from both DataMasque instances before each accept step. + That comparison protects against a code being swapped on its way between the instances, + so when the codes travel through another person or system, compare the fingerprints over a separate channel. + + Example usage, with one client for each DataMasque instance: + + .. code-block:: python + + # On the joining instance: create a request code. + link_request = joining_client.create_instance_secret_link_request() + + # On the sharing instance: check the request fingerprint, then share the instance secret. + request_verification = sharing_client.verify_instance_secret_link_request(link_request.request_code) + assert request_verification.fingerprint == link_request.fingerprint + link_response = sharing_client.accept_instance_secret_link_request(link_request.request_code) + + # On the joining instance: check the response fingerprint, then adopt the instance secret. + response_verification = joining_client.verify_instance_secret_link_response(link_response.response_code) + assert response_verification.response_fingerprint == link_response.response_fingerprint + joining_client.accept_instance_secret_link_response( + link_response.response_code, + response_verification.verification_token, + ) + """ + + def get_instance_secret_fingerprint(self) -> str: + """ + Returns the fingerprint of the instance secret of this DataMasque instance. + + Two DataMasque instances have the same fingerprint only when they have the same instance secret. + """ + + response = self.make_request("GET", "/api/instance-secret/") + fingerprint: str = response.json()["fingerprint"] + return fingerprint + + def get_current_instance_secret_links(self) -> list[InstanceSecretEvent]: + """ + Returns the shares and adoptions that link this DataMasque instance with others, newest first. + + These are the links that `rotate_instance_secret` would end, and the list is empty after a rotation. + Another DataMasque instance can rotate or restore its own instance secret without telling this one, + so a link listed here may have ended already. + Requires an admin user, and works on every license type. + + Raises: + DataMasqueApiError: the user is not an admin user. + """ + + response = self.make_request("GET", "/api/instance-secret/current-links/") + return [InstanceSecretEvent.model_validate(link) for link in response.json()["links"]] + + def rotate_instance_secret(self) -> InFlightSyncResult: + """ + Replaces the instance secret of this DataMasque instance with a newly generated one. + + Requires an admin user. + Hashed output of masking runs and in-flight masking changes differs from before this call, + and the instance no longer has the same instance secret as any DataMasque instance it was linked with. + Once this succeeds, masking runs use the new instance secret. + Returns an `InFlightSyncResult` stating whether the IFM service successfully received the new instance secret. + If DataMasque fails to notify the IFM service, + a DataMasque restart is required for in-flight masking to use the new instance secret. + + Raises: + DataMasqueApiError: the user is not an admin user. + """ + + response = self.make_request("POST", "/api/instance-secret/rotate/") + return InFlightSyncResult(response.json()["in_flight_sync"]) + + def create_instance_secret_link_request(self) -> InstanceSecretLinkRequest: + """ + Creates a request code for joining the instance secret of another DataMasque instance. + + Pass the request code to `accept_instance_secret_link_request` on the sharing DataMasque instance. + The new request code replaces the pending one, which can then no longer be used. + """ + + response = self.make_request("POST", "/api/instance-secret/link/request/") + return InstanceSecretLinkRequest.model_validate(response.json()) + + def get_pending_instance_secret_link_request(self) -> Optional[InstanceSecretLinkRequest]: + """ + Returns the pending request code of this DataMasque instance. + + Returns `None` when there is no request, or it has expired, been cancelled or been used. + """ + + response = self.make_request("GET", "/api/instance-secret/link/request/", require_status_check=False) + if response.status_code == 404: + return None + + self._raise_for_status(response) + return InstanceSecretLinkRequest.model_validate(response.json()) + + def cancel_instance_secret_link_request(self) -> None: + """Cancels the pending request code, so that it can no longer be used, or does nothing if there is none.""" + + self.make_request("DELETE", "/api/instance-secret/link/request/") + + def verify_instance_secret_link_request(self, request_code: str) -> InstanceSecretLinkRequestVerification: + """ + Verifies a request code from the joining DataMasque instance, without changing anything. + + Call this on the sharing DataMasque instance. + + Raises: + ValueError: `request_code` is empty. + InstanceSecretLinkError: the request code is not valid. + """ + + response = self._post_link_step("/api/instance-secret/link/request/verify/", {"request_code": request_code}) + return InstanceSecretLinkRequestVerification.model_validate(response.json()) + + def accept_instance_secret_link_request(self, request_code: str) -> InstanceSecretLinkResponse: + """ + Shares the instance secret of this DataMasque instance with the instance that created the request code. + + Call this on the sharing DataMasque instance, + and pass the response code to `verify_instance_secret_link_response` on the joining instance. + + Raises: + ValueError: `request_code` is empty. + InstanceSecretLinkError: the request code is not valid. + """ + + response = self._post_link_step("/api/instance-secret/link/request/accept/", {"request_code": request_code}) + return InstanceSecretLinkResponse.model_validate(response.json()) + + def verify_instance_secret_link_response(self, response_code: str) -> InstanceSecretLinkResponseVerification: + """ + Verifies a response code from the sharing DataMasque instance, without changing anything. + + Call this on the joining DataMasque instance, + and pass the returned `verification_token` to `accept_instance_secret_link_response`. + + Raises: + ValueError: `response_code` is empty. + InstanceSecretLinkError: the response code is not valid. + """ + + response = self._post_link_step( + "/api/instance-secret/link/response/verify/", + {"response_code": response_code}, + ) + return InstanceSecretLinkResponseVerification.model_validate(response.json()) + + def accept_instance_secret_link_response(self, response_code: str, verification_token: str) -> InFlightSyncResult: + """ + Accepts the response code and adopts its instance secret as the instance secret of this DataMasque instance. + + Call this on the joining DataMasque instance, + with the `verification_token` from `verify_instance_secret_link_response` for the same response code. + Once this succeeds, masking runs use the new instance secret. + Returns an `InFlightSyncResult` stating whether the IFM service successfully received the new instance secret. + If DataMasque fails to notify the IFM service, + a DataMasque restart is required for in-flight masking to use the new instance secret. + + Raises: + ValueError: `response_code` or `verification_token` is empty. + InstanceSecretLinkError: the response code is not valid, runs are in progress, + or the instance secret changed or was shared since the response code was verified. + """ + + response = self._post_link_step( + "/api/instance-secret/link/response/accept/", + {"response_code": response_code, "verification_token": verification_token}, + ) + return InFlightSyncResult(response.json()["in_flight_sync"]) + + def _post_link_step(self, path: str, data: dict[str, str]) -> Response: + for name, value in data.items(): + if not value: + raise ValueError(f"`{name}` must not be empty.") + + response = self.make_request("POST", path, data=data, require_status_check=False) + if response.status_code == 400: + # A 400 that is not a link error, or has a code that this version of the client does not know, + # is raised as a plain API error. + try: + error = response.json() + code = InstanceSecretLinkErrorCode(error["code"]) + message = error["message"] + except (ValueError, KeyError, TypeError): + pass + else: + raise InstanceSecretLinkError(message, code=code, response=response) + + self._raise_for_status(response, request_data=data) + return response diff --git a/datamasque/client/models/instance_secret.py b/datamasque/client/models/instance_secret.py new file mode 100644 index 0000000..cb809c0 --- /dev/null +++ b/datamasque/client/models/instance_secret.py @@ -0,0 +1,106 @@ +"""Models for the instance secret of a DataMasque instance, and for linking it with another DataMasque instance.""" + +import enum +from datetime import datetime +from typing import NewType, Optional + +from pydantic import BaseModel, ConfigDict + +InstanceSecretEventId = NewType("InstanceSecretEventId", str) + + +class InstanceSecretEventKind(enum.Enum): + """Something that happened to the instance secret of a DataMasque instance.""" + + initialised = "initialised" + """The instance secret was created when DataMasque was installed.""" + rotated = "rotated" + """The instance secret was replaced with a new random one.""" + shared = "shared" + """The instance secret was sent to another DataMasque instance.""" + adopted = "adopted" + """The instance secret was replaced with the one from another DataMasque instance.""" + + +class InFlightSyncResult(enum.Enum): + """ + Whether the IFM service successfully received a new instance secret. + + Masking runs use the new instance secret with every result; only in-flight masking can need a DataMasque restart. + """ + + notified = "notified" + """The IFM service uses the new instance secret, and nothing more is needed.""" + notify_failed = "notify_failed" + """Restart DataMasque so that the IFM service uses the new instance secret.""" + file_write_failed = "file_write_failed" + """Restart DataMasque so that the IFM service uses the new instance secret.""" + + +class InstanceSecretEvent(BaseModel): + """An initialisation, rotation, share or adoption of the instance secret of a DataMasque instance.""" + + model_config = ConfigDict(extra="allow") + + id: InstanceSecretEventId + created_at: datetime + kind: InstanceSecretEventKind + peer_hostname: Optional[str] + """The hostname of the other DataMasque instance, or `None` when the event involved no other instance.""" + request_fingerprint: Optional[str] + """The fingerprint of the request code, or `None` when the event involved no other instance.""" + response_fingerprint: Optional[str] + """The fingerprint of the response code, or `None` when the event involved no other instance.""" + username: str + """The user who initiated the event.""" + + +class InstanceSecretLinkRequest(BaseModel): + """A request code that the joining DataMasque instance creates, to be pasted on the sharing instance.""" + + model_config = ConfigDict(extra="allow") + + request_code: str + fingerprint: str + """The request fingerprint, which must match the one shown on the sharing DataMasque instance.""" + expires_at: datetime + + +class InstanceSecretLinkRequestVerification(BaseModel): + """What the sharing DataMasque instance reads from a request code, for comparison before sharing.""" + + model_config = ConfigDict(extra="allow") + + hostname: str + """The reported hostname of the joining DataMasque instance.""" + fingerprint: str + """The request fingerprint, which must match the one shown on the joining DataMasque instance.""" + expires_at: datetime + """When the request expires.""" + datamasque_version: Optional[str] + """The version of DataMasque that created the request code. Will always be non-empty for production builds.""" + + +class InstanceSecretLinkResponse(BaseModel): + """A response code that the sharing DataMasque instance creates, to be pasted on the joining instance.""" + + model_config = ConfigDict(extra="allow") + + response_code: str + response_fingerprint: str + """The response fingerprint, which must match the one shown on the joining DataMasque instance.""" + + +class InstanceSecretLinkResponseVerification(BaseModel): + """What the joining DataMasque instance reads from a response code, for comparison before accepting it.""" + + model_config = ConfigDict(extra="allow") + + hostname: str + """The reported hostname of the sharing DataMasque instance.""" + response_fingerprint: str + """The response fingerprint, which must match the one shown on the sharing DataMasque instance.""" + links_ending: list[InstanceSecretEvent] + """The current links that accepting the response code will end.""" + verification_token: str + """Pass this when accepting the response code, which then fails if the instance secret changed or was shared since.""" diff --git a/docs/client.models.rst b/docs/client.models.rst index c103f25..61d1998 100644 --- a/docs/client.models.rst +++ b/docs/client.models.rst @@ -75,6 +75,14 @@ datamasque.client.models.ifm module :undoc-members: :show-inheritance: +datamasque.client.models.instance_secret module +----------------------------------------------- + +.. automodule:: datamasque.client.models.instance_secret + :members: + :undoc-members: + :show-inheritance: + datamasque.client.models.license module --------------------------------------- diff --git a/docs/client.rst b/docs/client.rst index e6cc2ae..eee9083 100644 --- a/docs/client.rst +++ b/docs/client.rst @@ -100,6 +100,14 @@ datamasque.client.ifm module :undoc-members: :show-inheritance: +datamasque.client.instance_secret module +---------------------------------------- + +.. automodule:: datamasque.client.instance_secret + :members: + :undoc-members: + :show-inheritance: + datamasque.client.license module -------------------------------- diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py new file mode 100644 index 0000000..dc8384b --- /dev/null +++ b/tests/test_instance_secret.py @@ -0,0 +1,304 @@ +"""Tests for `InstanceSecretClient` (instance secret fingerprint and instance secret linking).""" + +from datetime import datetime, timezone +from typing import Optional + +import pytest +import requests_mock + +from datamasque.client.exceptions import DataMasqueApiError, InstanceSecretLinkError, InstanceSecretLinkErrorCode +from datamasque.client.models.instance_secret import InFlightSyncResult, InstanceSecretEventKind + +LINK_URL = "http://test-server/api/instance-secret/link" + +LINK_REQUEST_JSON = { + "request_code": "DMLINK-REQUEST", + "fingerprint": "7KQ2-9MXA-3HDP-T0WZ", + "expires_at": "2026-10-30T12:00:00Z", +} + + +def event_json( + kind: str, + *, + peer_hostname: Optional[str] = None, + request_fingerprint: Optional[str] = None, + response_fingerprint: Optional[str] = None, +) -> dict: + return { + "id": "3f2b8c1e-5d4a-4e6f-9a7b-1c2d3e4f5a6b", + "created_at": "2026-10-30T11:00:00Z", + "kind": kind, + "peer_hostname": peer_hostname, + "request_fingerprint": request_fingerprint, + "response_fingerprint": response_fingerprint, + "username": "admin", + } + + +def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): + with requests_mock.Mocker() as m: + m.get("http://test-server/api/instance-secret/", json={"fingerprint": "7KQ2-9MXA-3HDP-T0WZ"}) + assert client.get_instance_secret_fingerprint() == "7KQ2-9MXA-3HDP-T0WZ" + + +def test_get_current_instance_secret_links_returns_the_links_in_order(client): + shared = event_json( + "shared", + peer_hostname="joining.example.com", + request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", + response_fingerprint="0F2A-9QXH-7RZW-B4ND", + ) + adopted = { + **event_json( + "adopted", + peer_hostname="sharing.example.com", + request_fingerprint="EBDV-ECVC-8QJ4-9XT5", + response_fingerprint="9GGM-DR1H-ETXX-41Q6", + ), + "id": "8a1c2d3e-4f5a-4b6c-8d7e-9f0a1b2c3d4e", + } + with requests_mock.Mocker() as m: + m.get("http://test-server/api/instance-secret/current-links/", json={"links": [shared, adopted]}) + links = client.get_current_instance_secret_links() + + assert [(link.kind, link.peer_hostname) for link in links] == [ + (InstanceSecretEventKind.shared, "joining.example.com"), + (InstanceSecretEventKind.adopted, "sharing.example.com"), + ] + assert links[0].created_at == datetime(2026, 10, 30, 11, 0, tzinfo=timezone.utc) + assert links[1].response_fingerprint == "9GGM-DR1H-ETXX-41Q6" + + +def test_get_current_instance_secret_links_returns_an_empty_list_when_there_are_none(client): + with requests_mock.Mocker() as m: + m.get("http://test-server/api/instance-secret/current-links/", json={"links": []}) + assert client.get_current_instance_secret_links() == [] + + +def test_get_current_instance_secret_links_by_a_user_who_is_not_an_admin_raises_data_masque_api_error(client): + with requests_mock.Mocker() as m: + m.get( + "http://test-server/api/instance-secret/current-links/", + json={"detail": "You do not have permission to perform this action."}, + status_code=403, + ) + with pytest.raises(DataMasqueApiError) as error_info: + client.get_current_instance_secret_links() + + assert error_info.value.response.status_code == 403 + + +@pytest.mark.parametrize("in_flight_sync", list(InFlightSyncResult)) +def test_rotate_instance_secret_returns_the_in_flight_sync_result(client, in_flight_sync): + with requests_mock.Mocker() as m: + m.post("http://test-server/api/instance-secret/rotate/", json={"in_flight_sync": in_flight_sync.value}) + result = client.rotate_instance_secret() + + assert m.call_count == 1 + assert result is in_flight_sync + + +def test_rotate_instance_secret_by_a_user_who_is_not_an_admin_raises_data_masque_api_error(client): + with requests_mock.Mocker() as m: + m.post( + "http://test-server/api/instance-secret/rotate/", + json={"detail": "You do not have permission to perform this action."}, + status_code=403, + ) + with pytest.raises(DataMasqueApiError) as error_info: + client.rotate_instance_secret() + + assert error_info.value.response.status_code == 403 + + +def test_create_instance_secret_link_request_posts_without_a_body(client): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/request/", json=LINK_REQUEST_JSON, status_code=201) + link_request = client.create_instance_secret_link_request() + + assert m.last_request.body is None + assert link_request.request_code == "DMLINK-REQUEST" + + +def test_get_pending_instance_secret_link_request_returns_the_request(client): + with requests_mock.Mocker() as m: + m.get(f"{LINK_URL}/request/", json=LINK_REQUEST_JSON) + link_request = client.get_pending_instance_secret_link_request() + + assert link_request is not None + assert link_request.fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert link_request.expires_at == datetime(2026, 10, 30, 12, 0, tzinfo=timezone.utc) + + +def test_get_pending_instance_secret_link_request_returns_none_on_404(client): + with requests_mock.Mocker() as m: + m.get(f"{LINK_URL}/request/", json={"detail": "There is no pending request code."}, status_code=404) + assert client.get_pending_instance_secret_link_request() is None + + +def test_get_pending_instance_secret_link_request_raises_on_403(client): + with requests_mock.Mocker() as m: + m.get(f"{LINK_URL}/request/", json={"detail": "Not licensed."}, status_code=403) + with pytest.raises(DataMasqueApiError): + client.get_pending_instance_secret_link_request() + + +def test_verify_instance_secret_link_request_returns_what_the_admins_compare(client): + with requests_mock.Mocker() as m: + m.post( + f"{LINK_URL}/request/verify/", + json={ + "hostname": "joining.example.com", + "fingerprint": "7KQ2-9MXA-3HDP-T0WZ", + "expires_at": "2026-10-30T12:00:00Z", + "datamasque_version": None, + }, + ) + verification = client.verify_instance_secret_link_request("DMLINK-REQUEST") + + assert m.last_request.json() == {"request_code": "DMLINK-REQUEST"} + assert verification.hostname == "joining.example.com" + assert verification.fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert verification.datamasque_version is None + + +def test_accept_instance_secret_link_request_returns_the_response_code(client): + with requests_mock.Mocker() as m: + m.post( + f"{LINK_URL}/request/accept/", + json={"response_code": "DMLINK-RESPONSE", "response_fingerprint": "ABCD-EFGH-JKMN-PQRS"}, + ) + link_response = client.accept_instance_secret_link_request("DMLINK-REQUEST") + + assert m.last_request.json() == {"request_code": "DMLINK-REQUEST"} + assert link_response.response_code == "DMLINK-RESPONSE" + + +# Every error code that the server's API schema lists for a linking step. +SERVER_LINK_ERROR_CODES = ( + "malformed_code", + "newer_link_format", + "wrong_code_kind", + "invalid_public_key", + "own_request", + "request_expired", + "unknown_request", + "unseal_failed", + "invalid_secret", + "same_secret", + "active_runs", + "verification_stale", + "host_header_too_long", + "insecure_instance_secret", +) + + +@pytest.mark.parametrize("error_code", SERVER_LINK_ERROR_CODES) +def test_a_failed_linking_step_raises_instance_secret_link_error_with_the_code(client, error_code): + message = "The linking step failed." + with requests_mock.Mocker() as m: + m.post( + f"{LINK_URL}/request/verify/", + json={"code": error_code, "message": message}, + status_code=400, + ) + with pytest.raises(InstanceSecretLinkError, match=message) as error_info: + client.verify_instance_secret_link_request("DMLINK-REQUEST") + + assert error_info.value.code is InstanceSecretLinkErrorCode(error_code) + assert error_info.value.response.status_code == 400 + + +@pytest.mark.parametrize( + "error_body", + [ + {"code": "a_code_from_a_newer_server", "message": "Something new went wrong."}, + {"detail": "Bad request."}, + ["Bad request."], + ], +) +def test_a_400_that_is_not_a_known_link_error_raises_data_masque_api_error(client, error_body): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/request/verify/", json=error_body, status_code=400) + with pytest.raises(DataMasqueApiError) as error_info: + client.verify_instance_secret_link_request("DMLINK-REQUEST") + + assert not isinstance(error_info.value, InstanceSecretLinkError) + assert error_info.value.response.status_code == 400 + + +def test_a_failed_response_step_does_not_log_the_response_code(client, caplog): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/response/accept/", json={"detail": "Server error."}, status_code=500) + with pytest.raises(DataMasqueApiError): + client.accept_instance_secret_link_response("DMLINK-RESPONSE", "token") + + assert "Request data was" in caplog.text + assert "DMLINK-RESPONSE" not in caplog.text + + +def test_a_linking_step_without_an_instance_secret_raises_data_masque_api_error(client): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/request/accept/", json={"detail": "No instance secret."}, status_code=503) + with pytest.raises(DataMasqueApiError) as error_info: + client.accept_instance_secret_link_request("DMLINK-REQUEST") + + assert not isinstance(error_info.value, InstanceSecretLinkError) + + +@pytest.mark.parametrize("event_kind", [InstanceSecretEventKind.shared, InstanceSecretEventKind.adopted]) +def test_verify_instance_secret_link_response_parses_the_links_ending(client, event_kind): + with requests_mock.Mocker() as m: + m.post( + f"{LINK_URL}/response/verify/", + json={ + "hostname": "other.example.com", + "response_fingerprint": "ABCD-EFGH-JKMN-PQRS", + "links_ending": [ + event_json( + event_kind.value, + peer_hostname="third.example.com", + request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", + response_fingerprint="WXYZ-2345-6789-BCDF", + ) + ], + "verification_token": "token", + }, + ) + verification = client.verify_instance_secret_link_response("DMLINK-RESPONSE") + + assert m.last_request.json() == {"response_code": "DMLINK-RESPONSE"} + link_ending = verification.links_ending[0] + assert link_ending.kind is event_kind + assert link_ending.peer_hostname == "third.example.com" + assert link_ending.request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert link_ending.response_fingerprint == "WXYZ-2345-6789-BCDF" + assert verification.verification_token == "token" + + +def test_accept_instance_secret_link_response_returns_the_in_flight_sync_result(client): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/response/accept/", json={"in_flight_sync": "notify_failed"}) + result = client.accept_instance_secret_link_response("DMLINK-RESPONSE", "token") + + assert m.last_request.json() == {"response_code": "DMLINK-RESPONSE", "verification_token": "token"} + assert result is InFlightSyncResult.notify_failed + + +@pytest.mark.parametrize( + ("method_name", "arguments"), + [ + ("verify_instance_secret_link_request", ("",)), + ("accept_instance_secret_link_request", ("",)), + ("verify_instance_secret_link_response", ("",)), + ("accept_instance_secret_link_response", ("", "token")), + ("accept_instance_secret_link_response", ("DMLINK-RESPONSE", "")), + ], +) +def test_an_empty_code_raises_value_error_before_any_request(client, method_name, arguments): + with requests_mock.Mocker() as m: + with pytest.raises(ValueError): + getattr(client, method_name)(*arguments) + + assert m.call_count == 0