Skip to content
Merged
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
1 change: 1 addition & 0 deletions changelog/+clone-request-context.fixed.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:**

Expand Down Expand Up @@ -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:**

Expand Down
12 changes: 8 additions & 4 deletions infrahub_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1572,15 +1572,17 @@ 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
priority over `default_branch_from_git`, and the new client does not
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,
Expand Down Expand Up @@ -2667,15 +2669,17 @@ 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
priority over `default_branch_from_git`, and the new client does not
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,
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/sdk/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""
Expand Down
74 changes: 74 additions & 0 deletions tests/unit/sdk/test_generator.py
Original file line number Diff line number Diff line change
@@ -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
Loading