Repository navigation
DM-4710-Epic/instance secret linking #91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andrewchester-dm
wants to merge
17
commits into
main
Choose a base branch
from
epic/instance-secret-linking
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 a78fd43
feat: replace the event peer fingerprint with the request and respons…
cph-datamasque ce0cb0e
feat: add the insecure instance secret linking error code
cph-datamasque 1933a6f
feat: DM-5075 add rotate_instance_secret
andrewchester-dm 71edcaf
refactor: remove the instance secret link history method and model
kw-datamasque 0f1d825
docs: DM-4856 reword the stale verification text now the link history…
andrewchester-dm ce16cce
test: assert every field of a link ending, for shared and adopted
kw-datamasque 0887191
feat: add get_current_instance_secret_links
jiatolentino 7260695
Merge pull request #83 from datamasque/DM-5075-rotate-instance-secret
andrewchester-dm 86a52d1
Merge pull request #87 from datamasque/current-instance-secret-links
jiatolentino 8d346d9
fix(instance-secret): DM-5734 review fixes, rename the link fields an…
andrewchester-dm dfc0c3e
fix(instance-secret): DM-5734 address the PR review comments: error c…
andrewchester-dm 3468252
docs(instance-secret): DM-4710 describe the weak instance secret erro…
andrewchester-dm 5d7cfd6
docs(instance-secret): DM-4710 say "uses invalid characters" for the …
andrewchester-dm 41abcfc
docs(instance-secret): DM-4710 say "contains invalid characters" for …
andrewchester-dm 734fd9b
fix(instance-secret): DM-4710 raise InstanceSecretLinkError from link…
andrewchester-dm 5d56dc7
refactor(instance-secret): DM-4710 raise the plain API error from _ra…
andrewchester-dm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.