pixel-client 1.2.7__tar.gz → 1.3.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.
@@ -141,4 +141,13 @@ cython_debug/
141
141
  .env.*
142
142
 
143
143
  **/examples/**
144
- tmp/
144
+ tmp/
145
+
146
+ # Claude Code
147
+ .claude/
148
+
149
+ # Node
150
+ node_modules/
151
+
152
+ # OS
153
+ .DS_Store
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: pixel-client
3
- Version: 1.2.7
3
+ Version: 1.3.0
4
4
  Summary: Client library for Geodata Pixel
5
5
  Project-URL: Documentation, https://doc.geodatapixel.no/
6
6
  Project-URL: Organization, https://geodata.no
@@ -35,7 +35,8 @@ This client library provides a convenient interface for working with Geodata Pix
35
35
  - **Raster Data Handling**: Support for various raster data types (RGB, DTM, DSM)
36
36
  - **ArcGIS Services**: Create and manage ArcGIS Feature and Image services
37
37
  - **Harvest Services**: Automated data harvesting from ArcGIS Feature services
38
- - **Authentication**: Integrated Keycloak authentication
38
+ - **Authentication**: Integrated Keycloak authentication, or long lived api keys
39
+ - **Access Management**: Manage users, groups, project access, api keys, and geo service users for ArcGIS services
39
40
  - **Metadata Management**: Flexible metadata handling for uploaded files
40
41
  - **Attachments**: Add and manage file attachments to resources
41
42
 
@@ -54,7 +55,7 @@ pip install pixel-client
54
55
 
55
56
  ## Authentication
56
57
 
57
- The Pixel client requires authentication through Keycloak. You can provide authentication details through environment variables, a `.env` file, or directly in code:
58
+ The Pixel client authenticates either with Keycloak user credentials or with a Pixel api key. Provide exactly one of the two, through environment variables, a `.env` file, or directly in code:
58
59
 
59
60
  ```python
60
61
  from pixel_client import get_client, PixelApiSettings
@@ -62,7 +63,7 @@ from pixel_client import get_client, PixelApiSettings
62
63
  # Using environment variables
63
64
  client = get_client()
64
65
 
65
- # Using direct settings
66
+ # Using Keycloak credentials
66
67
  settings = PixelApiSettings(
67
68
  PIXEL_TENANT="your_realm",
68
69
  PIXEL_USERNAME="your_username",
@@ -70,11 +71,28 @@ settings = PixelApiSettings(
70
71
  )
71
72
  client = get_client(settings=settings)
72
73
 
74
+ # Using an api key, for unattended access (CI jobs, scheduled scripts)
75
+ settings = PixelApiSettings(
76
+ PIXEL_TENANT="your_realm",
77
+ PIXEL_API_KEY="pixel_v1_..."
78
+ )
79
+ client = get_client(settings=settings)
80
+
73
81
  # Using a .env file
74
82
  settings = PixelApiSettings.from_env_file("my_env_file.env")
75
83
  client = get_client(settings=settings)
76
84
  ```
77
85
 
86
+ Create api keys with `create_api_key`. The token is returned exactly once, at
87
+ creation, and is never retrievable again. An api key acts on behalf of the user
88
+ who created it, with the project roles, groups or organisation-wide role it was
89
+ given, and never more than that user's own current access.
90
+
91
+ Some management calls need a signed-in user and do not work with an api key:
92
+ creating, listing, renaming, revoking and replacing api keys, creating and
93
+ editing users, creating and changing geo service users, `me`, and the access
94
+ views (`list_grants`, `get_user_access`, `get_group_access`).
95
+
78
96
  ## Quick Start
79
97
 
80
98
  ### Synchronous Usage
@@ -14,7 +14,8 @@ This client library provides a convenient interface for working with Geodata Pix
14
14
  - **Raster Data Handling**: Support for various raster data types (RGB, DTM, DSM)
15
15
  - **ArcGIS Services**: Create and manage ArcGIS Feature and Image services
16
16
  - **Harvest Services**: Automated data harvesting from ArcGIS Feature services
17
- - **Authentication**: Integrated Keycloak authentication
17
+ - **Authentication**: Integrated Keycloak authentication, or long lived api keys
18
+ - **Access Management**: Manage users, groups, project access, api keys, and geo service users for ArcGIS services
18
19
  - **Metadata Management**: Flexible metadata handling for uploaded files
19
20
  - **Attachments**: Add and manage file attachments to resources
20
21
 
@@ -33,7 +34,7 @@ pip install pixel-client
33
34
 
34
35
  ## Authentication
35
36
 
36
- The Pixel client requires authentication through Keycloak. You can provide authentication details through environment variables, a `.env` file, or directly in code:
37
+ The Pixel client authenticates either with Keycloak user credentials or with a Pixel api key. Provide exactly one of the two, through environment variables, a `.env` file, or directly in code:
37
38
 
38
39
  ```python
39
40
  from pixel_client import get_client, PixelApiSettings
@@ -41,7 +42,7 @@ from pixel_client import get_client, PixelApiSettings
41
42
  # Using environment variables
42
43
  client = get_client()
43
44
 
44
- # Using direct settings
45
+ # Using Keycloak credentials
45
46
  settings = PixelApiSettings(
46
47
  PIXEL_TENANT="your_realm",
47
48
  PIXEL_USERNAME="your_username",
@@ -49,11 +50,28 @@ settings = PixelApiSettings(
49
50
  )
50
51
  client = get_client(settings=settings)
51
52
 
53
+ # Using an api key, for unattended access (CI jobs, scheduled scripts)
54
+ settings = PixelApiSettings(
55
+ PIXEL_TENANT="your_realm",
56
+ PIXEL_API_KEY="pixel_v1_..."
57
+ )
58
+ client = get_client(settings=settings)
59
+
52
60
  # Using a .env file
53
61
  settings = PixelApiSettings.from_env_file("my_env_file.env")
54
62
  client = get_client(settings=settings)
55
63
  ```
56
64
 
65
+ Create api keys with `create_api_key`. The token is returned exactly once, at
66
+ creation, and is never retrievable again. An api key acts on behalf of the user
67
+ who created it, with the project roles, groups or organisation-wide role it was
68
+ given, and never more than that user's own current access.
69
+
70
+ Some management calls need a signed-in user and do not work with an api key:
71
+ creating, listing, renaming, revoking and replacing api keys, creating and
72
+ editing users, creating and changing geo service users, `me`, and the access
73
+ views (`list_grants`, `get_user_access`, `get_group_access`).
74
+
57
75
  ## Quick Start
58
76
 
59
77
  ### Synchronous Usage
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pixel-client"
3
- version = "1.2.7"
3
+ version = "1.3.0"
4
4
  description = "Client library for Geodata Pixel"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -58,7 +58,8 @@ docs = [
58
58
  include = [
59
59
  "src/*"
60
60
  ]
61
-
61
+ [tool.uv]
62
+ exclude-newer = "10 days"
62
63
 
63
64
  [tool.basedpyright]
64
65
  include = ["src"]
@@ -0,0 +1,282 @@
1
+ """Resource handlers behind `grant_access_on` and `revoke_access_on`.
2
+
3
+ Each handler knows which principals and roles one kind of resource accepts,
4
+ and how to grant and revoke them through the API. Supporting a new kind of
5
+ resource means adding a `Resource` subclass in `models.py`, a handler here,
6
+ and an entry in `HANDLERS`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import TYPE_CHECKING, Awaitable, ClassVar, get_args
13
+
14
+ import httpx
15
+
16
+ from .exceptions import PixelBadRequestError
17
+ from .models import ArcgisServiceResource, ProjectResource, Resource
18
+ from .types import PrincipalKind, RoleType
19
+
20
+ if TYPE_CHECKING:
21
+ from ._base import PixelClientAsync
22
+
23
+ PRINCIPAL_ARGS: dict[PrincipalKind, str] = {
24
+ "user": "users",
25
+ "group": "groups",
26
+ "geo_service_user": "geo_service_users",
27
+ }
28
+ """Maps each principal kind to the keyword argument that takes it."""
29
+
30
+ Principals = dict[PrincipalKind, list[int]]
31
+
32
+ REQUEST_ERRORS = (PixelBadRequestError, httpx.HTTPError)
33
+
34
+
35
+ def change(
36
+ resource: Resource,
37
+ principal_kind: PrincipalKind,
38
+ principal_id: int,
39
+ role: str | None,
40
+ action: str,
41
+ ) -> dict:
42
+ """One access change, as reported back to the caller."""
43
+ return {
44
+ "resource": resource.as_dict(),
45
+ "principal_kind": principal_kind,
46
+ "principal_id": principal_id,
47
+ "role": role,
48
+ "action": action,
49
+ }
50
+
51
+
52
+ @dataclass
53
+ class Outcome:
54
+ """Collects the changes that were applied and the ones that failed."""
55
+
56
+ succeeded: list[dict] = field(default_factory=list)
57
+ failed: list[tuple[dict, Exception]] = field(default_factory=list)
58
+
59
+ async def apply(self, changes: list[dict], request: Awaitable) -> None:
60
+ """Await one request that applies `changes`, recording the result."""
61
+ try:
62
+ await request
63
+ except REQUEST_ERRORS as e:
64
+ self.failed.extend((c, e) for c in changes)
65
+ else:
66
+ self.succeeded.extend(changes)
67
+
68
+
69
+ class AccessHandler:
70
+ """Grants and revokes access on one kind of resource."""
71
+
72
+ principal_kinds: ClassVar[tuple[PrincipalKind, ...]]
73
+ roles: ClassVar[tuple[str, ...]]
74
+ fixed_role: ClassVar[str | None] = None
75
+ """Set when the resource has exactly one role, so callers may omit it."""
76
+
77
+ def check(self, resource: Resource, principals: Principals) -> None:
78
+ """Raise ValueError if `principals` contains a kind this resource does not accept."""
79
+ for kind, ids in principals.items():
80
+ if ids and kind not in self.principal_kinds:
81
+ accepted = ", ".join(PRINCIPAL_ARGS[k] for k in self.principal_kinds)
82
+ raise ValueError(
83
+ f"{type(resource).__name__} access can be given to {accepted}, "
84
+ f"not {PRINCIPAL_ARGS[kind]}."
85
+ )
86
+
87
+ def check_role(self, resource: Resource, role: str | None) -> str:
88
+ """Return the role to grant, or raise ValueError if it is not valid here."""
89
+ if self.fixed_role is not None and role in (None, self.fixed_role):
90
+ return self.fixed_role
91
+ if role not in self.roles:
92
+ raise ValueError(
93
+ f"The role for {type(resource).__name__} must be one of "
94
+ f"{', '.join(self.roles)}, got {role!r}."
95
+ )
96
+ return role
97
+
98
+ async def grant(
99
+ self,
100
+ client: PixelClientAsync,
101
+ resource: Resource,
102
+ role: str,
103
+ principals: Principals,
104
+ outcome: Outcome,
105
+ ) -> None:
106
+ raise NotImplementedError
107
+
108
+ async def revoke(
109
+ self,
110
+ client: PixelClientAsync,
111
+ resource: Resource,
112
+ principals: Principals,
113
+ outcome: Outcome,
114
+ ) -> None:
115
+ raise NotImplementedError
116
+
117
+
118
+ class ProjectAccess(AccessHandler):
119
+ """Project grants for users and groups.
120
+
121
+ A user's first grant on a project and a change to it are different routes
122
+ (`add_users` vs `users/{id}/role`), so current direct grants are read
123
+ first. Group grants go through a route that creates or updates.
124
+ """
125
+
126
+ principal_kinds = ("user", "group")
127
+ roles = get_args(RoleType)
128
+
129
+ async def _current(
130
+ self, client: PixelClientAsync, project_id: int, principals: Principals
131
+ ) -> dict[PrincipalKind, dict[int, str]]:
132
+ current: dict[PrincipalKind, dict[int, str]] = {"user": {}, "group": {}}
133
+ if principals.get("user"):
134
+ users = await client.list_project_users(project_id)
135
+ current["user"] = {u["id"]: u["role"] for u in users}
136
+ if principals.get("group"):
137
+ groups = await client.list_project_groups(project_id)
138
+ current["group"] = {g["id"]: g["role"] for g in groups}
139
+ return current
140
+
141
+ async def grant(self, client, resource, role, principals, outcome):
142
+ assert isinstance(resource, ProjectResource)
143
+ project_id = resource.id
144
+ try:
145
+ current = await self._current(client, project_id, principals)
146
+ except REQUEST_ERRORS as e:
147
+ outcome.failed.extend(
148
+ (change(resource, kind, pid, role, "granted"), e)
149
+ for kind, ids in principals.items()
150
+ for pid in ids
151
+ )
152
+ return
153
+
154
+ new_users = []
155
+ for user_id in principals.get("user", []):
156
+ held = current["user"].get(user_id)
157
+ if held is None:
158
+ new_users.append(user_id)
159
+ elif held == role:
160
+ outcome.succeeded.append(change(resource, "user", user_id, role, "unchanged"))
161
+ else:
162
+ await outcome.apply(
163
+ [change(resource, "user", user_id, role, "updated")],
164
+ client._put(
165
+ f"/projects/{project_id}/users/{user_id}/role",
166
+ params={"role": role},
167
+ ),
168
+ )
169
+ if new_users:
170
+ await outcome.apply(
171
+ [change(resource, "user", u, role, "granted") for u in new_users],
172
+ client._post(
173
+ f"/projects/{project_id}/add_users",
174
+ json={"users": [{"user_id": u, "role": role} for u in new_users]},
175
+ ),
176
+ )
177
+
178
+ for group_id in principals.get("group", []):
179
+ held = current["group"].get(group_id)
180
+ if held == role:
181
+ outcome.succeeded.append(change(resource, "group", group_id, role, "unchanged"))
182
+ continue
183
+ await outcome.apply(
184
+ [change(resource, "group", group_id, role, "granted" if held is None else "updated")],
185
+ client._put(
186
+ f"/projects/{project_id}/groups/{group_id}/role",
187
+ params={"role": role},
188
+ ),
189
+ )
190
+
191
+ async def revoke(self, client, resource, principals, outcome):
192
+ assert isinstance(resource, ProjectResource)
193
+ project_id = resource.id
194
+ try:
195
+ current = await self._current(client, project_id, principals)
196
+ except REQUEST_ERRORS as e:
197
+ outcome.failed.extend(
198
+ (change(resource, kind, pid, None, "revoked"), e)
199
+ for kind, ids in principals.items()
200
+ for pid in ids
201
+ )
202
+ return
203
+
204
+ routes = {
205
+ "user": f"/projects/{project_id}/users/{{}}/remove",
206
+ "group": f"/projects/{project_id}/groups/{{}}",
207
+ }
208
+ for kind in self.principal_kinds:
209
+ for principal_id in principals.get(kind, []):
210
+ if principal_id not in current[kind]:
211
+ outcome.succeeded.append(change(resource, kind, principal_id, None, "unchanged"))
212
+ continue
213
+ await outcome.apply(
214
+ [change(resource, kind, principal_id, None, "revoked")],
215
+ client._delete(routes[kind].format(principal_id)),
216
+ )
217
+
218
+
219
+ class ArcgisServiceAccess(AccessHandler):
220
+ """ArcGIS service access for geo service users. There is a single role."""
221
+
222
+ principal_kinds = ("geo_service_user",)
223
+ roles = ("geo_service_access",)
224
+ fixed_role = "geo_service_access"
225
+
226
+ def _route(self, resource: ArcgisServiceResource) -> str:
227
+ return f"/arcgis_services/{resource.service_type}/{resource.id}/access"
228
+
229
+ async def _current(self, client, resource, action, principals, outcome) -> set[int] | None:
230
+ try:
231
+ granted = await client.list_arcgis_service_access(resource.service_type, resource.id)
232
+ except REQUEST_ERRORS as e:
233
+ outcome.failed.extend(
234
+ (change(resource, "geo_service_user", pid, self.fixed_role if action == "granted" else None, action), e)
235
+ for pid in principals.get("geo_service_user", [])
236
+ )
237
+ return None
238
+ return {u["id"] for u in granted}
239
+
240
+ async def grant(self, client, resource, role, principals, outcome):
241
+ assert isinstance(resource, ArcgisServiceResource)
242
+ current = await self._current(client, resource, "granted", principals, outcome)
243
+ if current is None:
244
+ return
245
+ for user_id in principals.get("geo_service_user", []):
246
+ if user_id in current:
247
+ outcome.succeeded.append(change(resource, "geo_service_user", user_id, role, "unchanged"))
248
+ continue
249
+ await outcome.apply(
250
+ [change(resource, "geo_service_user", user_id, role, "granted")],
251
+ client._put(f"{self._route(resource)}/{user_id}"),
252
+ )
253
+
254
+ async def revoke(self, client, resource, principals, outcome):
255
+ assert isinstance(resource, ArcgisServiceResource)
256
+ current = await self._current(client, resource, "revoked", principals, outcome)
257
+ if current is None:
258
+ return
259
+ for user_id in principals.get("geo_service_user", []):
260
+ if user_id not in current:
261
+ outcome.succeeded.append(change(resource, "geo_service_user", user_id, None, "unchanged"))
262
+ continue
263
+ await outcome.apply(
264
+ [change(resource, "geo_service_user", user_id, None, "revoked")],
265
+ client._delete(f"{self._route(resource)}/{user_id}"),
266
+ )
267
+
268
+
269
+ HANDLERS: dict[type[Resource], AccessHandler] = {
270
+ ProjectResource: ProjectAccess(),
271
+ ArcgisServiceResource: ArcgisServiceAccess(),
272
+ }
273
+
274
+
275
+ def handler_for(resource: Resource) -> AccessHandler:
276
+ try:
277
+ return HANDLERS[type(resource)]
278
+ except KeyError:
279
+ raise ValueError(
280
+ f"Access cannot be managed on {resource!r}. Supported resources: "
281
+ f"{', '.join(cls.__name__ for cls in HANDLERS)}."
282
+ ) from None