Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 9 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@
History
=======

1.8.0 (unreleased)
------------------

* Added methods for the instance secret fingerprint and for linking the instance secret with another DataMasque instance.
* Added ``rotate_instance_secret``, which replaces the instance secret with a newly generated one.
* Added ``get_current_instance_secret_links``, which returns the links that rotating the instance secret would end.

Requires server version TBD

1.7.0 (unreleased)
------------------

Expand Down
22 changes: 22 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,16 @@
RulesetPlanPartialUpdateRequest,
RulesetPlanUpdateRequest,
)
from datamasque.client.models.instance_secret import (
InFlightSyncResult,
InstanceSecretEvent,
InstanceSecretEventId,
InstanceSecretEventKind,
InstanceSecretLinkRequest,
InstanceSecretLinkRequestVerification,
InstanceSecretLinkResponse,
InstanceSecretLinkResponseVerification,
)
from datamasque.client.models.license import LicenseInfo, SwitchableLicenseMetadata
from datamasque.client.models.project import (
Project,
Expand Down Expand Up @@ -309,6 +321,16 @@
"IfmTokenInfo",
"InDataDiscoveryConfig",
"InDataDiscoveryRule",
"InFlightSyncResult",
"InstanceSecretEvent",
"InstanceSecretEventId",
"InstanceSecretEventKind",
"InstanceSecretLinkError",
"InstanceSecretLinkErrorCode",
"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
46 changes: 46 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,51 @@ def __init__(self, message: str, *, response: Response, conflicts: "list[Resourc
self.conflicts = conflicts


class InstanceSecretLinkErrorCode(enum.Enum):
"""Why a step of instance secret linking failed."""

malformed_code = "malformed_code"
"""The code is not a valid link code."""
newer_link_format = "newer_link_format"
"""The code was created by a newer version of DataMasque."""
wrong_code_kind = "wrong_code_kind"
"""A response code was given where a request code was expected, or the other way round."""
invalid_public_key = "invalid_public_key"
"""The request code contains a key that is not valid."""
own_request = "own_request"
"""The linking request was sent to the same DataMasque instance that generated it."""
request_expired = "request_expired"
"""The request code has expired. Create a new request code."""
unknown_request = "unknown_request"
"""The request that matches the response code was not found."""
unseal_failed = "unseal_failed"
"""The instance secret in the response code could not be opened."""
invalid_secret = "invalid_secret"
"""The response code contains an invalid instance secret."""
same_secret = "same_secret"
"""This DataMasque instance already has the same instance secret as the other DataMasque instance."""
active_runs = "active_runs"
"""Runs are in progress. Cancel them or wait for them to finish."""
verification_stale = "verification_stale"
"""The instance secret changed or was shared since the response code was verified. Verify the response again."""
host_header_too_long = "host_header_too_long"
"""The hostname used to access DataMasque is longer than 253 characters, the longest that DNS allows."""
insecure_instance_secret = "insecure_instance_secret"
"""The instance secret of this DataMasque instance is not secure enough to share. Rotate it, then try again."""


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

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

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


class DataMasqueTransportError(DataMasqueException):
"""
Raised when a request to the DataMasque server fails before any response is received.
Expand Down
215 changes: 215 additions & 0 deletions datamasque/client/instance_secret.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
from typing import Optional

from requests import Response

from datamasque.client.base import BaseClient
from datamasque.client.exceptions import InstanceSecretLinkError, InstanceSecretLinkErrorCode
from datamasque.client.models.instance_secret import (
InFlightSyncResult,
InstanceSecretEvent,
InstanceSecretLinkRequest,
InstanceSecretLinkRequestVerification,
InstanceSecretLinkResponse,
InstanceSecretLinkResponseVerification,
)


class InstanceSecretClient(BaseClient):
"""
Instance secret and instance secret linking API methods, mixed into `DataMasqueClient`.

Linking gives two DataMasque instances the same instance secret, so that they produce the same hashed output.
The joining instance creates a request code, the sharing instance accepts it and returns a response code,
and the joining instance accepts that response code and adopts the instance secret in it.

Compare the fingerprints from both DataMasque instances before each accept step.
That comparison protects against a code being swapped on its way between the instances,
so when the codes travel through another person or system, compare the fingerprints over a separate channel.

Example usage, with one client for each DataMasque instance:

.. code-block:: python

# On the joining instance: create a request code.
link_request = joining_client.create_instance_secret_link_request()

# On the sharing instance: check the request fingerprint, then share the instance secret.
request_verification = sharing_client.verify_instance_secret_link_request(link_request.request_code)
assert request_verification.fingerprint == link_request.fingerprint
link_response = sharing_client.accept_instance_secret_link_request(link_request.request_code)

# On the joining instance: check the response fingerprint, then adopt the instance secret.
response_verification = joining_client.verify_instance_secret_link_response(link_response.response_code)
assert response_verification.response_fingerprint == link_response.response_fingerprint
joining_client.accept_instance_secret_link_response(
link_response.response_code,
response_verification.verification_token,
)
"""

def get_instance_secret_fingerprint(self) -> str:
"""
Returns the fingerprint of the instance secret of this DataMasque instance.

Two DataMasque instances have the same fingerprint only when they have the same instance secret.
"""

response = self.make_request("GET", "/api/instance-secret/")
fingerprint: str = response.json()["fingerprint"]
return fingerprint

def get_current_instance_secret_links(self) -> list[InstanceSecretEvent]:
"""
Returns the shares and adoptions that link this DataMasque instance with others, newest first.

These are the links that `rotate_instance_secret` would end, and the list is empty after a rotation.
Another DataMasque instance can rotate or restore its own instance secret without telling this one,
so a link listed here may have ended already.
Requires an admin user, and works on every license type.

Raises:
DataMasqueApiError: the user is not an admin user.
"""

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

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

Requires an admin user.
Hashed output of masking runs and in-flight masking changes differs from before this call,
and the instance no longer has the same instance secret as any DataMasque instance it was linked with.
Once this succeeds, masking runs use the new instance secret.
Returns an `InFlightSyncResult` stating whether the IFM service successfully received the new instance secret.
If DataMasque fails to notify the IFM service,
a DataMasque restart is required for in-flight masking to use the new instance secret.

Raises:
DataMasqueApiError: the user is not an admin user.
"""

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

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

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

response = self.make_request("POST", "/api/instance-secret/link/request/")
return InstanceSecretLinkRequest.model_validate(response.json())

def get_pending_instance_secret_link_request(self) -> Optional[InstanceSecretLinkRequest]:
"""
Returns the pending request code of this DataMasque instance.

Returns `None` when there is no request, or it has expired, been cancelled or been used.
"""

response = self.make_request("GET", "/api/instance-secret/link/request/", require_status_check=False)
if response.status_code == 404:
return None

self._raise_for_status(response)
return InstanceSecretLinkRequest.model_validate(response.json())

def cancel_instance_secret_link_request(self) -> None:
"""Cancels the pending request code, so that it can no longer be used, or does nothing if there is none."""

self.make_request("DELETE", "/api/instance-secret/link/request/")

def verify_instance_secret_link_request(self, request_code: str) -> InstanceSecretLinkRequestVerification:
"""
Verifies a request code from the joining DataMasque instance, without changing anything.

Call this on the sharing DataMasque instance.

Raises:
ValueError: `request_code` is empty.
InstanceSecretLinkError: the request code is not valid.
"""

response = self._post_link_step("/api/instance-secret/link/request/verify/", {"request_code": request_code})
return InstanceSecretLinkRequestVerification.model_validate(response.json())

def accept_instance_secret_link_request(self, request_code: str) -> InstanceSecretLinkResponse:
"""
Shares the instance secret of this DataMasque instance with the instance that created the request code.

Call this on the sharing DataMasque instance,
and pass the response code to `verify_instance_secret_link_response` on the joining instance.

Raises:
ValueError: `request_code` is empty.
InstanceSecretLinkError: the request code is not valid.
"""

response = self._post_link_step("/api/instance-secret/link/request/accept/", {"request_code": request_code})
return InstanceSecretLinkResponse.model_validate(response.json())

def verify_instance_secret_link_response(self, response_code: str) -> InstanceSecretLinkResponseVerification:
"""
Verifies a response code from the sharing DataMasque instance, without changing anything.

Call this on the joining DataMasque instance,
and pass the returned `verification_token` to `accept_instance_secret_link_response`.

Raises:
ValueError: `response_code` is empty.
InstanceSecretLinkError: the response code is not valid.
"""

response = self._post_link_step(
"/api/instance-secret/link/response/verify/",
{"response_code": response_code},
)
return InstanceSecretLinkResponseVerification.model_validate(response.json())

def accept_instance_secret_link_response(self, response_code: str, verification_token: str) -> InFlightSyncResult:
"""
Accepts the response code and adopts its instance secret as the instance secret of this DataMasque instance.

Call this on the joining DataMasque instance,
with the `verification_token` from `verify_instance_secret_link_response` for the same response code.
Once this succeeds, masking runs use the new instance secret.
Returns an `InFlightSyncResult` stating whether the IFM service successfully received the new instance secret.
If DataMasque fails to notify the IFM service,
a DataMasque restart is required for in-flight masking to use the new instance secret.

Raises:
ValueError: `response_code` or `verification_token` is empty.
InstanceSecretLinkError: the response code is not valid, runs are in progress,
or the instance secret changed or was shared since the response code was verified.
"""

response = self._post_link_step(
"/api/instance-secret/link/response/accept/",
{"response_code": response_code, "verification_token": verification_token},
)
return InFlightSyncResult(response.json()["in_flight_sync"])

def _post_link_step(self, path: str, data: dict[str, str]) -> Response:
for name, value in data.items():
if not value:
raise ValueError(f"`{name}` must not be empty.")

response = self.make_request("POST", path, data=data, require_status_check=False)
if response.status_code == 400:
# A 400 that is not a link error, or has a code that this version of the client does not know,
# is raised as a plain API error.
try:
error = response.json()
code = InstanceSecretLinkErrorCode(error["code"])
message = error["message"]
except (ValueError, KeyError, TypeError):
pass
else:
raise InstanceSecretLinkError(message, code=code, response=response)

self._raise_for_status(response, request_data=data)
return response
Loading
Loading