cmem-client 0.5.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.
Files changed (52) hide show
  1. cmem_client-0.5.0/LICENSE +201 -0
  2. cmem_client-0.5.0/PKG-INFO +64 -0
  3. cmem_client-0.5.0/README.md +39 -0
  4. cmem_client-0.5.0/cmem_client/__init__.py +13 -0
  5. cmem_client-0.5.0/cmem_client/auth_provider/__init__.py +14 -0
  6. cmem_client-0.5.0/cmem_client/auth_provider/abc.py +124 -0
  7. cmem_client-0.5.0/cmem_client/auth_provider/client_credentials.py +207 -0
  8. cmem_client-0.5.0/cmem_client/auth_provider/password.py +252 -0
  9. cmem_client-0.5.0/cmem_client/auth_provider/prefetched_token.py +153 -0
  10. cmem_client-0.5.0/cmem_client/client.py +485 -0
  11. cmem_client-0.5.0/cmem_client/components/__init__.py +10 -0
  12. cmem_client-0.5.0/cmem_client/components/graph_store.py +316 -0
  13. cmem_client-0.5.0/cmem_client/components/marketplace.py +179 -0
  14. cmem_client-0.5.0/cmem_client/components/sparql_wrapper.py +53 -0
  15. cmem_client-0.5.0/cmem_client/components/workspace.py +194 -0
  16. cmem_client-0.5.0/cmem_client/config.py +364 -0
  17. cmem_client-0.5.0/cmem_client/exceptions.py +82 -0
  18. cmem_client-0.5.0/cmem_client/logging_utils.py +49 -0
  19. cmem_client-0.5.0/cmem_client/models/__init__.py +16 -0
  20. cmem_client-0.5.0/cmem_client/models/access_condition.py +147 -0
  21. cmem_client-0.5.0/cmem_client/models/base.py +30 -0
  22. cmem_client-0.5.0/cmem_client/models/dataset.py +32 -0
  23. cmem_client-0.5.0/cmem_client/models/error.py +67 -0
  24. cmem_client-0.5.0/cmem_client/models/graph.py +26 -0
  25. cmem_client-0.5.0/cmem_client/models/item.py +143 -0
  26. cmem_client-0.5.0/cmem_client/models/logging_config.py +51 -0
  27. cmem_client-0.5.0/cmem_client/models/package.py +35 -0
  28. cmem_client-0.5.0/cmem_client/models/project.py +46 -0
  29. cmem_client-0.5.0/cmem_client/models/python_package.py +26 -0
  30. cmem_client-0.5.0/cmem_client/models/token.py +40 -0
  31. cmem_client-0.5.0/cmem_client/models/url.py +34 -0
  32. cmem_client-0.5.0/cmem_client/models/workflow.py +80 -0
  33. cmem_client-0.5.0/cmem_client/repositories/__init__.py +15 -0
  34. cmem_client-0.5.0/cmem_client/repositories/access_conditions.py +62 -0
  35. cmem_client-0.5.0/cmem_client/repositories/base/__init__.py +12 -0
  36. cmem_client-0.5.0/cmem_client/repositories/base/abc.py +138 -0
  37. cmem_client-0.5.0/cmem_client/repositories/base/paged_list.py +63 -0
  38. cmem_client-0.5.0/cmem_client/repositories/base/plain_list.py +39 -0
  39. cmem_client-0.5.0/cmem_client/repositories/base/task_search.py +70 -0
  40. cmem_client-0.5.0/cmem_client/repositories/datasets.py +36 -0
  41. cmem_client-0.5.0/cmem_client/repositories/graph_imports.py +93 -0
  42. cmem_client-0.5.0/cmem_client/repositories/graphs.py +458 -0
  43. cmem_client-0.5.0/cmem_client/repositories/marketplace_packages.py +486 -0
  44. cmem_client-0.5.0/cmem_client/repositories/projects.py +214 -0
  45. cmem_client-0.5.0/cmem_client/repositories/protocols/__init__.py +15 -0
  46. cmem_client-0.5.0/cmem_client/repositories/protocols/create_item.py +125 -0
  47. cmem_client-0.5.0/cmem_client/repositories/protocols/delete_item.py +95 -0
  48. cmem_client-0.5.0/cmem_client/repositories/protocols/export_item.py +114 -0
  49. cmem_client-0.5.0/cmem_client/repositories/protocols/import_item.py +141 -0
  50. cmem_client-0.5.0/cmem_client/repositories/python_packages.py +58 -0
  51. cmem_client-0.5.0/cmem_client/repositories/workflows.py +143 -0
  52. cmem_client-0.5.0/pyproject.toml +108 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 CMEM
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: cmem-client
3
+ Version: 0.5.0
4
+ Summary: Next generation eccenca Corporate Memory client library.
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: eccenca Corporate Memory,client
8
+ Author: eccenca GmbH
9
+ Author-email: cmempy-developer@eccenca.com
10
+ Requires-Python: >=3.13,<4
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Dist: eccenca-marketplace-client (>=0.5.0,<0.6.0)
18
+ Requires-Dist: httpx (>=0.27.0,<0.28.0)
19
+ Requires-Dist: pydantic (>=2.8.2,<3.0.0)
20
+ Requires-Dist: pyjwt (>=2.8.0,<3.0.0)
21
+ Requires-Dist: rdflib (>=7.2.1,<8.0.0)
22
+ Requires-Dist: xdg-base-dirs (>=6.0.2,<7.0.0)
23
+ Description-Content-Type: text/markdown
24
+
25
+ <!-- markdownlint-disable MD012 MD013 MD024 MD033 -->
26
+ # cmem-client
27
+
28
+ Next generation eccenca Corporate Memory client library.
29
+
30
+
31
+ [![poetry][poetry-shield]][poetry-link] [![ruff][ruff-shield]][ruff-link] [![mypy][mypy-shield]][mypy-link] [![copier][copier-shield]][copier]
32
+
33
+ ## Development
34
+
35
+ - Run [task](https://taskfile.dev/) to see all major development tasks.
36
+ - Use [pre-commit](https://pre-commit.com/) to avoid errors before commit.
37
+ - This repository was created with [this copier template](https://github.com/eccenca/cmem-plugin-template).
38
+
39
+ ## Goals
40
+
41
+ Compared to [cmem-cmempy](https://pypi.org/project/cmem-cmempy/), this package was started to have the following advantages:
42
+
43
+ - Better logging:
44
+ - ?
45
+ - Validation of incoming data:
46
+ - This is done using [pydantic](https://github.com/pydantic/pydantic).
47
+ - See the `models` subdirectory for details.
48
+ - Availability of data objects and proper typing:
49
+ - In addition to pydantic models, we use [mypy](https://www.mypy-lang.org/) to complain about untyped code.
50
+ - Async capabilities:
51
+ - Switching from requests to [httpx](https://www.python-httpx.org/) allows for using asynchronous calls as well as HTTP/2 sessions, if needed.
52
+ - Documentation:
53
+ - [MkDocs](https://www.mkdocs.org/) together with [mkdocstrings](https://mkdocstrings.github.io/) build the foundation for nice developer documentation.
54
+
55
+ [poetry-link]: https://python-poetry.org/
56
+ [poetry-shield]: https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json
57
+ [ruff-link]: https://docs.astral.sh/ruff/
58
+ [ruff-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&label=Code%20Style
59
+ [mypy-link]: https://mypy-lang.org/
60
+ [mypy-shield]: https://www.mypy-lang.org/static/mypy_badge.svg
61
+ [copier]: https://copier.readthedocs.io/
62
+ [copier-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border-purple.json
63
+
64
+
@@ -0,0 +1,39 @@
1
+ <!-- markdownlint-disable MD012 MD013 MD024 MD033 -->
2
+ # cmem-client
3
+
4
+ Next generation eccenca Corporate Memory client library.
5
+
6
+
7
+ [![poetry][poetry-shield]][poetry-link] [![ruff][ruff-shield]][ruff-link] [![mypy][mypy-shield]][mypy-link] [![copier][copier-shield]][copier]
8
+
9
+ ## Development
10
+
11
+ - Run [task](https://taskfile.dev/) to see all major development tasks.
12
+ - Use [pre-commit](https://pre-commit.com/) to avoid errors before commit.
13
+ - This repository was created with [this copier template](https://github.com/eccenca/cmem-plugin-template).
14
+
15
+ ## Goals
16
+
17
+ Compared to [cmem-cmempy](https://pypi.org/project/cmem-cmempy/), this package was started to have the following advantages:
18
+
19
+ - Better logging:
20
+ - ?
21
+ - Validation of incoming data:
22
+ - This is done using [pydantic](https://github.com/pydantic/pydantic).
23
+ - See the `models` subdirectory for details.
24
+ - Availability of data objects and proper typing:
25
+ - In addition to pydantic models, we use [mypy](https://www.mypy-lang.org/) to complain about untyped code.
26
+ - Async capabilities:
27
+ - Switching from requests to [httpx](https://www.python-httpx.org/) allows for using asynchronous calls as well as HTTP/2 sessions, if needed.
28
+ - Documentation:
29
+ - [MkDocs](https://www.mkdocs.org/) together with [mkdocstrings](https://mkdocstrings.github.io/) build the foundation for nice developer documentation.
30
+
31
+ [poetry-link]: https://python-poetry.org/
32
+ [poetry-shield]: https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json
33
+ [ruff-link]: https://docs.astral.sh/ruff/
34
+ [ruff-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&label=Code%20Style
35
+ [mypy-link]: https://mypy-lang.org/
36
+ [mypy-shield]: https://www.mypy-lang.org/static/mypy_badge.svg
37
+ [copier]: https://copier.readthedocs.io/
38
+ [copier-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border-purple.json
39
+
@@ -0,0 +1,13 @@
1
+ """Next generation eccenca Corporate Memory client library.
2
+
3
+ This package provides a modern Python API client for eccenca Corporate Memory,
4
+ featuring:
5
+ - Pydantic-based data validation and serialization
6
+ - Async HTTP operations with httpx
7
+ - Comprehensive type hints with mypy support
8
+ - Flexible authentication providers
9
+ - Repository pattern for organized data access
10
+
11
+ The main entry point is the Client class, which can be configured manually
12
+ or automatically from environment variables.
13
+ """
@@ -0,0 +1,14 @@
1
+ """Authentication providers for Corporate Memory client.
2
+
3
+ This package contains various authentication provider implementations for connecting
4
+ to eccenca Corporate Memory instances. It supports multiple OAuth 2.0 flows and
5
+ authentication methods to accommodate different deployment scenarios.
6
+
7
+ Supported authentication methods:
8
+ - Client Credentials Flow: For machine-to-machine authentication
9
+ - Resource Owner Password Flow: For trusted applications with user credentials
10
+ - Prefetched Token: For scenarios where tokens are obtained externally
11
+
12
+ The AuthProvider abstract base class provides a common interface, and specific
13
+ implementations handle the details of each authentication method.
14
+ """
@@ -0,0 +1,124 @@
1
+ """Abstract base class and factory for authentication providers.
2
+
3
+ This module defines the AuthProvider abstract base class that establishes the
4
+ interface all authentication providers must implement. It also provides a
5
+ factory method that automatically selects the appropriate authentication
6
+ provider based on environment variables.
7
+
8
+ The factory method supports automatic configuration from environment variables,
9
+ making it easy to switch between different authentication methods without
10
+ code changes by simply setting the OAUTH_GRANT_TYPE environment variable.
11
+ """
12
+
13
+ import logging
14
+ from abc import ABC, abstractmethod
15
+ from os import getenv
16
+
17
+ from cmem_client.config import Config
18
+ from cmem_client.exceptions import ClientEnvConfigError
19
+
20
+
21
+ class AuthProvider(ABC):
22
+ """Abstract base class for authentication providers.
23
+
24
+ AuthProvider defines the common interface that all authentication providers
25
+ must implement to work with the Corporate Memory client. It provides the
26
+ contract for obtaining access tokens and includes a factory method for
27
+ creating appropriate provider instances based on environment configuration.
28
+
29
+ All concrete authentication provider implementations must inherit from this
30
+ class and implement the get_access_token method. The class also provides
31
+ automatic provider selection through environment variables.
32
+ """
33
+
34
+ logger: logging.Logger
35
+ """The logger for the auth provider."""
36
+
37
+ @abstractmethod
38
+ def get_access_token(self) -> str:
39
+ """Get the access token for Bearer Authorization header.
40
+
41
+ This method must be implemented by all concrete authentication providers
42
+ to return a valid access token that can be used in HTTP Authorization
43
+ headers for API requests.
44
+
45
+ Returns:
46
+ A valid access token string.
47
+
48
+ Note:
49
+ Implementations should handle token refresh logic internally when
50
+ tokens expire, ensuring this method always returns a valid token.
51
+ """
52
+
53
+ @classmethod
54
+ def from_env(cls, config: Config) -> "AuthProvider":
55
+ """Create an authentication provider from environment variables.
56
+
57
+ This factory method automatically selects and configures the appropriate
58
+ authentication provider based on the OAUTH_GRANT_TYPE environment variable.
59
+ It supports multiple OAuth 2.0 flows and authentication methods.
60
+
61
+ Args:
62
+ config: Configuration object containing Corporate Memory connection
63
+ details and endpoint URLs.
64
+
65
+ Returns:
66
+ A configured AuthProvider instance appropriate for the environment
67
+ configuration.
68
+
69
+ Raises:
70
+ ClientEnvConfigError: If the OAUTH_GRANT_TYPE is not supported or
71
+ if required environment variables for the selected provider
72
+ are missing.
73
+
74
+ Environment Variables:
75
+ OAUTH_GRANT_TYPE (optional): The OAuth flow type. Defaults to
76
+ "client_credentials". Supported values:
77
+ - "client_credentials": Client Credentials Flow for M2M auth
78
+ - "password": Resource Owner Password Flow for trusted apps
79
+ - "prefetched_token": Use externally obtained access token
80
+ """
81
+ oauth_grant_type = getenv("OAUTH_GRANT_TYPE", "client_credentials")
82
+
83
+ if oauth_grant_type == "prefetched_token":
84
+ from cmem_client.auth_provider.prefetched_token import PrefetchedToken # noqa: PLC0415
85
+
86
+ return PrefetchedToken.from_env(config=config)
87
+
88
+ if oauth_grant_type == "client_credentials":
89
+ from cmem_client.auth_provider.client_credentials import ClientCredentialsFlow # noqa: PLC0415
90
+
91
+ return ClientCredentialsFlow.from_env(config=config)
92
+
93
+ if oauth_grant_type == "password":
94
+ from cmem_client.auth_provider.password import PasswordFlow # noqa: PLC0415
95
+
96
+ return PasswordFlow.from_env(config=config)
97
+
98
+ raise ClientEnvConfigError(f"No auth_provider configurable for the current environment ({oauth_grant_type})")
99
+
100
+ @classmethod
101
+ def from_cmempy(cls, config: Config) -> "AuthProvider":
102
+ """Create an authentication provider from a cmempy environment."""
103
+ try:
104
+ import cmem.cmempy.config as cmempy_config # noqa: PLC0415
105
+ except ImportError as error:
106
+ raise OSError("cmempy is not installed.") from error
107
+ oauth_grant_type = cmempy_config.get_oauth_grant_type()
108
+
109
+ if oauth_grant_type == "prefetched_token":
110
+ from cmem_client.auth_provider.prefetched_token import PrefetchedToken # noqa: PLC0415
111
+
112
+ return PrefetchedToken.from_cmempy(config=config)
113
+
114
+ if oauth_grant_type == "client_credentials":
115
+ from cmem_client.auth_provider.client_credentials import ClientCredentialsFlow # noqa: PLC0415
116
+
117
+ return ClientCredentialsFlow.from_cmempy(config=config)
118
+
119
+ if oauth_grant_type == "password":
120
+ from cmem_client.auth_provider.password import PasswordFlow # noqa: PLC0415
121
+
122
+ return PasswordFlow.from_cmempy(config=config)
123
+
124
+ raise ClientEnvConfigError(f"No auth_provider configurable for the current environment ({oauth_grant_type})")
@@ -0,0 +1,207 @@
1
+ """Client Credentials OAuth 2.0 flow authentication provider.
2
+
3
+ This module implements the Client Credentials Flow authentication method for
4
+ accessing eccenca Corporate Memory via OAuth 2.0. This flow is designed for
5
+ machine-to-machine authentication where no user interaction is required.
6
+
7
+ The Client Credentials Flow exchanges client ID and client secret for an access
8
+ token directly with the authorization server. It's ideal for backend services,
9
+ APIs, and automated systems that need to authenticate without user involvement.
10
+
11
+ This implementation handles token caching and automatic renewal when tokens expire.
12
+ """
13
+
14
+ import logging
15
+ from os import getenv
16
+
17
+ import httpx
18
+
19
+ from cmem_client.auth_provider.abc import AuthProvider
20
+ from cmem_client.config import Config
21
+ from cmem_client.exceptions import ClientEnvConfigError
22
+ from cmem_client.models.token import KeycloakToken
23
+
24
+
25
+ class ClientCredentialsFlow(AuthProvider):
26
+ """Client Credentials OAuth 2.0 flow authentication provider.
27
+
28
+ Implements the Client Credentials Flow (RFC 6749, section 4.4) for machine-to-machine
29
+ authentication with Corporate Memory via Keycloak. This flow exchanges client credentials
30
+ (client ID and secret) directly for access tokens without user interaction.
31
+
32
+ The provider handles automatic token caching and refresh, ensuring that get_access_token()
33
+ always returns a valid, non-expired token. It's designed for backend services, CLIs,
34
+ daemons, and other automated systems that need to authenticate as an application
35
+ rather than on behalf of a user.
36
+
37
+ Attributes:
38
+ client_id: The OAuth 2.0 client identifier for the application.
39
+ client_secret: The confidential client secret for authentication.
40
+ config: Corporate Memory configuration containing endpoint URLs.
41
+ httpx: HTTP client for making token requests to the OAuth server.
42
+ token: Currently cached Keycloak token with expiration tracking.
43
+
44
+ See Also:
45
+ https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-credentials-flow
46
+ https://tools.ietf.org/html/rfc6749#section-4.4
47
+ """
48
+
49
+ client_id: str
50
+ """OAuth 2.0 client identifier used to identify the application to the authorization server."""
51
+
52
+ client_secret: str
53
+ """Confidential client secret used to authenticate the application with the OAuth server."""
54
+
55
+ config: Config
56
+ """Corporate Memory configuration containing OAuth token endpoint and other URLs."""
57
+
58
+ httpx: httpx.Client
59
+ """HTTP client instance used for making requests to the OAuth token endpoint."""
60
+
61
+ token: KeycloakToken
62
+ """Currently cached access token with automatic expiration tracking and JWT parsing."""
63
+
64
+ logger: logging.Logger
65
+ """Logger object for logging."""
66
+
67
+ def __init__(self, config: Config, client_id: str, client_secret: str) -> None:
68
+ """Initialize a new Client Credentials Flow authentication provider.
69
+
70
+ Creates a new provider instance and immediately fetches an initial access
71
+ token. The provider will handle token refresh automatically when needed.
72
+
73
+ Args:
74
+ config: Corporate Memory configuration containing OAuth endpoint URLs
75
+ and other connection details.
76
+ client_id: The OAuth 2.0 client identifier registered with the
77
+ authorization server.
78
+ client_secret: The confidential client secret associated with the
79
+ client_id for authentication.
80
+
81
+ Raises:
82
+ HTTPError: If the initial token request fails due to network issues
83
+ or invalid credentials.
84
+ ValidationError: If the token response cannot be parsed as a valid
85
+ Keycloak token.
86
+
87
+ Note:
88
+ The constructor makes an immediate HTTP request to fetch the initial
89
+ token, so ensure network connectivity and valid credentials before
90
+ instantiation.
91
+ """
92
+ self.config = config
93
+ self.client_id = client_id
94
+ self.client_secret = client_secret
95
+ self.httpx = httpx.Client()
96
+ self.logger = logging.getLogger(__name__)
97
+ self.token = self.fetch_new_token()
98
+
99
+ @classmethod
100
+ def from_env(cls, config: Config) -> "ClientCredentialsFlow":
101
+ """Create a Client Credentials Flow provider from environment variables.
102
+
103
+ This factory method creates a provider instance by reading OAuth client
104
+ credentials from environment variables. It's the recommended way to
105
+ create providers in production environments where credentials are
106
+ managed externally.
107
+
108
+ Args:
109
+ config: Corporate Memory configuration containing OAuth endpoint URLs.
110
+
111
+ Returns:
112
+ A configured ClientCredentialsFlow instance ready for use.
113
+
114
+ Raises:
115
+ ClientEnvConfigError: If the required OAUTH_CLIENT_SECRET environment
116
+ variable is not set.
117
+
118
+ Environment Variables:
119
+ OAUTH_CLIENT_ID (optional): The OAuth 2.0 client identifier.
120
+ Defaults to "cmem-service-account" if not specified.
121
+ OAUTH_CLIENT_SECRET (required): The confidential client secret
122
+ for authentication. Must be provided.
123
+
124
+ Security Note:
125
+ Client secrets should be stored securely and never committed to
126
+ version control. Use environment variables or secure secret
127
+ management systems in production.
128
+ """
129
+ oauth_client_id = getenv("OAUTH_CLIENT_ID", "cmem-service-account")
130
+ oauth_client_secret = getenv("OAUTH_CLIENT_SECRET")
131
+ if not oauth_client_secret:
132
+ raise ClientEnvConfigError("Need OAUTH_CLIENT_SECRET environment variable.")
133
+ return cls(client_secret=oauth_client_secret, client_id=oauth_client_id, config=config)
134
+
135
+ @classmethod
136
+ def from_cmempy(cls, config: Config) -> "ClientCredentialsFlow":
137
+ """Create a Client Credentials Flow provider from a cmempy environment."""
138
+ try:
139
+ import cmem.cmempy.config as cmempy_config # noqa: PLC0415
140
+ except ImportError as error:
141
+ raise OSError("cmempy is not installed.") from error
142
+ oauth_client_id = cmempy_config.get_oauth_client_id()
143
+ oauth_client_secret = cmempy_config.get_oauth_client_secret()
144
+ if not oauth_client_secret:
145
+ raise ClientEnvConfigError("Need OAUTH_CLIENT_SECRET environment variable.")
146
+ return cls(client_secret=oauth_client_secret, client_id=oauth_client_id, config=config)
147
+
148
+ def get_access_token(self) -> str:
149
+ """Get a valid access token for Bearer Authorization header.
150
+
151
+ Returns a valid access token, automatically handling token refresh when
152
+ the current token is expired or near expiration. This method implements
153
+ intelligent caching to minimize unnecessary token requests while ensuring
154
+ the returned token is always valid.
155
+
156
+ Returns:
157
+ A valid access token string ready for use in HTTP Authorization headers.
158
+
159
+ Raises:
160
+ HTTPError: If token refresh fails due to network issues or invalid
161
+ credentials.
162
+ ValidationError: If the token response cannot be parsed.
163
+ """
164
+ if self.token.is_expired():
165
+ self.logger.debug("Access token expired, refreshing...")
166
+ self.token = self.fetch_new_token()
167
+ return self.token.access_token
168
+
169
+ def fetch_new_token(self) -> KeycloakToken:
170
+ """Fetch a new access token from the OAuth 2.0 token endpoint.
171
+
172
+ Makes an HTTP POST request to the Keycloak token endpoint using the
173
+ Client Credentials Flow parameters. The response is parsed and returned
174
+ as a KeycloakToken object with automatic expiration tracking.
175
+
176
+ Returns:
177
+ A new KeycloakToken instance with the fresh access token and
178
+ expiration information.
179
+
180
+ Raises:
181
+ HTTPError: If the token request fails due to network issues,
182
+ invalid credentials, or server errors.
183
+ ValidationError: If the token response cannot be parsed as a
184
+ valid Keycloak token format.
185
+
186
+ Note:
187
+ This method performs a synchronous HTTP request and should not be
188
+ called directly in most cases. Use get_access_token() instead,
189
+ which handles caching and only calls this method when necessary.
190
+
191
+ Implementation Details:
192
+ - Uses the standard OAuth 2.0 Client Credentials Flow parameters
193
+ - Sends credentials in the request body (not in Authorization header)
194
+ - Automatically decodes the JSON response and validates the format
195
+ - Extracts JWT claims for expiration tracking
196
+ """
197
+ self.logger.debug("Fetching new access token from OAuth 2.0 token endpoint.")
198
+ post_data = {
199
+ "grant_type": "client_credentials",
200
+ "client_id": self.client_id,
201
+ "client_secret": self.client_secret,
202
+ }
203
+ response = self.httpx.post(url=self.config.url_oauth_token, data=post_data)
204
+ response.raise_for_status()
205
+ content = response.content.decode("utf-8")
206
+ self.logger.debug("Successfully fetched new access token from OAuth 2.0 token endpoint.")
207
+ return KeycloakToken.model_validate_json(json_data=content)