diff --git a/changelog/+clone-request-context.fixed.md b/changelog/+clone-request-context.fixed.md new file mode 100644 index 000000000..080683803 --- /dev/null +++ b/changelog/+clone-request-context.fixed.md @@ -0,0 +1 @@ +Fixed `clone()` returning a client without the original client's request context. Changes saved by generators, transforms and checks were therefore sent without that account, and Infrahub recorded them against the account of the client's token. diff --git a/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx b/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx index 1b4b0356a..9f9e57e75 100644 --- a/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx +++ b/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx @@ -394,7 +394,7 @@ client default for these requests only. When None, the client default (if any) i clone(self, branch: str | None = None) -> InfrahubClient ``` -Return a new client with a copy of this client's configuration. +Return a new client with a copy of this client's configuration and request context. **Args:** @@ -763,7 +763,7 @@ Return user permissions. clone(self, branch: str | None = None) -> InfrahubClientSync ``` -Return a new client with a copy of this client's configuration. +Return a new client with a copy of this client's configuration and request context. **Args:** diff --git a/infrahub_sdk/client.py b/infrahub_sdk/client.py index 57974adcc..5d5fde59f 100644 --- a/infrahub_sdk/client.py +++ b/infrahub_sdk/client.py @@ -1572,7 +1572,7 @@ async def process_non_batch() -> tuple[list[InfrahubNode], list[InfrahubNode]]: return nodes def clone(self, branch: str | None = None) -> InfrahubClient: - """Return a new client with a copy of this client's configuration. + """Return a new client with a copy of this client's configuration and request context. Args: branch: Branch that the new client targets by default. When set, it takes @@ -1580,7 +1580,9 @@ def clone(self, branch: str | None = None) -> InfrahubClient: read its branch from the local Git repository. When not set, the new client finds its default branch the same way this client did. """ - return InfrahubClient(config=self.config.clone(branch=branch)) + clone = InfrahubClient(config=self.config.clone(branch=branch)) + clone._request_context = self._request_context.model_copy(deep=True) if self._request_context else None + return clone async def execute_graphql( self, @@ -2667,7 +2669,7 @@ def delete(self, kind: str | type[SchemaTypeSync], id: str, branch: str | None = node.delete() def clone(self, branch: str | None = None) -> InfrahubClientSync: - """Return a new client with a copy of this client's configuration. + """Return a new client with a copy of this client's configuration and request context. Args: branch: Branch that the new client targets by default. When set, it takes @@ -2675,7 +2677,9 @@ def clone(self, branch: str | None = None) -> InfrahubClientSync: read its branch from the local Git repository. When not set, the new client finds its default branch the same way this client did. """ - return InfrahubClientSync(config=self.config.clone(branch=branch)) + clone = InfrahubClientSync(config=self.config.clone(branch=branch)) + clone._request_context = self._request_context.model_copy(deep=True) if self._request_context else None + return clone def execute_graphql( self, diff --git a/tests/unit/sdk/test_client.py b/tests/unit/sdk/test_client.py index a164fa4b8..d5323a250 100644 --- a/tests/unit/sdk/test_client.py +++ b/tests/unit/sdk/test_client.py @@ -10,6 +10,7 @@ import pytest from infrahub_sdk import Config, InfrahubClient, InfrahubClientSync +from infrahub_sdk.context import ContextAccount, RequestContext from infrahub_sdk.exceptions import ( ApiError, NodeNotFoundError, @@ -750,6 +751,29 @@ async def test_clone(clients: BothClients, client_type: str) -> None: assert clients.sync.default_branch == clone.default_branch +@pytest.mark.parametrize("client_type", client_types) +async def test_clone_keeps_request_context(clients: BothClients, client_type: str) -> None: + """A cloned client sends its requests with the same account as the original client.""" + client = getattr(clients, client_type) + client.request_context = RequestContext(account=ContextAccount(id="account-1")) + + clone = client.clone(branch="my_other_branch") + + assert clone.request_context == RequestContext(account=ContextAccount(id="account-1")) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_clone_request_context_is_independent(clients: BothClients, client_type: str) -> None: + """Changing the account of a cloned client does not change the account of the original client.""" + client = getattr(clients, client_type) + client.request_context = RequestContext(account=ContextAccount(id="account-1")) + + clone = client.clone() + clone.request_context.account = ContextAccount(id="account-2") + + assert client.request_context == RequestContext(account=ContextAccount(id="account-1")) + + @pytest.mark.parametrize("client_type", client_types) async def test_clone_define_branch(clients: BothClients, client_type: str) -> None: """Validate that the clone branch parameter sets the correct branch of the cloned client.""" diff --git a/tests/unit/sdk/test_generator.py b/tests/unit/sdk/test_generator.py new file mode 100644 index 000000000..a19598a10 --- /dev/null +++ b/tests/unit/sdk/test_generator.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from infrahub_sdk import Config, InfrahubClient +from infrahub_sdk.context import ContextAccount, RequestContext +from infrahub_sdk.generator import InfrahubGenerator +from infrahub_sdk.node import InfrahubNode + +if TYPE_CHECKING: + from pytest_httpx import HTTPXMock + + from infrahub_sdk.schema import NodeSchemaAPI + +GENERATOR_GROUP_SCHEMA = { + "generics": [{"name": "Node", "namespace": "Core"}], + "nodes": [ + { + "name": "GeneratorGroup", + "namespace": "Core", + "attributes": [ + {"name": "name", "kind": "Text", "unique": True}, + {"name": "description", "kind": "Text", "optional": True}, + ], + "relationships": [{"name": "members", "peer": "CoreNode", "cardinality": "many", "optional": True}], + } + ], +} + + +class LocationGenerator(InfrahubGenerator): + location_schema: NodeSchemaAPI + + async def generate(self, data: dict) -> None: + location = InfrahubNode( + client=self.client, + schema=self.location_schema, + data={"name": {"value": "JFK1"}, "type": {"value": "SITE"}}, + ) + await location.save(update_group_context=False) + + +async def test_generator_writes_carry_the_client_request_context( + location_schema: NodeSchemaAPI, httpx_mock: HTTPXMock +) -> None: + """A generator sends its writes with the account of the client it was given.""" + httpx_mock.add_response( + method="POST", url="http://mock/api/query/locations?branch=main&update_group=true", json={"data": {}} + ) + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json={ + "data": {"BuiltinLocationCreate": {"ok": True, "object": {"id": "17aec828-9814-ce00-3f20-1a053670f1c8"}}} + }, + ) + httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main", json=GENERATOR_GROUP_SCHEMA) + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json={"data": {"CoreGeneratorGroup": {"count": 0, "edges": []}}}, + ) + client = InfrahubClient(config=Config(address="http://mock")) + client.request_context = RequestContext(account=ContextAccount(id="account-1")) + + generator = LocationGenerator(query="locations", client=client, branch="main", infrahub_node=InfrahubNode) + generator.location_schema = location_schema + await generator.run(identifier="location-generator") + + mutation = httpx_mock.get_requests(url="http://mock/graphql/main")[0] + query = " ".join(json.loads(mutation.content)["query"].split()) + assert "BuiltinLocationCreate" in query + assert 'context: { account: { id: "account-1" } }' in query