inmanta-module-netbird 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- inmanta_module_netbird-0.1.0/MANIFEST.in +5 -0
- inmanta_module_netbird-0.1.0/PKG-INFO +72 -0
- inmanta_module_netbird-0.1.0/README.md +60 -0
- inmanta_module_netbird-0.1.0/inmanta_module_netbird.egg-info/PKG-INFO +72 -0
- inmanta_module_netbird-0.1.0/inmanta_module_netbird.egg-info/SOURCES.txt +19 -0
- inmanta_module_netbird-0.1.0/inmanta_module_netbird.egg-info/dependency_links.txt +1 -0
- inmanta_module_netbird-0.1.0/inmanta_module_netbird.egg-info/not-zip-safe +1 -0
- inmanta_module_netbird-0.1.0/inmanta_module_netbird.egg-info/requires.txt +3 -0
- inmanta_module_netbird-0.1.0/inmanta_module_netbird.egg-info/top_level.txt +1 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/__init__.py +371 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/files/.gitkeep +0 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/helpers.py +237 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/model/_init.cf +140 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/py.typed +0 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/setup.cfg +72 -0
- inmanta_module_netbird-0.1.0/inmanta_plugins/netbird/templates/.gitkeep +0 -0
- inmanta_module_netbird-0.1.0/pyproject.toml +3 -0
- inmanta_module_netbird-0.1.0/setup.cfg +54 -0
- inmanta_module_netbird-0.1.0/tests/test_basics.py +25 -0
- inmanta_module_netbird-0.1.0/tests/test_user.py +225 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: inmanta-module-netbird
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple module to manage netbird resources
|
|
5
|
+
Author: Guillaume Everarts de Velp
|
|
6
|
+
Author-email: edvgui@gmail.com
|
|
7
|
+
License: ASL 2.0
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: inmanta-module-std<9,>=4.0
|
|
10
|
+
Requires-Dist: inmanta-module-files<3,>=2.11.0
|
|
11
|
+
Requires-Dist: inmanta-core>=15.1.0
|
|
12
|
+
|
|
13
|
+
# inmanta-module-netbird
|
|
14
|
+
|
|
15
|
+
[](https://pypi.python.org/pypi/inmanta-module-netbird/)
|
|
16
|
+
[](https://github.com/edvgui/inmanta-module-netbird/actions)
|
|
17
|
+
|
|
18
|
+
This package is an adapter that is meant to be used with the inmanta orchestrator: https://docs.inmanta.com
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
This module allows to manage [netbird](https://netbird.io) resources, through the netbird management api.
|
|
23
|
+
|
|
24
|
+
The module is a work in progress, it currently contains the base entities every
|
|
25
|
+
resource of this module builds upon:
|
|
26
|
+
1. `netbird::Api`: the endpoint and credentials used to reach the netbird management api.
|
|
27
|
+
2. `netbird::ResourceABC`: the base entity for all the resources managed by this module.
|
|
28
|
+
3. `netbird::JsonObjectABC`: the base entity for every object of the netbird api.
|
|
29
|
+
|
|
30
|
+
And the following resources:
|
|
31
|
+
1. `netbird::User`: a user, or a service user, of the netbird account.
|
|
32
|
+
|
|
33
|
+
Every netbird object is co-managed with whoever else edits the account: an attribute
|
|
34
|
+
left `null` in the model keeps the value the api currently holds, only the values the
|
|
35
|
+
model sets are enforced. The api addresses its objects by opaque ids, and so does
|
|
36
|
+
this module: `netbird::ResourceABC.id` is a reference resolving the id of an object
|
|
37
|
+
from the facts its resource publishes, to be fed to whatever other resource points at
|
|
38
|
+
it.
|
|
39
|
+
|
|
40
|
+
## Example
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
import netbird
|
|
44
|
+
|
|
45
|
+
api = netbird::Api(
|
|
46
|
+
agent_name="netbird",
|
|
47
|
+
management_url="https://api.netbird.io",
|
|
48
|
+
api_token=std::get_env("NETBIRD_TOKEN"),
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
netbird::User(
|
|
52
|
+
api=api,
|
|
53
|
+
name="Alice",
|
|
54
|
+
email="alice@example.com",
|
|
55
|
+
role="admin",
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Find more examples in the `tests` folder of this module!
|
|
60
|
+
|
|
61
|
+
## Development
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
python3 -m venv .venv
|
|
65
|
+
source .venv/bin/activate
|
|
66
|
+
make install
|
|
67
|
+
pytest tests
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The tests deploy a netbird server locally, in a podman container of their own, and
|
|
71
|
+
run against its api. The container is started again for each test, so that every
|
|
72
|
+
test sees a fresh, empty account. They are skipped when podman is not available.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# inmanta-module-netbird
|
|
2
|
+
|
|
3
|
+
[](https://pypi.python.org/pypi/inmanta-module-netbird/)
|
|
4
|
+
[](https://github.com/edvgui/inmanta-module-netbird/actions)
|
|
5
|
+
|
|
6
|
+
This package is an adapter that is meant to be used with the inmanta orchestrator: https://docs.inmanta.com
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
This module allows to manage [netbird](https://netbird.io) resources, through the netbird management api.
|
|
11
|
+
|
|
12
|
+
The module is a work in progress, it currently contains the base entities every
|
|
13
|
+
resource of this module builds upon:
|
|
14
|
+
1. `netbird::Api`: the endpoint and credentials used to reach the netbird management api.
|
|
15
|
+
2. `netbird::ResourceABC`: the base entity for all the resources managed by this module.
|
|
16
|
+
3. `netbird::JsonObjectABC`: the base entity for every object of the netbird api.
|
|
17
|
+
|
|
18
|
+
And the following resources:
|
|
19
|
+
1. `netbird::User`: a user, or a service user, of the netbird account.
|
|
20
|
+
|
|
21
|
+
Every netbird object is co-managed with whoever else edits the account: an attribute
|
|
22
|
+
left `null` in the model keeps the value the api currently holds, only the values the
|
|
23
|
+
model sets are enforced. The api addresses its objects by opaque ids, and so does
|
|
24
|
+
this module: `netbird::ResourceABC.id` is a reference resolving the id of an object
|
|
25
|
+
from the facts its resource publishes, to be fed to whatever other resource points at
|
|
26
|
+
it.
|
|
27
|
+
|
|
28
|
+
## Example
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
import netbird
|
|
32
|
+
|
|
33
|
+
api = netbird::Api(
|
|
34
|
+
agent_name="netbird",
|
|
35
|
+
management_url="https://api.netbird.io",
|
|
36
|
+
api_token=std::get_env("NETBIRD_TOKEN"),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
netbird::User(
|
|
40
|
+
api=api,
|
|
41
|
+
name="Alice",
|
|
42
|
+
email="alice@example.com",
|
|
43
|
+
role="admin",
|
|
44
|
+
)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Find more examples in the `tests` folder of this module!
|
|
48
|
+
|
|
49
|
+
## Development
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
python3 -m venv .venv
|
|
53
|
+
source .venv/bin/activate
|
|
54
|
+
make install
|
|
55
|
+
pytest tests
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The tests deploy a netbird server locally, in a podman container of their own, and
|
|
59
|
+
run against its api. The container is started again for each test, so that every
|
|
60
|
+
test sees a fresh, empty account. They are skipped when podman is not available.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: inmanta-module-netbird
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple module to manage netbird resources
|
|
5
|
+
Author: Guillaume Everarts de Velp
|
|
6
|
+
Author-email: edvgui@gmail.com
|
|
7
|
+
License: ASL 2.0
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: inmanta-module-std<9,>=4.0
|
|
10
|
+
Requires-Dist: inmanta-module-files<3,>=2.11.0
|
|
11
|
+
Requires-Dist: inmanta-core>=15.1.0
|
|
12
|
+
|
|
13
|
+
# inmanta-module-netbird
|
|
14
|
+
|
|
15
|
+
[](https://pypi.python.org/pypi/inmanta-module-netbird/)
|
|
16
|
+
[](https://github.com/edvgui/inmanta-module-netbird/actions)
|
|
17
|
+
|
|
18
|
+
This package is an adapter that is meant to be used with the inmanta orchestrator: https://docs.inmanta.com
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
This module allows to manage [netbird](https://netbird.io) resources, through the netbird management api.
|
|
23
|
+
|
|
24
|
+
The module is a work in progress, it currently contains the base entities every
|
|
25
|
+
resource of this module builds upon:
|
|
26
|
+
1. `netbird::Api`: the endpoint and credentials used to reach the netbird management api.
|
|
27
|
+
2. `netbird::ResourceABC`: the base entity for all the resources managed by this module.
|
|
28
|
+
3. `netbird::JsonObjectABC`: the base entity for every object of the netbird api.
|
|
29
|
+
|
|
30
|
+
And the following resources:
|
|
31
|
+
1. `netbird::User`: a user, or a service user, of the netbird account.
|
|
32
|
+
|
|
33
|
+
Every netbird object is co-managed with whoever else edits the account: an attribute
|
|
34
|
+
left `null` in the model keeps the value the api currently holds, only the values the
|
|
35
|
+
model sets are enforced. The api addresses its objects by opaque ids, and so does
|
|
36
|
+
this module: `netbird::ResourceABC.id` is a reference resolving the id of an object
|
|
37
|
+
from the facts its resource publishes, to be fed to whatever other resource points at
|
|
38
|
+
it.
|
|
39
|
+
|
|
40
|
+
## Example
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
import netbird
|
|
44
|
+
|
|
45
|
+
api = netbird::Api(
|
|
46
|
+
agent_name="netbird",
|
|
47
|
+
management_url="https://api.netbird.io",
|
|
48
|
+
api_token=std::get_env("NETBIRD_TOKEN"),
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
netbird::User(
|
|
52
|
+
api=api,
|
|
53
|
+
name="Alice",
|
|
54
|
+
email="alice@example.com",
|
|
55
|
+
role="admin",
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Find more examples in the `tests` folder of this module!
|
|
60
|
+
|
|
61
|
+
## Development
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
python3 -m venv .venv
|
|
65
|
+
source .venv/bin/activate
|
|
66
|
+
make install
|
|
67
|
+
pytest tests
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The tests deploy a netbird server locally, in a podman container of their own, and
|
|
71
|
+
run against its api. The container is started again for each test, so that every
|
|
72
|
+
test sees a fresh, empty account. They are skipped when podman is not available.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
MANIFEST.in
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
setup.cfg
|
|
5
|
+
inmanta_module_netbird.egg-info/PKG-INFO
|
|
6
|
+
inmanta_module_netbird.egg-info/SOURCES.txt
|
|
7
|
+
inmanta_module_netbird.egg-info/dependency_links.txt
|
|
8
|
+
inmanta_module_netbird.egg-info/not-zip-safe
|
|
9
|
+
inmanta_module_netbird.egg-info/requires.txt
|
|
10
|
+
inmanta_module_netbird.egg-info/top_level.txt
|
|
11
|
+
inmanta_plugins/netbird/__init__.py
|
|
12
|
+
inmanta_plugins/netbird/helpers.py
|
|
13
|
+
inmanta_plugins/netbird/py.typed
|
|
14
|
+
inmanta_plugins/netbird/setup.cfg
|
|
15
|
+
inmanta_plugins/netbird/files/.gitkeep
|
|
16
|
+
inmanta_plugins/netbird/model/_init.cf
|
|
17
|
+
inmanta_plugins/netbird/templates/.gitkeep
|
|
18
|
+
tests/test_basics.py
|
|
19
|
+
tests/test_user.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
inmanta_plugins
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright 2026 Guillaume Everarts de Velp
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
|
|
16
|
+
Contact: edvgui@gmail.com
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import copy
|
|
20
|
+
import typing
|
|
21
|
+
from dataclasses import asdict
|
|
22
|
+
|
|
23
|
+
import pydantic
|
|
24
|
+
import requests
|
|
25
|
+
from inmanta_plugins.files.json import Operation, serialize_for_resource, update
|
|
26
|
+
|
|
27
|
+
import inmanta.agent.handler
|
|
28
|
+
import inmanta.execute.proxy
|
|
29
|
+
import inmanta.export
|
|
30
|
+
import inmanta.resources
|
|
31
|
+
from inmanta.util import dict_path
|
|
32
|
+
from inmanta_plugins.netbird.helpers import Session
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ResourceABC(
|
|
36
|
+
inmanta.resources.PurgeableResource, inmanta.resources.ManagedResource
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
Base exporter class for all netbird resources.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
# inmanta infers the type of the parent's fields from its own literal, which
|
|
43
|
+
# makes any tuple of another length look like an invalid override
|
|
44
|
+
fields: tuple[str, ...] = ( # type: ignore[assignment]
|
|
45
|
+
"management_url",
|
|
46
|
+
"api_token",
|
|
47
|
+
"desired_state",
|
|
48
|
+
)
|
|
49
|
+
management_url: str
|
|
50
|
+
api_token: str
|
|
51
|
+
|
|
52
|
+
# The json object the model wants, serialized from the entity itself: every
|
|
53
|
+
# netbird object is a json object, and the resource is its own desired state.
|
|
54
|
+
desired_state: list[dict]
|
|
55
|
+
|
|
56
|
+
# The object as the api holds it, narrowed down to the keys that take part in the
|
|
57
|
+
# diff. Filled in by the handler, it is not exported.
|
|
58
|
+
body: dict = {}
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def get_desired_state(
|
|
62
|
+
cls, _: inmanta.export.Exporter, entity: inmanta.execute.proxy.DynamicProxy
|
|
63
|
+
) -> list[dict]:
|
|
64
|
+
return [asdict(s) for s in serialize_for_resource(entity.root, entity)]
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def get_management_url(
|
|
68
|
+
cls, _: inmanta.export.Exporter, entity: inmanta.execute.proxy.DynamicProxy
|
|
69
|
+
) -> str:
|
|
70
|
+
return entity.api.management_url
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def get_api_token(
|
|
74
|
+
cls, _: inmanta.export.Exporter, entity: inmanta.execute.proxy.DynamicProxy
|
|
75
|
+
) -> str:
|
|
76
|
+
return entity.api.api_token
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
T = typing.TypeVar("T")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def process_netbird_response(
|
|
83
|
+
response: requests.Response,
|
|
84
|
+
*,
|
|
85
|
+
expected_type: type[T] = object, # type: ignore[assignment]
|
|
86
|
+
) -> T:
|
|
87
|
+
"""
|
|
88
|
+
Helper method to process a response from the netbird api, and easily render
|
|
89
|
+
the errors we received, if any.
|
|
90
|
+
|
|
91
|
+
:param response: The response object requests built from the api response.
|
|
92
|
+
:param expected_type: The type of the result we expect to get from the api.
|
|
93
|
+
"""
|
|
94
|
+
if not response.ok:
|
|
95
|
+
try:
|
|
96
|
+
error = response.json()
|
|
97
|
+
except requests.JSONDecodeError:
|
|
98
|
+
# The error is not valid json, let requests build the error for us
|
|
99
|
+
response.raise_for_status()
|
|
100
|
+
raise
|
|
101
|
+
|
|
102
|
+
match error:
|
|
103
|
+
case {"message": str() as message, "code": int() as code}:
|
|
104
|
+
raise RuntimeError(f"The api returned an error ({code}): {message}")
|
|
105
|
+
case _:
|
|
106
|
+
raise RuntimeError(f"The api returned an error: {error}")
|
|
107
|
+
|
|
108
|
+
if not response.content:
|
|
109
|
+
# Some endpoints, like the delete ones, answer with an empty body
|
|
110
|
+
return typing.cast(T, None)
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
body = response.json()
|
|
114
|
+
except requests.JSONDecodeError as e:
|
|
115
|
+
raise RuntimeError(f"Unexpected response from the api: {response.text}") from e
|
|
116
|
+
|
|
117
|
+
if body is None and typing.get_origin(expected_type) is list:
|
|
118
|
+
# A listing endpoint with nothing to list answers with a json null instead of
|
|
119
|
+
# an empty list
|
|
120
|
+
return typing.cast(T, [])
|
|
121
|
+
|
|
122
|
+
adapter = pydantic.TypeAdapter(expected_type)
|
|
123
|
+
try:
|
|
124
|
+
return adapter.validate_python(body)
|
|
125
|
+
except pydantic.ValidationError as e:
|
|
126
|
+
raise RuntimeError(
|
|
127
|
+
f"Unexpected response from api, expected {expected_type} but got {body}"
|
|
128
|
+
) from e
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def find_user(session: Session, name: str) -> dict | None:
|
|
132
|
+
"""
|
|
133
|
+
Find a user of the account by its name, and return None if it doesn't exist. The
|
|
134
|
+
listing is not filtered on the service_user query parameter, so it holds both the
|
|
135
|
+
regular and the service users of the account.
|
|
136
|
+
|
|
137
|
+
The name is what identifies a user here: the api doesn't keep the email address
|
|
138
|
+
of a service user, so it is the only thing every user is guaranteed to have.
|
|
139
|
+
"""
|
|
140
|
+
users = process_netbird_response(
|
|
141
|
+
session.get(url="users"),
|
|
142
|
+
expected_type=list[dict],
|
|
143
|
+
)
|
|
144
|
+
return next((u for u in users if u["name"] == name), None)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
NR = typing.TypeVar("NR", bound=ResourceABC)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class HandlerABC(inmanta.agent.handler.CRUDHandler[NR]):
|
|
151
|
+
"""
|
|
152
|
+
Base handler containing the basic logic to interact with the netbird api.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
# Set up in pre, before any of the crud methods runs
|
|
156
|
+
session: Session
|
|
157
|
+
|
|
158
|
+
@inmanta.agent.handler.cache(
|
|
159
|
+
timeout=60,
|
|
160
|
+
call_on_delete=lambda s: s.close(),
|
|
161
|
+
)
|
|
162
|
+
def get_session(self, management_url: str, api_token: str) -> Session:
|
|
163
|
+
"""
|
|
164
|
+
Setup a session towards a netbird management server api.
|
|
165
|
+
"""
|
|
166
|
+
session = Session(
|
|
167
|
+
base_url=management_url.rstrip("/") + "/api/",
|
|
168
|
+
timeout=30,
|
|
169
|
+
secrets={api_token: "******"},
|
|
170
|
+
cache=True,
|
|
171
|
+
)
|
|
172
|
+
session.headers["Authorization"] = "Token " + api_token
|
|
173
|
+
|
|
174
|
+
return session
|
|
175
|
+
|
|
176
|
+
def pre(self, ctx: inmanta.agent.handler.HandlerContext, resource: NR) -> None:
|
|
177
|
+
# Setup the session object that can be used to access the netbird api
|
|
178
|
+
self.session = self.get_session(resource.management_url, resource.api_token)
|
|
179
|
+
self.session.logger = ctx
|
|
180
|
+
|
|
181
|
+
def publish_ids(
|
|
182
|
+
self, ctx: inmanta.agent.handler.HandlerContext, **ids: str
|
|
183
|
+
) -> None:
|
|
184
|
+
"""
|
|
185
|
+
Publish the identifiers the handler resolved on the api as facts. The api
|
|
186
|
+
addresses every object by an opaque id, which the model never knows: exposing
|
|
187
|
+
them makes it possible to point at an object from outside the model without
|
|
188
|
+
going digging through the api.
|
|
189
|
+
|
|
190
|
+
:param ids: The identifiers to publish, by fact name.
|
|
191
|
+
"""
|
|
192
|
+
for name, value in ids.items():
|
|
193
|
+
ctx.set_fact(name, value, expires=False)
|
|
194
|
+
|
|
195
|
+
def normalize(self, body: dict) -> dict:
|
|
196
|
+
"""
|
|
197
|
+
Put a body in a canonical shape, so that the current and the desired state
|
|
198
|
+
can be compared even when the api returns a collection in another order.
|
|
199
|
+
"""
|
|
200
|
+
return body
|
|
201
|
+
|
|
202
|
+
def merged_body(self, current: dict, resource: NR) -> dict:
|
|
203
|
+
"""
|
|
204
|
+
The object as it should be once the desired state is applied onto the state
|
|
205
|
+
the api currently holds. Everything the model leaves null keeps the value
|
|
206
|
+
the account has for it, and the values the api computes on its own are
|
|
207
|
+
carried along rather than dropped, so that the body the handler writes back
|
|
208
|
+
stays complete even where the model has no opinion.
|
|
209
|
+
|
|
210
|
+
On a create there is nothing to merge onto, and this is the desired state on
|
|
211
|
+
its own.
|
|
212
|
+
|
|
213
|
+
:param current: The object as the api currently holds it.
|
|
214
|
+
:param resource: The resource being deployed, carrying the desired state.
|
|
215
|
+
"""
|
|
216
|
+
return self.normalize(apply_desired_state(current, resource.desired_state))
|
|
217
|
+
|
|
218
|
+
def diff_body(self, body: dict) -> dict:
|
|
219
|
+
"""
|
|
220
|
+
The part of a body that takes part in the diff. The api of an object that
|
|
221
|
+
only accepts some of its values on an update narrows this down: a difference
|
|
222
|
+
the handler has no way to enforce would otherwise show up as a change on
|
|
223
|
+
every single deploy, and never converge.
|
|
224
|
+
|
|
225
|
+
:param body: A full object, as the api holds it or as the model wants it.
|
|
226
|
+
"""
|
|
227
|
+
return body
|
|
228
|
+
|
|
229
|
+
def calculate_diff(
|
|
230
|
+
self,
|
|
231
|
+
ctx: inmanta.agent.handler.HandlerContext,
|
|
232
|
+
current: NR,
|
|
233
|
+
desired: NR,
|
|
234
|
+
) -> dict[str, dict[str, object]]:
|
|
235
|
+
desired.body = self.merged_body(current.body, desired)
|
|
236
|
+
|
|
237
|
+
changes = super().calculate_diff(ctx, current, desired)
|
|
238
|
+
current_body = self.diff_body(current.body)
|
|
239
|
+
desired_body = self.diff_body(desired.body)
|
|
240
|
+
if desired_body != current_body:
|
|
241
|
+
changes["body"] = {"current": current_body, "desired": desired_body}
|
|
242
|
+
|
|
243
|
+
return changes
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def apply_desired_state(current: dict, desired_state: list[dict]) -> dict:
|
|
247
|
+
"""
|
|
248
|
+
Apply the serialized entities describing the desired state onto the state the api
|
|
249
|
+
currently holds. Anything the model doesn't set is left as it is, which is what
|
|
250
|
+
lets this module co-manage an object with whoever else edits it in the dashboard.
|
|
251
|
+
|
|
252
|
+
:param current: The object as the api currently holds it.
|
|
253
|
+
:param desired_state: The serialized object describing the desired state.
|
|
254
|
+
"""
|
|
255
|
+
desired = copy.deepcopy(current)
|
|
256
|
+
for item in desired_state:
|
|
257
|
+
desired = update(
|
|
258
|
+
desired,
|
|
259
|
+
dict_path.to_path(item["path"]),
|
|
260
|
+
Operation(item["operation"]),
|
|
261
|
+
item["value"],
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
return desired
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def select(body: dict, keys: typing.Sequence[str]) -> dict:
|
|
268
|
+
"""
|
|
269
|
+
Narrow a body down to the keys one endpoint of the api takes. The api doesn't
|
|
270
|
+
accept the same values on a create as on an update, and rejects the ones that
|
|
271
|
+
don't belong to the call being made.
|
|
272
|
+
|
|
273
|
+
:param body: The object the handler wants to write.
|
|
274
|
+
:param keys: The keys the endpoint takes.
|
|
275
|
+
"""
|
|
276
|
+
return {key: body[key] for key in keys if key in body}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# The keys of the user object the api takes when a user is created, and the ones it
|
|
280
|
+
# takes when an existing user is updated. They don't overlap fully: the identity of
|
|
281
|
+
# a user is fixed at creation, and a user can only be blocked afterwards.
|
|
282
|
+
USER_CREATE_KEYS = ("email", "name", "role", "auto_groups", "is_service_user")
|
|
283
|
+
USER_UPDATE_KEYS = ("role", "auto_groups", "is_blocked")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@inmanta.resources.resource("netbird::User", "name", "api.agent_name")
|
|
287
|
+
class UserResource(ResourceABC):
|
|
288
|
+
fields = ("name",)
|
|
289
|
+
name: str
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@inmanta.agent.handler.provider("netbird::User", "")
|
|
293
|
+
class UserHandler(HandlerABC[UserResource]):
|
|
294
|
+
def diff_body(self, body: dict) -> dict:
|
|
295
|
+
# The api only takes USER_UPDATE_KEYS on an update, so the values it only
|
|
296
|
+
# accepts at creation are kept out of the diff: the handler could not enforce
|
|
297
|
+
# a change to them anyway.
|
|
298
|
+
return select(body, USER_UPDATE_KEYS)
|
|
299
|
+
|
|
300
|
+
def normalize(self, body: dict) -> dict:
|
|
301
|
+
# The api doesn't preserve the order of the auto groups
|
|
302
|
+
if body.get("auto_groups") is not None:
|
|
303
|
+
body["auto_groups"] = sorted(body["auto_groups"])
|
|
304
|
+
|
|
305
|
+
return body
|
|
306
|
+
|
|
307
|
+
def read_resource(
|
|
308
|
+
self,
|
|
309
|
+
ctx: inmanta.agent.handler.HandlerContext,
|
|
310
|
+
resource: UserResource,
|
|
311
|
+
) -> None:
|
|
312
|
+
user = find_user(self.session, resource.name)
|
|
313
|
+
if user is None:
|
|
314
|
+
raise inmanta.agent.handler.ResourcePurged()
|
|
315
|
+
|
|
316
|
+
ctx.set("ID", user["id"])
|
|
317
|
+
self.publish_ids(ctx, id=user["id"])
|
|
318
|
+
|
|
319
|
+
resource.body = self.normalize(user)
|
|
320
|
+
|
|
321
|
+
def create_resource(
|
|
322
|
+
self,
|
|
323
|
+
ctx: inmanta.agent.handler.HandlerContext,
|
|
324
|
+
resource: UserResource,
|
|
325
|
+
) -> None:
|
|
326
|
+
desired = self.merged_body({}, resource)
|
|
327
|
+
user = process_netbird_response(
|
|
328
|
+
self.session.post(url="users", json=select(desired, USER_CREATE_KEYS)),
|
|
329
|
+
expected_type=dict,
|
|
330
|
+
)
|
|
331
|
+
self.publish_ids(ctx, id=user["id"])
|
|
332
|
+
ctx.set_created()
|
|
333
|
+
|
|
334
|
+
if desired.get("is_blocked"):
|
|
335
|
+
# The api doesn't take the blocked flag when a user is created, so a user
|
|
336
|
+
# the model wants blocked from the start needs a second call. It is
|
|
337
|
+
# built from the user the api just made, as an update has to carry the
|
|
338
|
+
# values the model has no opinion about too.
|
|
339
|
+
process_netbird_response(
|
|
340
|
+
self.session.put(
|
|
341
|
+
url=f"users/{user['id']}",
|
|
342
|
+
json=select(self.merged_body(user, resource), USER_UPDATE_KEYS),
|
|
343
|
+
),
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def update_resource(
|
|
347
|
+
self,
|
|
348
|
+
ctx: inmanta.agent.handler.HandlerContext,
|
|
349
|
+
changes: dict,
|
|
350
|
+
resource: UserResource,
|
|
351
|
+
) -> None:
|
|
352
|
+
# The body calculate_diff merged is the object as the api holds it, with the
|
|
353
|
+
# desired state applied on top. The api only takes part of it on an update,
|
|
354
|
+
# and rejects everything else.
|
|
355
|
+
process_netbird_response(
|
|
356
|
+
self.session.put(
|
|
357
|
+
url=f"users/{ctx.get('ID')}",
|
|
358
|
+
json=select(resource.body, USER_UPDATE_KEYS),
|
|
359
|
+
),
|
|
360
|
+
)
|
|
361
|
+
ctx.set_updated()
|
|
362
|
+
|
|
363
|
+
def delete_resource(
|
|
364
|
+
self,
|
|
365
|
+
ctx: inmanta.agent.handler.HandlerContext,
|
|
366
|
+
resource: UserResource,
|
|
367
|
+
) -> None:
|
|
368
|
+
process_netbird_response(
|
|
369
|
+
self.session.delete(url=f"users/{ctx.get('ID')}"),
|
|
370
|
+
)
|
|
371
|
+
ctx.set_purged()
|
|
File without changes
|