From bfeaee925af8568f52608ba4d0579c68d26dc7e3 Mon Sep 17 00:00:00 2001 From: Colin Haywood Date: Sat, 31 Oct 2026 13:25:12 +1300 Subject: [PATCH 01/15] feat: add methods and models for instance secret linking --- HISTORY.rst | 7 + datamasque/client/__init__.py | 24 +++ datamasque/client/base.py | 2 +- datamasque/client/dmclient.py | 2 + datamasque/client/exceptions.py | 44 ++++ datamasque/client/instance_secret.py | 186 ++++++++++++++++ datamasque/client/models/instance_secret.py | 115 ++++++++++ docs/client.models.rst | 8 + docs/client.rst | 8 + tests/test_instance_secret.py | 228 ++++++++++++++++++++ 10 files changed, 623 insertions(+), 1 deletion(-) create mode 100644 datamasque/client/instance_secret.py create mode 100644 datamasque/client/models/instance_secret.py create mode 100644 tests/test_instance_secret.py diff --git a/HISTORY.rst b/HISTORY.rst index 1a55312..ae9633b 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -2,6 +2,13 @@ History ======= +1.8.0 (unreleased) +------------------ + +* Added methods for the instance secret fingerprint and for linking the instance secret with another DataMasque instance. + +Requires server version TBD + 1.7.0 (unreleased) ------------------ diff --git a/datamasque/client/__init__.py b/datamasque/client/__init__.py index f8ccc63..4469339 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,17 @@ RulesetPlanPartialUpdateRequest, RulesetPlanUpdateRequest, ) +from datamasque.client.models.instance_secret import ( + InFlightSyncResult, + InstanceSecretEvent, + InstanceSecretEventId, + InstanceSecretEventKind, + InstanceSecretLinkHistory, + InstanceSecretLinkRequest, + InstanceSecretLinkRequestVerification, + InstanceSecretLinkResponse, + InstanceSecretLinkResponseVerification, +) from datamasque.client.models.license import LicenseInfo, SwitchableLicenseMetadata from datamasque.client.models.project import ( Project, @@ -309,6 +322,17 @@ "IfmTokenInfo", "InDataDiscoveryConfig", "InDataDiscoveryRule", + "InFlightSyncResult", + "InstanceSecretEvent", + "InstanceSecretEventId", + "InstanceSecretEventKind", + "InstanceSecretLinkError", + "InstanceSecretLinkErrorCode", + "InstanceSecretLinkHistory", + "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..655bedd 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,49 @@ 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 or its history changed after 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.""" + + +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..843e239 --- /dev/null +++ b/datamasque/client/instance_secret.py @@ -0,0 +1,186 @@ +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, + InstanceSecretLinkHistory, + 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_instance_secret_link_history(self) -> InstanceSecretLinkHistory: + """Returns every event of the instance secret of this DataMasque instance, and the links that are current.""" + + response = self.make_request("GET", "/api/instance-secret/link/history/") + return InstanceSecretLinkHistory.model_validate(response.json()) + + 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 or its history changed after 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..8808a06 --- /dev/null +++ b/datamasque/client/models/instance_secret.py @@ -0,0 +1,115 @@ +"""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.""" + peer_fingerprint: Optional[str] + """The fingerprint compared with the other DataMasque instance, or `None` when the event involved no other instance.""" + username: str + """The user who initiated the event.""" + + +class InstanceSecretLinkHistory(BaseModel): + """The events of the instance secret of a DataMasque instance.""" + + model_config = ConfigDict(extra="allow") + + current_links: list[InstanceSecretEvent] + """The shares and adoptions that no later change to the instance secret has ended.""" + events: list[InstanceSecretEvent] + """Every event, newest first.""" + + +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 or its history has changed.""" 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..305044a --- /dev/null +++ b/tests/test_instance_secret.py @@ -0,0 +1,228 @@ +"""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, peer_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, + "peer_fingerprint": peer_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_instance_secret_link_history_parses_events(client): + shared = event_json("shared", peer_hostname="other.example.com", peer_fingerprint="ABCD-EFGH-JKMN-PQRS") + with requests_mock.Mocker() as m: + m.get(f"{LINK_URL}/history/", json={"current_links": [shared], "events": [shared, event_json("initialised")]}) + history = client.get_instance_secret_link_history() + + assert history.current_links[0].kind is InstanceSecretEventKind.shared + assert history.current_links[0].peer_hostname == "other.example.com" + assert [event.kind for event in history.events] == [ + InstanceSecretEventKind.shared, + InstanceSecretEventKind.initialised, + ] + + +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", +) + + +@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) + + +def test_verify_instance_secret_link_response_parses_the_links_ending(client): + 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("adopted", peer_hostname="third.example.com")], + "verification_token": "token", + }, + ) + verification = client.verify_instance_secret_link_response("DMLINK-RESPONSE") + + assert m.last_request.json() == {"response_code": "DMLINK-RESPONSE"} + assert verification.links_ending[0].kind is InstanceSecretEventKind.adopted + 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 From a78fd43e069c58b1cd50d94e4661e7a328ae8de1 Mon Sep 17 00:00:00 2001 From: Colin Haywood Date: Thu, 5 Nov 2026 12:57:20 +1300 Subject: [PATCH 02/15] feat: replace the event peer fingerprint with the request and response fingerprints --- datamasque/client/models/instance_secret.py | 6 ++++-- tests/test_instance_secret.py | 20 +++++++++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/datamasque/client/models/instance_secret.py b/datamasque/client/models/instance_secret.py index 8808a06..73ef956 100644 --- a/datamasque/client/models/instance_secret.py +++ b/datamasque/client/models/instance_secret.py @@ -47,8 +47,10 @@ class InstanceSecretEvent(BaseModel): kind: InstanceSecretEventKind peer_hostname: Optional[str] """The hostname of the other DataMasque instance, or `None` when the event involved no other instance.""" - peer_fingerprint: Optional[str] - """The fingerprint compared with 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.""" diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index 305044a..6b8c1aa 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -18,13 +18,20 @@ } -def event_json(kind: str, *, peer_hostname: Optional[str] = None, peer_fingerprint: Optional[str] = None) -> dict: +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, - "peer_fingerprint": peer_fingerprint, + "request_fingerprint": request_fingerprint, + "response_fingerprint": response_fingerprint, "username": "admin", } @@ -36,13 +43,20 @@ def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): def test_get_instance_secret_link_history_parses_events(client): - shared = event_json("shared", peer_hostname="other.example.com", peer_fingerprint="ABCD-EFGH-JKMN-PQRS") + shared = event_json( + "shared", + peer_hostname="other.example.com", + request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", + response_fingerprint="ABCD-EFGH-JKMN-PQRS", + ) with requests_mock.Mocker() as m: m.get(f"{LINK_URL}/history/", json={"current_links": [shared], "events": [shared, event_json("initialised")]}) history = client.get_instance_secret_link_history() assert history.current_links[0].kind is InstanceSecretEventKind.shared assert history.current_links[0].peer_hostname == "other.example.com" + assert history.current_links[0].request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert history.current_links[0].response_fingerprint == "ABCD-EFGH-JKMN-PQRS" assert [event.kind for event in history.events] == [ InstanceSecretEventKind.shared, InstanceSecretEventKind.initialised, From ce0cb0e8905b0733d31997ad44eacca637fec44e Mon Sep 17 00:00:00 2001 From: Colin Haywood Date: Thu, 5 Nov 2026 13:33:43 +1300 Subject: [PATCH 03/15] feat: add the insecure instance secret linking error code --- datamasque/client/exceptions.py | 2 ++ tests/test_instance_secret.py | 1 + 2 files changed, 3 insertions(+) diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index 655bedd..6c392eb 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -133,6 +133,8 @@ class InstanceSecretLinkErrorCode(enum.Enum): """The instance secret or its history changed after 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): diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index 6b8c1aa..c3afcdd 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -141,6 +141,7 @@ def test_accept_instance_secret_link_request_returns_the_response_code(client): "active_runs", "verification_stale", "host_header_too_long", + "insecure_instance_secret", ) From 1933a6f848dc07261b05da5fe93396561142dd15 Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Tue, 17 Nov 2026 11:27:49 +1300 Subject: [PATCH 04/15] feat: DM-5075 add rotate_instance_secret --- HISTORY.rst | 1 + datamasque/client/instance_secret.py | 19 +++++++++++++++++++ tests/test_instance_secret.py | 23 +++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/HISTORY.rst b/HISTORY.rst index ae9633b..817e42e 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -6,6 +6,7 @@ History ------------------ * 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. Requires server version TBD diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index e720334..6dc3784 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -57,6 +57,25 @@ def get_instance_secret_fingerprint(self) -> str: fingerprint: str = response.json()["fingerprint"] return fingerprint + 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. diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index a73c784..878c8e0 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -42,6 +42,29 @@ def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): assert client.get_instance_secret_fingerprint() == "7KQ2-9MXA-3HDP-T0WZ" +@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) From 71edcaf546efb55fe7011f25b8a741dc48c655e8 Mon Sep 17 00:00:00 2001 From: Kane Williams Date: Tue, 17 Nov 2026 14:46:52 +1300 Subject: [PATCH 05/15] refactor: remove the instance secret link history method and model --- datamasque/client/__init__.py | 2 -- datamasque/client/instance_secret.py | 7 ------- datamasque/client/models/instance_secret.py | 11 ----------- tests/test_instance_secret.py | 21 --------------------- 4 files changed, 41 deletions(-) diff --git a/datamasque/client/__init__.py b/datamasque/client/__init__.py index 4469339..33a0cc6 100644 --- a/datamasque/client/__init__.py +++ b/datamasque/client/__init__.py @@ -141,7 +141,6 @@ InstanceSecretEvent, InstanceSecretEventId, InstanceSecretEventKind, - InstanceSecretLinkHistory, InstanceSecretLinkRequest, InstanceSecretLinkRequestVerification, InstanceSecretLinkResponse, @@ -328,7 +327,6 @@ "InstanceSecretEventKind", "InstanceSecretLinkError", "InstanceSecretLinkErrorCode", - "InstanceSecretLinkHistory", "InstanceSecretLinkRequest", "InstanceSecretLinkRequestVerification", "InstanceSecretLinkResponse", diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index 843e239..e720334 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -6,7 +6,6 @@ from datamasque.client.exceptions import InstanceSecretLinkError, InstanceSecretLinkErrorCode from datamasque.client.models.instance_secret import ( InFlightSyncResult, - InstanceSecretLinkHistory, InstanceSecretLinkRequest, InstanceSecretLinkRequestVerification, InstanceSecretLinkResponse, @@ -58,12 +57,6 @@ def get_instance_secret_fingerprint(self) -> str: fingerprint: str = response.json()["fingerprint"] return fingerprint - def get_instance_secret_link_history(self) -> InstanceSecretLinkHistory: - """Returns every event of the instance secret of this DataMasque instance, and the links that are current.""" - - response = self.make_request("GET", "/api/instance-secret/link/history/") - return InstanceSecretLinkHistory.model_validate(response.json()) - def create_instance_secret_link_request(self) -> InstanceSecretLinkRequest: """ Creates a request code for joining the instance secret of another DataMasque instance. diff --git a/datamasque/client/models/instance_secret.py b/datamasque/client/models/instance_secret.py index 73ef956..3939313 100644 --- a/datamasque/client/models/instance_secret.py +++ b/datamasque/client/models/instance_secret.py @@ -55,17 +55,6 @@ class InstanceSecretEvent(BaseModel): """The user who initiated the event.""" -class InstanceSecretLinkHistory(BaseModel): - """The events of the instance secret of a DataMasque instance.""" - - model_config = ConfigDict(extra="allow") - - current_links: list[InstanceSecretEvent] - """The shares and adoptions that no later change to the instance secret has ended.""" - events: list[InstanceSecretEvent] - """Every event, newest first.""" - - class InstanceSecretLinkRequest(BaseModel): """A request code that the joining DataMasque instance creates, to be pasted on the sharing instance.""" diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index c3afcdd..ac08929 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -42,27 +42,6 @@ def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): assert client.get_instance_secret_fingerprint() == "7KQ2-9MXA-3HDP-T0WZ" -def test_get_instance_secret_link_history_parses_events(client): - shared = event_json( - "shared", - peer_hostname="other.example.com", - request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", - response_fingerprint="ABCD-EFGH-JKMN-PQRS", - ) - with requests_mock.Mocker() as m: - m.get(f"{LINK_URL}/history/", json={"current_links": [shared], "events": [shared, event_json("initialised")]}) - history = client.get_instance_secret_link_history() - - assert history.current_links[0].kind is InstanceSecretEventKind.shared - assert history.current_links[0].peer_hostname == "other.example.com" - assert history.current_links[0].request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" - assert history.current_links[0].response_fingerprint == "ABCD-EFGH-JKMN-PQRS" - assert [event.kind for event in history.events] == [ - InstanceSecretEventKind.shared, - InstanceSecretEventKind.initialised, - ] - - 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) From 0f1d82555a1c02a92768f1e7aef55a0475b4d002 Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Wed, 18 Nov 2026 16:06:45 +1300 Subject: [PATCH 06/15] docs: DM-4856 reword the stale verification text now the link history is removed --- datamasque/client/exceptions.py | 2 +- datamasque/client/instance_secret.py | 2 +- datamasque/client/models/instance_secret.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index 6c392eb..b1f1e38 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -130,7 +130,7 @@ class InstanceSecretLinkErrorCode(enum.Enum): active_runs = "active_runs" """Runs are in progress. Cancel them or wait for them to finish.""" verification_stale = "verification_stale" - """The instance secret or its history changed after the response code was verified. Verify the response again.""" + """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" diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index 6dc3784..8ab7bc4 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -167,7 +167,7 @@ def accept_instance_secret_link_response(self, response_code: str, verification_ Raises: ValueError: `response_code` or `verification_token` is empty. InstanceSecretLinkError: the response code is not valid, runs are in progress, - or the instance secret or its history changed after the response code was verified. + or the instance secret changed or was shared since the response code was verified. """ response = self._post_link_step( diff --git a/datamasque/client/models/instance_secret.py b/datamasque/client/models/instance_secret.py index 3939313..cb809c0 100644 --- a/datamasque/client/models/instance_secret.py +++ b/datamasque/client/models/instance_secret.py @@ -103,4 +103,4 @@ class InstanceSecretLinkResponseVerification(BaseModel): 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 or its history has changed.""" + """Pass this when accepting the response code, which then fails if the instance secret changed or was shared since.""" From ce16cce582d1c5a93fd30319f072484617a882b1 Mon Sep 17 00:00:00 2001 From: Kane Williams Date: Tue, 17 Nov 2026 16:45:18 +1300 Subject: [PATCH 07/15] test: assert every field of a link ending, for shared and adopted --- tests/test_instance_secret.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index ac08929..a73c784 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -177,21 +177,33 @@ def test_a_linking_step_without_an_instance_secret_raises_data_masque_api_error( assert not isinstance(error_info.value, InstanceSecretLinkError) -def test_verify_instance_secret_link_response_parses_the_links_ending(client): +@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("adopted", peer_hostname="third.example.com")], + "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"} - assert verification.links_ending[0].kind is InstanceSecretEventKind.adopted + 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" From 0887191f028990190be97bef6c8f92b7c40779ef Mon Sep 17 00:00:00 2001 From: jiatolentino Date: Thu, 19 Nov 2026 11:58:07 +0800 Subject: [PATCH 08/15] feat: add get_current_instance_secret_links Returns the shares and adoptions that rotating the instance secret would end, newest first. --- HISTORY.rst | 1 + datamasque/client/instance_secret.py | 17 ++++++++++ tests/test_instance_secret.py | 47 ++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/HISTORY.rst b/HISTORY.rst index 817e42e..042b546 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -7,6 +7,7 @@ History * 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 diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index 8ab7bc4..69ec276 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -6,6 +6,7 @@ from datamasque.client.exceptions import InstanceSecretLinkError, InstanceSecretLinkErrorCode from datamasque.client.models.instance_secret import ( InFlightSyncResult, + InstanceSecretEvent, InstanceSecretLinkRequest, InstanceSecretLinkRequestVerification, InstanceSecretLinkResponse, @@ -57,6 +58,22 @@ def get_instance_secret_fingerprint(self) -> str: 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. diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index 878c8e0..dc8384b 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -42,6 +42,53 @@ def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): 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: From 8d346d90a55a235d0ce366d0870046ac5056fc72 Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Fri, 27 Nov 2026 09:55:55 +1300 Subject: [PATCH 09/15] fix(instance-secret): DM-5734 review fixes, rename the link fields and narrow the current links to shares and adoptions --- HISTORY.rst | 3 +- datamasque/client/__init__.py | 10 +- datamasque/client/instance_secret.py | 28 +-- datamasque/client/models/instance_secret.py | 59 +++--- tests/test_instance_secret.py | 206 ++++++++++++++------ 5 files changed, 199 insertions(+), 107 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 042b546..0b27dd5 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -5,7 +5,8 @@ History 1.8.0 (unreleased) ------------------ -* Added methods for the instance secret fingerprint and for linking the instance secret with another DataMasque instance. +* 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. diff --git a/datamasque/client/__init__.py b/datamasque/client/__init__.py index 33a0cc6..881c4f9 100644 --- a/datamasque/client/__init__.py +++ b/datamasque/client/__init__.py @@ -138,9 +138,8 @@ ) from datamasque.client.models.instance_secret import ( InFlightSyncResult, - InstanceSecretEvent, - InstanceSecretEventId, - InstanceSecretEventKind, + InstanceSecretLink, + InstanceSecretLinkKind, InstanceSecretLinkRequest, InstanceSecretLinkRequestVerification, InstanceSecretLinkResponse, @@ -322,11 +321,10 @@ "InDataDiscoveryConfig", "InDataDiscoveryRule", "InFlightSyncResult", - "InstanceSecretEvent", - "InstanceSecretEventId", - "InstanceSecretEventKind", + "InstanceSecretLink", "InstanceSecretLinkError", "InstanceSecretLinkErrorCode", + "InstanceSecretLinkKind", "InstanceSecretLinkRequest", "InstanceSecretLinkRequestVerification", "InstanceSecretLinkResponse", diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index 69ec276..b910a17 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -6,7 +6,7 @@ from datamasque.client.exceptions import InstanceSecretLinkError, InstanceSecretLinkErrorCode from datamasque.client.models.instance_secret import ( InFlightSyncResult, - InstanceSecretEvent, + InstanceSecretLink, InstanceSecretLinkRequest, InstanceSecretLinkRequestVerification, InstanceSecretLinkResponse, @@ -35,12 +35,14 @@ class InstanceSecretClient(BaseClient): # 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 + if request_verification.request_fingerprint != link_request.request_fingerprint: + raise ValueError("The request fingerprints differ.") 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 + if response_verification.response_fingerprint != link_response.response_fingerprint: + raise ValueError("The response fingerprints differ.") joining_client.accept_instance_secret_link_response( link_response.response_code, response_verification.verification_token, @@ -58,7 +60,7 @@ def get_instance_secret_fingerprint(self) -> str: fingerprint: str = response.json()["fingerprint"] return fingerprint - def get_current_instance_secret_links(self) -> list[InstanceSecretEvent]: + def get_current_instance_secret_links(self) -> list[InstanceSecretLink]: """ Returns the shares and adoptions that link this DataMasque instance with others, newest first. @@ -68,11 +70,11 @@ def get_current_instance_secret_links(self) -> list[InstanceSecretEvent]: Requires an admin user, and works on every license type. Raises: - DataMasqueApiError: the user is not an admin user. + DataMasqueApiError: the request fails, for example because 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"]] + return [InstanceSecretLink.model_validate(link) for link in response.json()["links"]] def rotate_instance_secret(self) -> InFlightSyncResult: """ @@ -82,12 +84,12 @@ def rotate_instance_secret(self) -> InFlightSyncResult: 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, + Returns an `InFlightSyncResult` stating whether the in-flight masking service received the new instance secret. + If DataMasque fails to notify the in-flight masking 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. + DataMasqueApiError: the request fails, for example because the user is not an admin user. """ response = self.make_request("POST", "/api/instance-secret/rotate/") @@ -132,6 +134,7 @@ def verify_instance_secret_link_request(self, request_code: str) -> InstanceSecr Raises: ValueError: `request_code` is empty. InstanceSecretLinkError: the request code is not valid. + DataMasqueApiError: the request fails for another reason. """ response = self._post_link_step("/api/instance-secret/link/request/verify/", {"request_code": request_code}) @@ -147,6 +150,7 @@ def accept_instance_secret_link_request(self, request_code: str) -> InstanceSecr Raises: ValueError: `request_code` is empty. InstanceSecretLinkError: the request code is not valid. + DataMasqueApiError: the request fails for another reason. """ response = self._post_link_step("/api/instance-secret/link/request/accept/", {"request_code": request_code}) @@ -162,6 +166,7 @@ def verify_instance_secret_link_response(self, response_code: str) -> InstanceSe Raises: ValueError: `response_code` is empty. InstanceSecretLinkError: the response code is not valid. + DataMasqueApiError: the request fails for another reason. """ response = self._post_link_step( @@ -177,14 +182,15 @@ def accept_instance_secret_link_response(self, response_code: str, verification_ 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, + Returns an `InFlightSyncResult` stating whether the in-flight masking service received the new instance secret. + If DataMasque fails to notify the in-flight masking 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. + DataMasqueApiError: the request fails for another reason. """ response = self._post_link_step( diff --git a/datamasque/client/models/instance_secret.py b/datamasque/client/models/instance_secret.py index cb809c0..6c31213 100644 --- a/datamasque/client/models/instance_secret.py +++ b/datamasque/client/models/instance_secret.py @@ -2,20 +2,14 @@ import enum from datetime import datetime -from typing import NewType, Optional +from typing import Optional from pydantic import BaseModel, ConfigDict -InstanceSecretEventId = NewType("InstanceSecretEventId", str) +class InstanceSecretLinkKind(enum.Enum): + """How a DataMasque instance came to share its instance secret with another DataMasque instance.""" -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" @@ -24,35 +18,35 @@ class InstanceSecretEventKind(enum.Enum): class InFlightSyncResult(enum.Enum): """ - Whether the IFM service successfully received a new instance secret. + Whether the in-flight masking 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. + Only in-flight masking can need a DataMasque restart after a new instance secret. """ notified = "notified" - """The IFM service uses the new instance secret, and nothing more is needed.""" + """The in-flight masking 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.""" + """Restart DataMasque so that the in-flight masking service uses the new instance secret.""" file_write_failed = "file_write_failed" - """Restart DataMasque so that the IFM service uses the new instance secret.""" + """Restart DataMasque so that the in-flight masking service uses the new instance secret.""" -class InstanceSecretEvent(BaseModel): - """An initialisation, rotation, share or adoption of the instance secret of a DataMasque instance.""" +class InstanceSecretLink(BaseModel): + """A share or adoption that linked the instance secret of a DataMasque instance with another instance.""" model_config = ConfigDict(extra="allow") - id: InstanceSecretEventId + id: str 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.""" + kind: InstanceSecretLinkKind + peer_hostname: str + """The hostname of the other DataMasque instance.""" + request_fingerprint: str + """The fingerprint of the request code.""" + response_fingerprint: str + """The fingerprint of the response code.""" username: str - """The user who initiated the event.""" + """The user who initiated the share or adoption.""" class InstanceSecretLinkRequest(BaseModel): @@ -61,7 +55,7 @@ class InstanceSecretLinkRequest(BaseModel): model_config = ConfigDict(extra="allow") request_code: str - fingerprint: str + request_fingerprint: str """The request fingerprint, which must match the one shown on the sharing DataMasque instance.""" expires_at: datetime @@ -71,9 +65,9 @@ class InstanceSecretLinkRequestVerification(BaseModel): model_config = ConfigDict(extra="allow") - hostname: str + peer_hostname: str """The reported hostname of the joining DataMasque instance.""" - fingerprint: str + request_fingerprint: str """The request fingerprint, which must match the one shown on the joining DataMasque instance.""" expires_at: datetime """When the request expires.""" @@ -96,11 +90,14 @@ class InstanceSecretLinkResponseVerification(BaseModel): model_config = ConfigDict(extra="allow") - hostname: str + peer_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] + links_ending: list[InstanceSecretLink] """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.""" + """ + Pass this when accepting the response code. + The accept fails if the instance secret changed or was shared since. + """ diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index dc8384b..86fb6f4 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -1,29 +1,48 @@ """Tests for `InstanceSecretClient` (instance secret fingerprint and instance secret linking).""" +import re from datetime import datetime, timezone -from typing import Optional import pytest import requests_mock +from pydantic import ValidationError from datamasque.client.exceptions import DataMasqueApiError, InstanceSecretLinkError, InstanceSecretLinkErrorCode -from datamasque.client.models.instance_secret import InFlightSyncResult, InstanceSecretEventKind +from datamasque.client.models.instance_secret import InFlightSyncResult, InstanceSecretLink, InstanceSecretLinkKind LINK_URL = "http://test-server/api/instance-secret/link" LINK_REQUEST_JSON = { "request_code": "DMLINK-REQUEST", - "fingerprint": "7KQ2-9MXA-3HDP-T0WZ", + "request_fingerprint": "7KQ2-9MXA-3HDP-T0WZ", "expires_at": "2026-10-30T12:00:00Z", } +# 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", +) + -def event_json( +def link_json( kind: str, *, - peer_hostname: Optional[str] = None, - request_fingerprint: Optional[str] = None, - response_fingerprint: Optional[str] = None, + peer_hostname: str = "peer.example.com", + request_fingerprint: str = "7KQ2-9MXA-3HDP-T0WZ", + response_fingerprint: str = "9GGM-DR1H-ETXX-41Q6", ) -> dict: return { "id": "3f2b8c1e-5d4a-4e6f-9a7b-1c2d3e4f5a6b", @@ -43,14 +62,14 @@ def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): def test_get_current_instance_secret_links_returns_the_links_in_order(client): - shared = event_json( + shared = link_json( "shared", peer_hostname="joining.example.com", request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", response_fingerprint="0F2A-9QXH-7RZW-B4ND", ) adopted = { - **event_json( + **link_json( "adopted", peer_hostname="sharing.example.com", request_fingerprint="EBDV-ECVC-8QJ4-9XT5", @@ -63,13 +82,24 @@ def test_get_current_instance_secret_links_returns_the_links_in_order(client): 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"), + (InstanceSecretLinkKind.shared, "joining.example.com"), + (InstanceSecretLinkKind.adopted, "sharing.example.com"), ] + assert links[0].id == "3f2b8c1e-5d4a-4e6f-9a7b-1c2d3e4f5a6b" + assert links[0].username == "admin" + assert links[0].request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" assert links[0].created_at == datetime(2026, 10, 30, 11, 0, tzinfo=timezone.utc) assert links[1].response_fingerprint == "9GGM-DR1H-ETXX-41Q6" +@pytest.mark.parametrize("kind", ["rotated", "initialised"]) +def test_get_current_instance_secret_links_rejects_an_unknown_kind(client, kind): + with requests_mock.Mocker() as m: + m.get("http://test-server/api/instance-secret/current-links/", json={"links": [link_json(kind)]}) + with pytest.raises(ValidationError, match="kind"): + client.get_current_instance_secret_links() + + 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": []}) @@ -83,7 +113,12 @@ def test_get_current_instance_secret_links_by_a_user_who_is_not_an_admin_raises_ json={"detail": "You do not have permission to perform this action."}, status_code=403, ) - with pytest.raises(DataMasqueApiError) as error_info: + with pytest.raises( + DataMasqueApiError, + match=re.escape( + "API request to http://test-server/api/instance-secret/current-links/ failed with status 403" + ), + ) as error_info: client.get_current_instance_secret_links() assert error_info.value.response.status_code == 403 @@ -106,7 +141,10 @@ def test_rotate_instance_secret_by_a_user_who_is_not_an_admin_raises_data_masque json={"detail": "You do not have permission to perform this action."}, status_code=403, ) - with pytest.raises(DataMasqueApiError) as error_info: + with pytest.raises( + DataMasqueApiError, + match=re.escape("API request to http://test-server/api/instance-secret/rotate/ failed with status 403"), + ) as error_info: client.rotate_instance_secret() assert error_info.value.response.status_code == 403 @@ -127,7 +165,8 @@ def test_get_pending_instance_secret_link_request_returns_the_request(client): 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.request_code == "DMLINK-REQUEST" + assert link_request.request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" assert link_request.expires_at == datetime(2026, 10, 30, 12, 0, tzinfo=timezone.utc) @@ -140,17 +179,45 @@ def test_get_pending_instance_secret_link_request_returns_none_on_404(client): 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): + with pytest.raises( + DataMasqueApiError, + match=re.escape(f"API request to {LINK_URL}/request/ failed with status 403"), + ) as error_info: client.get_pending_instance_secret_link_request() + assert error_info.value.response.status_code == 403 + + +def test_cancel_instance_secret_link_request_sends_a_delete_and_returns_none(client): + with requests_mock.Mocker() as m: + m.delete(f"{LINK_URL}/request/", status_code=204) + result = client.cancel_instance_secret_link_request() + + assert m.call_count == 1 + assert m.last_request.method == "DELETE" + assert m.last_request.url == f"{LINK_URL}/request/" + assert result is None + + +def test_cancel_instance_secret_link_request_raises_on_403(client): + with requests_mock.Mocker() as m: + m.delete(f"{LINK_URL}/request/", json={"detail": "Not licensed."}, status_code=403) + with pytest.raises( + DataMasqueApiError, + match=re.escape(f"API request to {LINK_URL}/request/ failed with status 403"), + ) as error_info: + client.cancel_instance_secret_link_request() + + assert error_info.value.response.status_code == 403 + 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", + "peer_hostname": "joining.example.com", + "request_fingerprint": "7KQ2-9MXA-3HDP-T0WZ", "expires_at": "2026-10-30T12:00:00Z", "datamasque_version": None, }, @@ -158,8 +225,8 @@ def test_verify_instance_secret_link_request_returns_what_the_admins_compare(cli 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.peer_hostname == "joining.example.com" + assert verification.request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" assert verification.datamasque_version is None @@ -175,25 +242,6 @@ def test_accept_instance_secret_link_request_returns_the_response_code(client): 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." @@ -210,6 +258,21 @@ def test_a_failed_linking_step_raises_instance_secret_link_error_with_the_code(c assert error_info.value.response.status_code == 400 +@pytest.mark.parametrize("error_code", ["verification_stale", "active_runs"]) +def test_a_failed_accept_of_a_response_code_raises_instance_secret_link_error_without_logging_request_data( + client, caplog, error_code +): + message = "The response code was not accepted." + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/response/accept/", json={"code": error_code, "message": message}, status_code=400) + with pytest.raises(InstanceSecretLinkError, match=message) as error_info: + client.accept_instance_secret_link_response("DMLINK-RESPONSE", "token") + + assert error_info.value.code is InstanceSecretLinkErrorCode(error_code) + assert error_info.value.response.status_code == 400 + assert "Request data was" not in caplog.text + + @pytest.mark.parametrize( "error_body", [ @@ -221,7 +284,23 @@ def test_a_failed_linking_step_raises_instance_secret_link_error_with_the_code(c 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: + with pytest.raises( + DataMasqueApiError, + match=re.escape(f"API request to {LINK_URL}/request/verify/ failed with status 400"), + ) 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_400_with_a_body_that_is_not_json_raises_data_masque_api_error(client): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/request/verify/", text="Bad Request", status_code=400) + with pytest.raises( + DataMasqueApiError, + match=re.escape(f"API request to {LINK_URL}/request/verify/ failed with status 400"), + ) as error_info: client.verify_instance_secret_link_request("DMLINK-REQUEST") assert not isinstance(error_info.value, InstanceSecretLinkError) @@ -231,33 +310,42 @@ def test_a_400_that_is_not_a_known_link_error_raises_data_masque_api_error(clien 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 + with pytest.raises( + DataMasqueApiError, + match=re.escape(f"API request to {LINK_URL}/response/accept/ failed with status 500"), + ) as error_info: + client.accept_instance_secret_link_response("DMLINK-RESPONSE", "VERIFICATION-TOKEN") + + assert error_info.value.response.status_code == 500 + assert "Request data was: {'response_code': '', 'verification_token': ''}" in caplog.text assert "DMLINK-RESPONSE" not in caplog.text + assert "VERIFICATION-TOKEN" 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: + with pytest.raises( + DataMasqueApiError, + match=re.escape(f"API request to {LINK_URL}/request/accept/ failed with status 503"), + ) as error_info: client.accept_instance_secret_link_request("DMLINK-REQUEST") assert not isinstance(error_info.value, InstanceSecretLinkError) + assert error_info.value.response.status_code == 503 -@pytest.mark.parametrize("event_kind", [InstanceSecretEventKind.shared, InstanceSecretEventKind.adopted]) -def test_verify_instance_secret_link_response_parses_the_links_ending(client, event_kind): +@pytest.mark.parametrize("link_kind", [InstanceSecretLinkKind.shared, InstanceSecretLinkKind.adopted]) +def test_verify_instance_secret_link_response_parses_the_links_ending(client, link_kind): with requests_mock.Mocker() as m: m.post( f"{LINK_URL}/response/verify/", json={ - "hostname": "other.example.com", + "peer_hostname": "other.example.com", "response_fingerprint": "ABCD-EFGH-JKMN-PQRS", "links_ending": [ - event_json( - event_kind.value, + link_json( + link_kind.value, peer_hostname="third.example.com", request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", response_fingerprint="WXYZ-2345-6789-BCDF", @@ -269,8 +357,10 @@ def test_verify_instance_secret_link_response_parses_the_links_ending(client, ev verification = client.verify_instance_secret_link_response("DMLINK-RESPONSE") assert m.last_request.json() == {"response_code": "DMLINK-RESPONSE"} + assert verification.peer_hostname == "other.example.com" link_ending = verification.links_ending[0] - assert link_ending.kind is event_kind + assert isinstance(link_ending, InstanceSecretLink) + assert link_ending.kind is link_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" @@ -287,18 +377,18 @@ def test_accept_instance_secret_link_response_returns_the_in_flight_sync_result( @pytest.mark.parametrize( - ("method_name", "arguments"), + ("method_name", "arguments", "empty_name"), [ - ("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", "")), + ("verify_instance_secret_link_request", ("",), "request_code"), + ("accept_instance_secret_link_request", ("",), "request_code"), + ("verify_instance_secret_link_response", ("",), "response_code"), + ("accept_instance_secret_link_response", ("", "token"), "response_code"), + ("accept_instance_secret_link_response", ("DMLINK-RESPONSE", ""), "verification_token"), ], ) -def test_an_empty_code_raises_value_error_before_any_request(client, method_name, arguments): +def test_an_empty_code_raises_value_error_before_any_request(client, method_name, arguments, empty_name): with requests_mock.Mocker() as m: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=re.escape(f"`{empty_name}` must not be empty.")): getattr(client, method_name)(*arguments) assert m.call_count == 0 From dfc0c3e17c825c07e5bb2a0062daf3b713bc3e67 Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Fri, 27 Nov 2026 09:55:55 +1300 Subject: [PATCH 10/15] fix(instance-secret): DM-5734 address the PR review comments: error code, secret fingerprint, server version and 1.8.0 --- HISTORY.rst | 2 +- datamasque/client/exceptions.py | 2 ++ datamasque/client/instance_secret.py | 2 ++ datamasque/client/models/instance_secret.py | 5 +++ pyproject.toml | 2 +- tests/test_instance_secret.py | 36 ++++++++++++--------- uv.lock | 2 +- 7 files changed, 33 insertions(+), 18 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 0b27dd5..08a93fc 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -10,7 +10,7 @@ History * 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 +Requires server version 3.26.23 1.7.0 (unreleased) ------------------ diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index b1f1e38..0edeb4b 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -119,6 +119,8 @@ class InstanceSecretLinkErrorCode(enum.Enum): """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.""" + request_created_in_future = "request_created_in_future" + """The request code has a creation time in the future. Check the clocks of both DataMasque instances.""" unknown_request = "unknown_request" """The request that matches the response code was not found.""" unseal_failed = "unseal_failed" diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index b910a17..5cdebc9 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -43,6 +43,8 @@ class InstanceSecretClient(BaseClient): response_verification = joining_client.verify_instance_secret_link_response(link_response.response_code) if response_verification.response_fingerprint != link_response.response_fingerprint: raise ValueError("The response fingerprints differ.") + if response_verification.instance_secret_fingerprint != sharing_client.get_instance_secret_fingerprint(): + raise ValueError("The instance secret fingerprints differ.") joining_client.accept_instance_secret_link_response( link_response.response_code, response_verification.verification_token, diff --git a/datamasque/client/models/instance_secret.py b/datamasque/client/models/instance_secret.py index 6c31213..185e1ce 100644 --- a/datamasque/client/models/instance_secret.py +++ b/datamasque/client/models/instance_secret.py @@ -94,6 +94,11 @@ class InstanceSecretLinkResponseVerification(BaseModel): """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.""" + instance_secret_fingerprint: str + """ + The fingerprint that the instance secret of this DataMasque instance will have after the link. + It must match the fingerprint on the sharing DataMasque instance. + """ links_ending: list[InstanceSecretLink] """The current links that accepting the response code will end.""" verification_token: str diff --git a/pyproject.toml b/pyproject.toml index 6f3eaed..2c3cf5c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "datamasque-python" -version = "1.6.0" +version = "1.8.0" description = "Official Python client for the DataMasque data-masking API." authors = [ { name = "DataMasque Ltd" }, diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index 86fb6f4..4634951 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -10,11 +10,14 @@ from datamasque.client.exceptions import DataMasqueApiError, InstanceSecretLinkError, InstanceSecretLinkErrorCode from datamasque.client.models.instance_secret import InFlightSyncResult, InstanceSecretLink, InstanceSecretLinkKind +REQUEST_FINGERPRINT = "7KQ2-9MXA-3HDP-T0WZ" +SECRET_FINGERPRINT = "5NBC-2WTR-8JKE-X7YH" +RESPONSE_FINGERPRINT = "9GGM-DR1H-ETXX-41Q6" LINK_URL = "http://test-server/api/instance-secret/link" LINK_REQUEST_JSON = { "request_code": "DMLINK-REQUEST", - "request_fingerprint": "7KQ2-9MXA-3HDP-T0WZ", + "request_fingerprint": REQUEST_FINGERPRINT, "expires_at": "2026-10-30T12:00:00Z", } @@ -26,6 +29,7 @@ "invalid_public_key", "own_request", "request_expired", + "request_created_in_future", "unknown_request", "unseal_failed", "invalid_secret", @@ -41,8 +45,8 @@ def link_json( kind: str, *, peer_hostname: str = "peer.example.com", - request_fingerprint: str = "7KQ2-9MXA-3HDP-T0WZ", - response_fingerprint: str = "9GGM-DR1H-ETXX-41Q6", + request_fingerprint: str = REQUEST_FINGERPRINT, + response_fingerprint: str = RESPONSE_FINGERPRINT, ) -> dict: return { "id": "3f2b8c1e-5d4a-4e6f-9a7b-1c2d3e4f5a6b", @@ -57,15 +61,15 @@ def link_json( 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" + m.get("http://test-server/api/instance-secret/", json={"fingerprint": SECRET_FINGERPRINT}) + assert client.get_instance_secret_fingerprint() == SECRET_FINGERPRINT def test_get_current_instance_secret_links_returns_the_links_in_order(client): shared = link_json( "shared", peer_hostname="joining.example.com", - request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", + request_fingerprint=REQUEST_FINGERPRINT, response_fingerprint="0F2A-9QXH-7RZW-B4ND", ) adopted = { @@ -73,7 +77,7 @@ def test_get_current_instance_secret_links_returns_the_links_in_order(client): "adopted", peer_hostname="sharing.example.com", request_fingerprint="EBDV-ECVC-8QJ4-9XT5", - response_fingerprint="9GGM-DR1H-ETXX-41Q6", + response_fingerprint=RESPONSE_FINGERPRINT, ), "id": "8a1c2d3e-4f5a-4b6c-8d7e-9f0a1b2c3d4e", } @@ -87,16 +91,16 @@ def test_get_current_instance_secret_links_returns_the_links_in_order(client): ] assert links[0].id == "3f2b8c1e-5d4a-4e6f-9a7b-1c2d3e4f5a6b" assert links[0].username == "admin" - assert links[0].request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert links[0].request_fingerprint == REQUEST_FINGERPRINT assert links[0].created_at == datetime(2026, 10, 30, 11, 0, tzinfo=timezone.utc) - assert links[1].response_fingerprint == "9GGM-DR1H-ETXX-41Q6" + assert links[1].response_fingerprint == RESPONSE_FINGERPRINT @pytest.mark.parametrize("kind", ["rotated", "initialised"]) def test_get_current_instance_secret_links_rejects_an_unknown_kind(client, kind): with requests_mock.Mocker() as m: m.get("http://test-server/api/instance-secret/current-links/", json={"links": [link_json(kind)]}) - with pytest.raises(ValidationError, match="kind"): + with pytest.raises(ValidationError, match="Input should be 'shared' or 'adopted'"): client.get_current_instance_secret_links() @@ -166,7 +170,7 @@ def test_get_pending_instance_secret_link_request_returns_the_request(client): assert link_request is not None assert link_request.request_code == "DMLINK-REQUEST" - assert link_request.request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert link_request.request_fingerprint == REQUEST_FINGERPRINT assert link_request.expires_at == datetime(2026, 10, 30, 12, 0, tzinfo=timezone.utc) @@ -217,7 +221,7 @@ def test_verify_instance_secret_link_request_returns_what_the_admins_compare(cli f"{LINK_URL}/request/verify/", json={ "peer_hostname": "joining.example.com", - "request_fingerprint": "7KQ2-9MXA-3HDP-T0WZ", + "request_fingerprint": REQUEST_FINGERPRINT, "expires_at": "2026-10-30T12:00:00Z", "datamasque_version": None, }, @@ -226,7 +230,7 @@ def test_verify_instance_secret_link_request_returns_what_the_admins_compare(cli assert m.last_request.json() == {"request_code": "DMLINK-REQUEST"} assert verification.peer_hostname == "joining.example.com" - assert verification.request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert verification.request_fingerprint == REQUEST_FINGERPRINT assert verification.datamasque_version is None @@ -343,11 +347,12 @@ def test_verify_instance_secret_link_response_parses_the_links_ending(client, li json={ "peer_hostname": "other.example.com", "response_fingerprint": "ABCD-EFGH-JKMN-PQRS", + "instance_secret_fingerprint": SECRET_FINGERPRINT, "links_ending": [ link_json( link_kind.value, peer_hostname="third.example.com", - request_fingerprint="7KQ2-9MXA-3HDP-T0WZ", + request_fingerprint=REQUEST_FINGERPRINT, response_fingerprint="WXYZ-2345-6789-BCDF", ) ], @@ -358,11 +363,12 @@ def test_verify_instance_secret_link_response_parses_the_links_ending(client, li assert m.last_request.json() == {"response_code": "DMLINK-RESPONSE"} assert verification.peer_hostname == "other.example.com" + assert verification.instance_secret_fingerprint == SECRET_FINGERPRINT link_ending = verification.links_ending[0] assert isinstance(link_ending, InstanceSecretLink) assert link_ending.kind is link_kind assert link_ending.peer_hostname == "third.example.com" - assert link_ending.request_fingerprint == "7KQ2-9MXA-3HDP-T0WZ" + assert link_ending.request_fingerprint == REQUEST_FINGERPRINT assert link_ending.response_fingerprint == "WXYZ-2345-6789-BCDF" assert verification.verification_token == "token" diff --git a/uv.lock b/uv.lock index 0fb45ec..acff748 100644 --- a/uv.lock +++ b/uv.lock @@ -419,7 +419,7 @@ toml = [ [[package]] name = "datamasque-python" -version = "1.6.0" +version = "1.8.0" source = { editable = "." } dependencies = [ { name = "pydantic" }, From 346825295644c61ee7a41980124a0e702d4b25e5 Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Mon, 30 Nov 2026 10:20:19 +1300 Subject: [PATCH 11/15] docs(instance-secret): DM-4710 describe the weak instance secret error without calling it insecure --- datamasque/client/exceptions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index 0edeb4b..fcae78e 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -136,7 +136,7 @@ class InstanceSecretLinkErrorCode(enum.Enum): 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.""" + """The instance secret is too short, or uses characters that a generated one does not. Rotate it, then try again.""" class InstanceSecretLinkError(DataMasqueApiError): From 5d7cfd62b3153ab08107eb386bc27d8bc91e347b Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Mon, 30 Nov 2026 11:05:34 +1300 Subject: [PATCH 12/15] docs(instance-secret): DM-4710 say "uses invalid characters" for the weak instance secret error --- datamasque/client/exceptions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index fcae78e..679dd18 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -136,7 +136,7 @@ class InstanceSecretLinkErrorCode(enum.Enum): 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 is too short, or uses characters that a generated one does not. Rotate it, then try again.""" + """The instance secret is too short, or uses invalid characters. Rotate it, then try again.""" class InstanceSecretLinkError(DataMasqueApiError): From 41abcfc5c2d0a2049b05d7b5778abfec37f6151c Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Mon, 30 Nov 2026 13:27:49 +1300 Subject: [PATCH 13/15] docs(instance-secret): DM-4710 say "contains invalid characters" for the weak instance secret error --- datamasque/client/exceptions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/datamasque/client/exceptions.py b/datamasque/client/exceptions.py index 679dd18..07b1b6c 100644 --- a/datamasque/client/exceptions.py +++ b/datamasque/client/exceptions.py @@ -136,7 +136,7 @@ class InstanceSecretLinkErrorCode(enum.Enum): 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 is too short, or uses invalid characters. Rotate it, then try again.""" + """The instance secret is too short, or contains invalid characters. Rotate it, then try again.""" class InstanceSecretLinkError(DataMasqueApiError): From 734fd9b89ac4df45463a07e667816f09137f8a01 Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Mon, 30 Nov 2026 13:36:20 +1300 Subject: [PATCH 14/15] fix(instance-secret): DM-4710 raise InstanceSecretLinkError from link request creation and the fingerprint read, and drop "(unreleased)" from the 1.7.0 heading --- HISTORY.rst | 4 +-- datamasque/client/instance_secret.py | 46 +++++++++++++++++++--------- tests/test_instance_secret.py | 44 ++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 16 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 08a93fc..87dfbf3 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -12,8 +12,8 @@ History Requires server version 3.26.23 -1.7.0 (unreleased) ------------------- +1.7.0 +----- * Added an optional ``instance`` field to ``DatabaseConnectionConfig``: the SQL Server named instance, taken from the Instance input in the connection form's advanced settings. diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index 5cdebc9..d12945e 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -56,9 +56,15 @@ 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. + + Raises: + InstanceSecretLinkError: the server refuses to show the fingerprint, + for example because the instance secret is too short or contains invalid characters. """ - response = self.make_request("GET", "/api/instance-secret/") + response = self.make_request("GET", "/api/instance-secret/", require_status_check=False) + self._raise_for_link_error(response) + self._raise_for_status(response) fingerprint: str = response.json()["fingerprint"] return fingerprint @@ -103,9 +109,15 @@ def create_instance_secret_link_request(self) -> InstanceSecretLinkRequest: 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. + + Raises: + InstanceSecretLinkError: the server refuses the request, + for example because the hostname used to reach it is too long to go in a request code. """ - response = self.make_request("POST", "/api/instance-secret/link/request/") + response = self.make_request("POST", "/api/instance-secret/link/request/", require_status_check=False) + self._raise_for_link_error(response) + self._raise_for_status(response) return InstanceSecretLinkRequest.model_validate(response.json()) def get_pending_instance_secret_link_request(self) -> Optional[InstanceSecretLinkRequest]: @@ -207,17 +219,23 @@ def _post_link_step(self, path: str, data: dict[str, str]) -> Response: 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_link_error(response) self._raise_for_status(response, request_data=data) return response + + @staticmethod + def _raise_for_link_error(response: Response) -> None: + """Raise `InstanceSecretLinkError` if `response` is a 400 with a link error code that this client knows.""" + if response.status_code != 400: + return + + # A 400 that is not a link error, or has a code that this version of the client does not know, + # is left for the caller to raise as a plain API error. + try: + error = response.json() + code = InstanceSecretLinkErrorCode(error["code"]) + message = error["message"] + except (ValueError, KeyError, TypeError): + return + + raise InstanceSecretLinkError(message, code=code, response=response) diff --git a/tests/test_instance_secret.py b/tests/test_instance_secret.py index 4634951..d4e9c78 100644 --- a/tests/test_instance_secret.py +++ b/tests/test_instance_secret.py @@ -65,6 +65,30 @@ def test_get_instance_secret_fingerprint_returns_the_fingerprint(client): assert client.get_instance_secret_fingerprint() == SECRET_FINGERPRINT +def test_get_instance_secret_fingerprint_raises_instance_secret_link_error_for_a_link_error(client): + message = "The instance secret of this DataMasque instance is too short, or contains invalid characters." + with requests_mock.Mocker() as m: + m.get( + "http://test-server/api/instance-secret/", + json={"code": "insecure_instance_secret", "message": message}, + status_code=400, + ) + with pytest.raises(InstanceSecretLinkError, match=re.escape(message)) as error_info: + client.get_instance_secret_fingerprint() + + assert error_info.value.code is InstanceSecretLinkErrorCode.insecure_instance_secret + + +def test_get_instance_secret_fingerprint_raises_data_masque_api_error_for_another_failure(client): + with requests_mock.Mocker() as m: + m.get("http://test-server/api/instance-secret/", json={"detail": "Not ready"}, status_code=503) + with pytest.raises(DataMasqueApiError) as error_info: + client.get_instance_secret_fingerprint() + + assert not isinstance(error_info.value, InstanceSecretLinkError) + assert error_info.value.response.status_code == 503 + + def test_get_current_instance_secret_links_returns_the_links_in_order(client): shared = link_json( "shared", @@ -163,6 +187,26 @@ def test_create_instance_secret_link_request_posts_without_a_body(client): assert link_request.request_code == "DMLINK-REQUEST" +def test_create_instance_secret_link_request_raises_instance_secret_link_error_for_a_link_error(client): + message = "The hostname used to access DataMasque is longer than 253 characters." + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/request/", json={"code": "host_header_too_long", "message": message}, status_code=400) + with pytest.raises(InstanceSecretLinkError, match=re.escape(message)) as error_info: + client.create_instance_secret_link_request() + + assert error_info.value.code is InstanceSecretLinkErrorCode.host_header_too_long + + +def test_create_instance_secret_link_request_raises_data_masque_api_error_for_another_failure(client): + with requests_mock.Mocker() as m: + m.post(f"{LINK_URL}/request/", json={"detail": "Forbidden"}, status_code=403) + with pytest.raises(DataMasqueApiError) as error_info: + client.create_instance_secret_link_request() + + assert not isinstance(error_info.value, InstanceSecretLinkError) + assert error_info.value.response.status_code == 403 + + 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) From 5d56dc770a35d76ab304e11554611bb260d40c5e Mon Sep 17 00:00:00 2001 From: Andrew Chester Date: Mon, 30 Nov 2026 21:32:28 +1300 Subject: [PATCH 15/15] refactor(instance-secret): DM-4710 raise the plain API error from _raise_for_link_error so callers make one call and add the 1.8.0 release date --- HISTORY.rst | 2 +- datamasque/client/instance_secret.py | 40 ++++++++++++++-------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 87dfbf3..1fd57f1 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -2,7 +2,7 @@ History ======= -1.8.0 (unreleased) +1.8.0 (2026-12-04) ------------------ * Added methods for the instance secret fingerprint diff --git a/datamasque/client/instance_secret.py b/datamasque/client/instance_secret.py index d12945e..41cb10d 100644 --- a/datamasque/client/instance_secret.py +++ b/datamasque/client/instance_secret.py @@ -64,7 +64,6 @@ def get_instance_secret_fingerprint(self) -> str: response = self.make_request("GET", "/api/instance-secret/", require_status_check=False) self._raise_for_link_error(response) - self._raise_for_status(response) fingerprint: str = response.json()["fingerprint"] return fingerprint @@ -117,7 +116,6 @@ def create_instance_secret_link_request(self) -> InstanceSecretLinkRequest: response = self.make_request("POST", "/api/instance-secret/link/request/", require_status_check=False) self._raise_for_link_error(response) - self._raise_for_status(response) return InstanceSecretLinkRequest.model_validate(response.json()) def get_pending_instance_secret_link_request(self) -> Optional[InstanceSecretLinkRequest]: @@ -219,23 +217,25 @@ def _post_link_step(self, path: str, data: dict[str, str]) -> Response: raise ValueError(f"`{name}` must not be empty.") response = self.make_request("POST", path, data=data, require_status_check=False) - self._raise_for_link_error(response) - self._raise_for_status(response, request_data=data) + self._raise_for_link_error(response, request_data=data) return response - @staticmethod - def _raise_for_link_error(response: Response) -> None: - """Raise `InstanceSecretLinkError` if `response` is a 400 with a link error code that this client knows.""" - if response.status_code != 400: - return - - # A 400 that is not a link error, or has a code that this version of the client does not know, - # is left for the caller to raise as a plain API error. - try: - error = response.json() - code = InstanceSecretLinkErrorCode(error["code"]) - message = error["message"] - except (ValueError, KeyError, TypeError): - return - - raise InstanceSecretLinkError(message, code=code, response=response) + def _raise_for_link_error(self, response: Response, *, request_data: Optional[dict[str, str]] = None) -> None: + """ + Raise the error for a failed `response`, or do nothing if it succeeded. + + A 400 with a link error code that this client knows raises `InstanceSecretLinkError`, + and any other failure raises as `_raise_for_status` does. + """ + if response.status_code == 400: + try: + error = response.json() + code = InstanceSecretLinkErrorCode(error["code"]) + message = error["message"] + except (ValueError, KeyError, TypeError): + # Not a link error, or a code that this version of the client does not know. + pass + else: + raise InstanceSecretLinkError(message, code=code, response=response) + + self._raise_for_status(response, request_data=request_data)