Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
bfeaee9
feat: add methods and models for instance secret linking
cph-datamasque Oct 31, 2026
a78fd43
feat: replace the event peer fingerprint with the request and respons…
cph-datamasque Nov 4, 2026
ce0cb0e
feat: add the insecure instance secret linking error code
cph-datamasque Nov 5, 2026
1933a6f
feat: DM-5075 add rotate_instance_secret
andrewchester-dm Nov 16, 2026
71edcaf
refactor: remove the instance secret link history method and model
kw-datamasque Nov 17, 2026
0f1d825
docs: DM-4856 reword the stale verification text now the link history…
andrewchester-dm Nov 18, 2026
ce16cce
test: assert every field of a link ending, for shared and adopted
kw-datamasque Nov 17, 2026
0887191
feat: add get_current_instance_secret_links
jiatolentino Nov 19, 2026
7260695
Merge pull request #83 from datamasque/DM-5075-rotate-instance-secret
andrewchester-dm Nov 23, 2026
86a52d1
Merge pull request #87 from datamasque/current-instance-secret-links
jiatolentino Nov 23, 2026
8d346d9
fix(instance-secret): DM-5734 review fixes, rename the link fields an…
andrewchester-dm Nov 26, 2026
dfc0c3e
fix(instance-secret): DM-5734 address the PR review comments: error c…
andrewchester-dm Nov 26, 2026
3468252
docs(instance-secret): DM-4710 describe the weak instance secret erro…
andrewchester-dm Nov 29, 2026
5d7cfd6
docs(instance-secret): DM-4710 say "uses invalid characters" for the …
andrewchester-dm Nov 29, 2026
41abcfc
docs(instance-secret): DM-4710 say "contains invalid characters" for …
andrewchester-dm Nov 30, 2026
734fd9b
fix(instance-secret): DM-4710 raise InstanceSecretLinkError from link…
andrewchester-dm Nov 30, 2026
5d56dc7
refactor(instance-secret): DM-4710 raise the plain API error from _ra…
andrewchester-dm Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,19 @@
History
=======

1.7.0 (unreleased)
1.8.0 (2026-12-04)
------------------

* 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 3.26.23

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.
It round-trips through ``list_connections`` and ``create_or_update_connection``,
Expand Down
20 changes: 20 additions & 0 deletions datamasque/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
DiscoveryConfigNotFoundError,
FailedToStartError,
IfmAuthError,
InstanceSecretLinkError,
InstanceSecretLinkErrorCode,
InvalidDiscoveryConfigError,
InvalidLibraryError,
InvalidRulesetError,
Expand Down Expand Up @@ -134,6 +136,15 @@
RulesetPlanPartialUpdateRequest,
RulesetPlanUpdateRequest,
)
from datamasque.client.models.instance_secret import (
InFlightSyncResult,
InstanceSecretLink,
InstanceSecretLinkKind,
InstanceSecretLinkRequest,
InstanceSecretLinkRequestVerification,
InstanceSecretLinkResponse,
InstanceSecretLinkResponseVerification,
)
from datamasque.client.models.license import LicenseInfo, SwitchableLicenseMetadata
from datamasque.client.models.project import (
Project,
Expand Down Expand Up @@ -309,6 +320,15 @@
"IfmTokenInfo",
"InDataDiscoveryConfig",
"InDataDiscoveryRule",
"InFlightSyncResult",
"InstanceSecretLink",
"InstanceSecretLinkError",
"InstanceSecretLinkErrorCode",
"InstanceSecretLinkKind",
"InstanceSecretLinkRequest",
"InstanceSecretLinkRequestVerification",
"InstanceSecretLinkResponse",
"InstanceSecretLinkResponseVerification",
"InvalidDiscoveryConfigError",
"InvalidLibraryError",
"InvalidRulesetError",
Expand Down
2 changes: 1 addition & 1 deletion datamasque/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions datamasque/client/dmclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -40,6 +41,7 @@ class DataMasqueClient(
RGConfigClient,
UserClient,
SettingsClient,
InstanceSecretClient,
):
"""
Client for a DataMasque server instance.
Expand Down
48 changes: 48 additions & 0 deletions datamasque/client/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import enum
from typing import TYPE_CHECKING

from requests import Response
Expand Down Expand Up @@ -103,6 +104,53 @@ 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"
Comment thread
cph-datamasque marked this conversation as resolved.
Resolved
"""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"
"""The instance secret in the response code could not be opened."""
invalid_secret = "invalid_secret"
"""The response code contains an invalid instance secret."""
same_secret = "same_secret"
"""This DataMasque instance already has the same instance secret as the other DataMasque instance."""
active_runs = "active_runs"
"""Runs are in progress. Cancel them or wait for them to finish."""
verification_stale = "verification_stale"
"""The instance secret changed or was shared since the response code was verified. Verify the response again."""
host_header_too_long = "host_header_too_long"
"""The hostname used to access DataMasque is longer than 253 characters, the longest that DNS allows."""
insecure_instance_secret = "insecure_instance_secret"
"""The instance secret is too short, or contains invalid characters. Rotate it, then try again."""


class InstanceSecretLinkError(DataMasqueApiError):
"""
Raised when a step of instance secret linking fails, for example because a code has expired.

The reason is on the `.code` attribute, and the message says what to do next.
"""

def __init__(self, message: str, *, code: InstanceSecretLinkErrorCode, response: Response) -> None:
super().__init__(message, response=response)
self.code = code


class DataMasqueTransportError(DataMasqueException):
"""
Raised when a request to the DataMasque server fails before any response is received.
Expand Down
241 changes: 241 additions & 0 deletions datamasque/client/instance_secret.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
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,
InstanceSecretLink,
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)
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)
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,
)
"""

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/", require_status_check=False)
self._raise_for_link_error(response)
fingerprint: str = response.json()["fingerprint"]
return fingerprint

def get_current_instance_secret_links(self) -> list[InstanceSecretLink]:
"""
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 request fails, for example because the user is not an admin user.
"""

response = self.make_request("GET", "/api/instance-secret/current-links/")
return [InstanceSecretLink.model_validate(link) for link in response.json()["links"]]

def rotate_instance_secret(self) -> InFlightSyncResult:
"""
Replaces the instance secret of this DataMasque instance with a newly generated one.

Requires an admin user.
Hashed output of masking runs and in-flight masking changes differs from before this call,
and the instance no longer has the same instance secret as any DataMasque instance it was linked with.
Once this succeeds, masking runs use the new instance secret.
Returns an `InFlightSyncResult` stating whether the 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 request fails, for example because the user is not an admin user.
"""

response = self.make_request("POST", "/api/instance-secret/rotate/")
return InFlightSyncResult(response.json()["in_flight_sync"])

def create_instance_secret_link_request(self) -> InstanceSecretLinkRequest:
"""
Creates a request code for joining the instance secret of another DataMasque instance.

Pass the request code to `accept_instance_secret_link_request` on the sharing DataMasque instance.
The new request code replaces the pending one, which can then no longer be used.

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/", require_status_check=False)
self._raise_for_link_error(response)
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.
DataMasqueApiError: the request fails for another reason.
"""

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.
DataMasqueApiError: the request fails for another reason.
"""

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.
DataMasqueApiError: the request fails for another reason.
"""

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 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(
"/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)
self._raise_for_link_error(response, request_data=data)
return 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)
Loading
Loading