seven2one-questra-authorization 1.0.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.
@@ -0,0 +1,59 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual Environment
24
+ .venv/
25
+ venv/
26
+ ENV/
27
+ env/
28
+
29
+ # uv
30
+ .uv/
31
+ uv.lock
32
+
33
+ # IDEs
34
+ .vscode/
35
+ .idea/
36
+ *.swp
37
+ *.swo
38
+ *~
39
+
40
+ # Testing
41
+ .pytest_cache/
42
+ .coverage
43
+ htmlcov/
44
+ .tox/
45
+ .env
46
+ packages/data/tests/integration/test_data/
47
+
48
+ # Linting
49
+ .ruff_cache/
50
+
51
+ # MkDocs
52
+ site/
53
+
54
+ # OS
55
+ .DS_Store
56
+ Thumbs.db
57
+ */__marimo__/
58
+ notebooks/play.py
59
+ notebooks/quickstart-authz.py
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.4
2
+ Name: seven2one-questra-authorization
3
+ Version: 1.0.0
4
+ Summary: Authorization Client for Questra® - Role and Permission Management
5
+ Author-email: Team Techstack <questra_python@seven2one.de>
6
+ License: Proprietary
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: gql[requests]<4.0.0,>=3.5.0
21
+ Requires-Dist: pydantic<3.0.0,>=2.0.0
22
+ Requires-Dist: seven2one-questra-authentication>=2.0.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Questra Authorization
26
+
27
+ Python Authorization Client für die Questra® Plattform – Role und Permission Management.
28
+
29
+ ## Features
30
+
31
+ - **Role Management**: Rollen abfragen und verwalten
32
+ - **Permission Checks**: Berechtigungen prüfen
33
+ - **Type-Safe**: Vollständig typisierte API
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install seven2one-questra-authorization
39
+ ```
40
+
41
+ ## Requirements
42
+
43
+ - Python >= 3.10
44
+ - seven2one-questra-authentication >= 2.0.0
45
+
46
+ ## Schnellstart
47
+
48
+ ```python
49
+ from seven2one.questra.authentication import QuestraAuthentication
50
+ from seven2one.questra.authz import QuestraAuthz
51
+
52
+ auth = QuestraAuthentication(
53
+ url="https://auth.example.com",
54
+ username="ServiceUser",
55
+ password="secret",
56
+ )
57
+ authz = QuestraAuthz(url="https://authz.example.com", authentication=auth)
58
+ ```
59
+
60
+ ## Weitere Informationen
61
+
62
+ - **Vollständige Dokumentation:** <https://pydocs.[questra-host.domain]>
63
+ - **Support:** <support@seven2one.de>
64
+
65
+ ## License
66
+
67
+ Proprietary - Seven2one Informationssysteme GmbH
@@ -0,0 +1,43 @@
1
+ # Questra Authorization
2
+
3
+ Python Authorization Client für die Questra® Plattform – Role und Permission Management.
4
+
5
+ ## Features
6
+
7
+ - **Role Management**: Rollen abfragen und verwalten
8
+ - **Permission Checks**: Berechtigungen prüfen
9
+ - **Type-Safe**: Vollständig typisierte API
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install seven2one-questra-authorization
15
+ ```
16
+
17
+ ## Requirements
18
+
19
+ - Python >= 3.10
20
+ - seven2one-questra-authentication >= 2.0.0
21
+
22
+ ## Schnellstart
23
+
24
+ ```python
25
+ from seven2one.questra.authentication import QuestraAuthentication
26
+ from seven2one.questra.authz import QuestraAuthz
27
+
28
+ auth = QuestraAuthentication(
29
+ url="https://auth.example.com",
30
+ username="ServiceUser",
31
+ password="secret",
32
+ )
33
+ authz = QuestraAuthz(url="https://authz.example.com", authentication=auth)
34
+ ```
35
+
36
+ ## Weitere Informationen
37
+
38
+ - **Vollständige Dokumentation:** <https://pydocs.[questra-host.domain]>
39
+ - **Support:** <support@seven2one.de>
40
+
41
+ ## License
42
+
43
+ Proprietary - Seven2one Informationssysteme GmbH
@@ -0,0 +1,50 @@
1
+ [project]
2
+ name = "seven2one-questra-authorization"
3
+ version = "1.0.0"
4
+ description = "Authorization Client for Questra® - Role and Permission Management"
5
+ authors = [{name = "Team Techstack", email = "questra_python@seven2one.de"}]
6
+ readme = "README.md"
7
+ requires-python = ">=3.10"
8
+ license = {text = "Proprietary"}
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "License :: Other/Proprietary License",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.10",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ "Topic :: Security",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = [
24
+ "gql[requests]>=3.5.0,<4.0.0",
25
+ "pydantic>=2.0.0,<3.0.0",
26
+ "seven2one-questra-authentication>=2.0.0",
27
+ ]
28
+
29
+ [tool.uv]
30
+ package = true
31
+
32
+ [tool.uv.sources]
33
+ seven2one-questra-authentication = { workspace = true }
34
+
35
+ [build-system]
36
+ requires = ["hatchling"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.sdist]
40
+ include = [
41
+ "src/",
42
+ "README.md",
43
+ "pyproject.toml",
44
+ ]
45
+ exclude = [
46
+ "tests/",
47
+ ]
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/seven2one"]
@@ -0,0 +1,89 @@
1
+ """
2
+ Questra Authorization - User, group, and external-rights management for the Questra platform.
3
+
4
+ Example:
5
+ ```python
6
+ from seven2one.questra.authentication import QuestraAuthentication
7
+ from seven2one.questra.authorization import QuestraAuthz
8
+
9
+ auth = QuestraAuthentication(
10
+ url="https://authentik.seven2one.academy.s2o.dev",
11
+ username="ServiceUser",
12
+ password="secret",
13
+ )
14
+ authz = QuestraAuthz(
15
+ graphql_url="https://seven2one.academy.s2o.dev/authz/graphql",
16
+ auth_client=auth,
17
+ )
18
+
19
+ me = authz.get_me()
20
+ groups = authz.list_groups()
21
+ users = authz.list_users()
22
+
23
+ # Direct GraphQL access
24
+ info = authz.raw.queries.get_service_info()
25
+ ```
26
+ """
27
+
28
+ from ._field_path import FieldPath, FieldSelector
29
+ from .exceptions import (
30
+ AuthorizationError,
31
+ PermissionDeniedError,
32
+ PolicyNotFoundError,
33
+ QuestraAuthorizationGraphQLError,
34
+ QuestraAuthzError,
35
+ RoleNotFoundError,
36
+ )
37
+ from .generated.models import (
38
+ AggregatedExternalRight,
39
+ AggregatedExternalRights,
40
+ ExternalRight,
41
+ ExternalRights,
42
+ ExternalRightsPayload,
43
+ Group,
44
+ GroupPayload,
45
+ GroupsPayload,
46
+ GroupsWithExternalRightsPayload,
47
+ GroupWithExternalRightsPayload,
48
+ IdentityProviderUser,
49
+ ServiceInfo,
50
+ User,
51
+ UserIdWithGroupIdsInformation,
52
+ UserPayload,
53
+ UsersPayload,
54
+ UsersToGroupsPayload,
55
+ )
56
+ from .questra_authorization import QuestraAuthorization
57
+
58
+ __all__ = [
59
+ # Main client
60
+ "QuestraAuthorization",
61
+ # Field selection
62
+ "FieldPath",
63
+ "FieldSelector",
64
+ # Exceptions
65
+ "QuestraAuthzError",
66
+ "QuestraAuthorizationGraphQLError",
67
+ "AuthorizationError",
68
+ "PermissionDeniedError",
69
+ "RoleNotFoundError",
70
+ "PolicyNotFoundError",
71
+ # Models
72
+ "User",
73
+ "UserPayload",
74
+ "UserIdWithGroupIdsInformation",
75
+ "UsersPayload",
76
+ "UsersToGroupsPayload",
77
+ "Group",
78
+ "GroupPayload",
79
+ "GroupsPayload",
80
+ "GroupWithExternalRightsPayload",
81
+ "GroupsWithExternalRightsPayload",
82
+ "ExternalRight",
83
+ "ExternalRights",
84
+ "ExternalRightsPayload",
85
+ "AggregatedExternalRight",
86
+ "AggregatedExternalRights",
87
+ "IdentityProviderUser",
88
+ "ServiceInfo",
89
+ ]
@@ -0,0 +1,184 @@
1
+ """FieldPath and field-selection utilities for the Authorization GraphQL client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from typing import Any, Union
7
+
8
+ # Type alias for field selector — either a FieldPath or a plain wire-name string.
9
+ FieldSelector = Union["FieldPath", str]
10
+
11
+
12
+ def _snake_to_camel(name: str) -> str:
13
+ """Convert snake_case to camelCase.
14
+
15
+ Passes already-camelCase strings through unchanged (no underscores → no-op).
16
+
17
+ Examples::
18
+
19
+ >>> _snake_to_camel("workspace_name")
20
+ 'workspaceName'
21
+ >>> _snake_to_camel("isActive")
22
+ 'isActive'
23
+ """
24
+ parts = name.split("_")
25
+ return parts[0] + "".join(p.capitalize() for p in parts[1:])
26
+
27
+
28
+ class FieldPath:
29
+ """A GraphQL field path, optionally with navigable children.
30
+
31
+ Created by the :attr:`~seven2one.questra.authorization.QuestraAuthorization.schema`
32
+ accessor. Supports chained attribute access to build nested wire paths.
33
+
34
+ ``str(field_path)`` returns the camelCase wire name for use in GraphQL queries
35
+ and filter dicts. ``__hash__`` and ``__eq__`` are defined so that FieldPath
36
+ instances can be used directly as keys in ``where`` dicts.
37
+
38
+ Example::
39
+
40
+ u = authz.schema.users
41
+ fields = [u.id, u.username, u.groups.id, u.groups.name]
42
+ authz.list_users(fields=fields)
43
+
44
+ # FieldPath as where key
45
+ authz.list_users(where={u.is_active: {"eq": True}})
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ wire_name: str,
51
+ _children: dict[str, FieldPath] | None = None,
52
+ ) -> None:
53
+ object.__setattr__(self, "_wire_name", wire_name)
54
+ object.__setattr__(self, "_children", _children or {})
55
+
56
+ def __str__(self) -> str:
57
+ return object.__getattribute__(self, "_wire_name") # type: ignore[no-any-return]
58
+
59
+ def __repr__(self) -> str:
60
+ return f"FieldPath({object.__getattribute__(self, '_wire_name')!r})"
61
+
62
+ def __hash__(self) -> int:
63
+ return hash(object.__getattribute__(self, "_wire_name"))
64
+
65
+ def __eq__(self, other: object) -> bool:
66
+ if isinstance(other, FieldPath):
67
+ return object.__getattribute__(
68
+ self, "_wire_name"
69
+ ) == object.__getattribute__(other, "_wire_name")
70
+ return NotImplemented
71
+
72
+ def __getattr__(self, name: str) -> FieldPath:
73
+ if name.startswith("_"):
74
+ raise AttributeError(name)
75
+ children: dict[str, FieldPath] = object.__getattribute__(self, "_children")
76
+ wire_name: str = object.__getattribute__(self, "_wire_name")
77
+ if name in children:
78
+ child = children[name]
79
+ child_wire: str = object.__getattribute__(child, "_wire_name")
80
+ child_children: dict[str, FieldPath] = object.__getattribute__(
81
+ child, "_children"
82
+ )
83
+ return FieldPath(f"{wire_name}.{child_wire}", child_children)
84
+ # Graceful passthrough: snake_case → camelCase wire name.
85
+ # Allows navigating unknown fields without import.
86
+ return FieldPath(f"{wire_name}.{_snake_to_camel(name)}")
87
+
88
+ def __dir__(self) -> list[str]:
89
+ children: dict[str, FieldPath] = object.__getattribute__(self, "_children")
90
+ return list(children.keys())
91
+
92
+ def _to_wire_paths(self) -> list[str]:
93
+ """Return all leaf wire paths rooted at this field.
94
+
95
+ A scalar field returns ``["wire_name"]``. A navigation field with children
96
+ expands recursively into dotted leaf paths so that
97
+ ``FieldPath("rights", {"right": ..., "id": ...})._to_wire_paths()``
98
+ returns ``["rights.right", "rights.id"]``.
99
+ """
100
+ wire: str = object.__getattribute__(self, "_wire_name")
101
+ children: dict[str, FieldPath] = object.__getattribute__(self, "_children")
102
+ if not children:
103
+ return [wire]
104
+ result: list[str] = []
105
+ for child_fp in children.values():
106
+ for sub in child_fp._to_wire_paths():
107
+ result.append(f"{wire}.{sub}")
108
+ return result
109
+
110
+
111
+ def _fields_to_graphql(fields: list[FieldSelector]) -> str:
112
+ """Convert a list of :class:`FieldPath` / ``str`` selectors to a GraphQL field string.
113
+
114
+ Groups dotted wire names into nested ``{ }`` blocks recursively.
115
+ Navigation ``FieldPath`` objects (those with children) are automatically
116
+ expanded into their full subfield selection.
117
+
118
+ Example::
119
+
120
+ _fields_to_graphql(["id", "groups.id", "groups.name"])
121
+ # → "id groups { id name }"
122
+
123
+ er = authz.schema.external_rights
124
+ _fields_to_graphql([er.scope, er.rights])
125
+ # → "scope rights { right id }"
126
+ """
127
+ wire_paths: list[str] = []
128
+ for f in fields:
129
+ if isinstance(f, FieldPath):
130
+ wire_paths.extend(f._to_wire_paths())
131
+ else:
132
+ wire_paths.append(_snake_to_camel(f))
133
+ return _build_selection(wire_paths)
134
+
135
+
136
+ def _build_selection(names: list[str]) -> str:
137
+ top_level: list[str] = []
138
+ grouped: dict[str, list[str]] = defaultdict(list)
139
+
140
+ for name in names:
141
+ if "." in name:
142
+ prefix, rest = name.split(".", 1)
143
+ grouped[prefix].append(rest)
144
+ elif name not in top_level:
145
+ top_level.append(name)
146
+
147
+ parts: list[str] = list(top_level)
148
+ for prefix, children in grouped.items():
149
+ sub = _build_selection(children)
150
+ parts.append(f"{prefix} {{ {sub} }}")
151
+
152
+ return " ".join(parts)
153
+
154
+
155
+ def _normalize_where(
156
+ where: dict[Any, Any] | None,
157
+ ) -> dict[str, object] | None:
158
+ """Normalise a where-filter dict.
159
+
160
+ - :class:`FieldPath` keys → ``str(key)`` (camelCase wire name).
161
+ - ``str`` keys → ``_snake_to_camel(key)`` (converts snake_case; passes camelCase through).
162
+ - Nested dicts and ``and``/``or`` lists are recursed into.
163
+
164
+ Args:
165
+ where: Raw filter dict or ``None``.
166
+
167
+ Returns:
168
+ Normalised dict with string camelCase keys, or ``None``.
169
+ """
170
+ if where is None:
171
+ return None
172
+ result: dict[str, object] = {}
173
+ for key, value in where.items():
174
+ str_key = _snake_to_camel(str(key))
175
+ if isinstance(value, list):
176
+ result[str_key] = [
177
+ _normalize_where(item) if isinstance(item, dict) else item
178
+ for item in value
179
+ ]
180
+ elif isinstance(value, dict):
181
+ result[str_key] = _normalize_where(value)
182
+ else:
183
+ result[str_key] = value
184
+ return result
@@ -0,0 +1,69 @@
1
+ """Custom exceptions for seven2one-questra-authorization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class QuestraAuthzError(Exception):
9
+ """Base exception for all questra-authorization errors."""
10
+
11
+ def __init__(self, message: str) -> None:
12
+ self.message = message
13
+ super().__init__(self.message)
14
+
15
+
16
+ class QuestraAuthorizationGraphQLError(QuestraAuthzError):
17
+ """Exception for GraphQL errors returned by the Authorization service."""
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ code: str | None = None,
23
+ extensions: dict[str, Any] | None = None,
24
+ locations: list[Any] | None = None,
25
+ path: list[Any] | None = None,
26
+ ) -> None:
27
+ super().__init__(message)
28
+ self.code = code
29
+ self.extensions = extensions or {}
30
+ self.locations = locations or []
31
+ self.path = path or []
32
+
33
+ def __str__(self) -> str:
34
+ parts = [f"GraphQL Error: {self.message}"]
35
+ if self.code:
36
+ parts.append(f"Code: {self.code}")
37
+ if self.path:
38
+ parts.append(f"Path: {' -> '.join(map(str, self.path))}")
39
+ return " | ".join(parts)
40
+
41
+ def __repr__(self) -> str:
42
+ return (
43
+ f"QuestraAuthorizationGraphQLError(message={self.message!r}, "
44
+ f"code={self.code!r}, path={self.path!r})"
45
+ )
46
+
47
+
48
+ class AuthorizationError(QuestraAuthzError):
49
+ """Raised when an authorization check fails."""
50
+
51
+ pass
52
+
53
+
54
+ class PermissionDeniedError(AuthorizationError):
55
+ """Raised when the principal lacks the required permission."""
56
+
57
+ pass
58
+
59
+
60
+ class RoleNotFoundError(QuestraAuthzError):
61
+ """Raised when a requested role does not exist."""
62
+
63
+ pass
64
+
65
+
66
+ class PolicyNotFoundError(QuestraAuthzError):
67
+ """Raised when a requested policy does not exist."""
68
+
69
+ pass
@@ -0,0 +1,2 @@
1
+ # Generated from schema/authorization.sdl
2
+ # DO NOT EDIT MANUALLY