From bfeaee925af8568f52608ba4d0579c68d26dc7e3 Mon Sep 17 00:00:00 2001 From: Colin Haywood Date: Sat, 31 Oct 2026 13:25:12 +1300 Subject: [PATCH 1/8] 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 2/8] 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 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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 8/8] 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: