dapla-auth-client 0.0.1__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,21 @@
1
+ MIT License
2
+
3
+ Copyright © 2025 Statistics Norway
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.3
2
+ Name: dapla-auth-client
3
+ Version: 0.0.1
4
+ Summary: Dapla Auth Client
5
+ License: MIT
6
+ Author: Dapla Developers
7
+ Author-email: dapla-platform-developers@ssb.no
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Dist: deprecated (>=1.2.18,<2.0.0)
17
+ Requires-Dist: google-auth (>=2.40.2)
18
+ Requires-Dist: pytest (>=8.4.0,<9.0.0)
19
+ Requires-Dist: requests (>=2.27.1)
20
+ Requires-Dist: responses (>=0.25.7,<0.26.0)
21
+ Project-URL: Changelog, https://github.com/statisticsnorway/dapla-auth-client/releases
22
+ Project-URL: Documentation, https://statisticsnorway.github.io/dapla-auth-client
23
+ Project-URL: Homepage, https://github.com/statisticsnorway/dapla-auth-client
24
+ Project-URL: Repository, https://github.com/statisticsnorway/dapla-auth-client
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Dapla Auth Client
28
+
29
+ [![PyPI](https://img.shields.io/pypi/v/dapla-auth-client.svg)][pypi status]
30
+ [![Status](https://img.shields.io/pypi/status/dapla-auth-client.svg)][pypi status]
31
+ [![Python Version](https://img.shields.io/pypi/pyversions/dapla-auth-client)][pypi status]
32
+ [![License](https://img.shields.io/pypi/l/dapla-auth-client)][license]
33
+
34
+ [![Documentation](https://github.com/statisticsnorway/dapla-auth-client/actions/workflows/docs.yml/badge.svg)][documentation]
35
+ [![Tests](https://github.com/statisticsnorway/dapla-auth-client/actions/workflows/tests.yml/badge.svg)][tests]
36
+ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=statisticsnorway_dapla-auth-client&metric=coverage)][sonarcov]
37
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=statisticsnorway_dapla-auth-client&metric=alert_status)][sonarquality]
38
+
39
+ [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)][pre-commit]
40
+ [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)][black]
41
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
42
+ [![Poetry](https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json)][poetry]
43
+
44
+ [pypi status]: https://pypi.org/project/dapla-auth-client/
45
+ [documentation]: https://statisticsnorway.github.io/dapla-auth-client
46
+ [tests]: https://github.com/statisticsnorway/dapla-auth-client/actions?workflow=Tests
47
+ [sonarcov]: https://sonarcloud.io/summary/overall?id=statisticsnorway_dapla-auth-client
48
+ [sonarquality]: https://sonarcloud.io/summary/overall?id=statisticsnorway_dapla-auth-client
49
+ [pre-commit]: https://github.com/pre-commit/pre-commit
50
+ [black]: https://github.com/psf/black
51
+ [poetry]: https://python-poetry.org/
52
+
53
+ ## Features
54
+
55
+ - Detects Dapla environment, service, and region via environment variables
56
+ - Retrieves current Dapla region (e.g., checks for DAPLA_LAB)
57
+ - Reads Kubernetes service-account token from filesystem
58
+ - Exchanges Kubernetes token for Keycloak token in Dapla Lab
59
+ - Overrides Google-Auth refresh handler to use custom token fetch logic
60
+ - Fetches Google ADC credentials
61
+
62
+ ## Requirements
63
+
64
+ - Python >3.8 (3.10 is preferred)
65
+ - Poetry, install via curl -sSL https://install.python-poetry.org | python3 -
66
+
67
+ ## Installation
68
+
69
+ You can install _Dapla Auth Client_ via [pip] from [PyPI]:
70
+
71
+ ```console
72
+ pip install dapla-auth-client
73
+ ```
74
+
75
+ ## Usage
76
+
77
+ ```python
78
+ # This code snippet demonstrates how to use the Dapla Auth Client to fetch a personal token.
79
+
80
+ from dapla_auth_client import AuthClient
81
+
82
+ print(AuthClient.fetch_personal_token())
83
+ ```
84
+
85
+ ## Contributing
86
+
87
+ Contributions are very welcome.
88
+ To learn more, see the [Contributor Guide].
89
+
90
+ ## License
91
+
92
+ Distributed under the terms of the [MIT license][license],
93
+ _Dapla Auth Client_ is free and open source software.
94
+
95
+ ## Issues
96
+
97
+ If you encounter any problems,
98
+ please [file an issue] along with a detailed description.
99
+
100
+ ## Credits
101
+
102
+ This project was generated from [Statistics Norway]'s [SSB PyPI Template].
103
+
104
+ [statistics norway]: https://www.ssb.no/en
105
+ [pypi]: https://pypi.org/
106
+ [ssb pypi template]: https://github.com/statisticsnorway/ssb-pypitemplate
107
+ [file an issue]: https://github.com/statisticsnorway/dapla-auth-client/issues
108
+ [pip]: https://pip.pypa.io/
109
+
110
+ <!-- github-only -->
111
+
112
+ [license]: https://github.com/statisticsnorway/dapla-auth-client/blob/main/LICENSE
113
+ [contributor guide]: https://github.com/statisticsnorway/dapla-auth-client/blob/main/CONTRIBUTING.md
114
+ [reference guide]: https://statisticsnorway.github.io/dapla-auth-client/reference.html
115
+
@@ -0,0 +1,88 @@
1
+ # Dapla Auth Client
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/dapla-auth-client.svg)][pypi status]
4
+ [![Status](https://img.shields.io/pypi/status/dapla-auth-client.svg)][pypi status]
5
+ [![Python Version](https://img.shields.io/pypi/pyversions/dapla-auth-client)][pypi status]
6
+ [![License](https://img.shields.io/pypi/l/dapla-auth-client)][license]
7
+
8
+ [![Documentation](https://github.com/statisticsnorway/dapla-auth-client/actions/workflows/docs.yml/badge.svg)][documentation]
9
+ [![Tests](https://github.com/statisticsnorway/dapla-auth-client/actions/workflows/tests.yml/badge.svg)][tests]
10
+ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=statisticsnorway_dapla-auth-client&metric=coverage)][sonarcov]
11
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=statisticsnorway_dapla-auth-client&metric=alert_status)][sonarquality]
12
+
13
+ [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)][pre-commit]
14
+ [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)][black]
15
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
16
+ [![Poetry](https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json)][poetry]
17
+
18
+ [pypi status]: https://pypi.org/project/dapla-auth-client/
19
+ [documentation]: https://statisticsnorway.github.io/dapla-auth-client
20
+ [tests]: https://github.com/statisticsnorway/dapla-auth-client/actions?workflow=Tests
21
+ [sonarcov]: https://sonarcloud.io/summary/overall?id=statisticsnorway_dapla-auth-client
22
+ [sonarquality]: https://sonarcloud.io/summary/overall?id=statisticsnorway_dapla-auth-client
23
+ [pre-commit]: https://github.com/pre-commit/pre-commit
24
+ [black]: https://github.com/psf/black
25
+ [poetry]: https://python-poetry.org/
26
+
27
+ ## Features
28
+
29
+ - Detects Dapla environment, service, and region via environment variables
30
+ - Retrieves current Dapla region (e.g., checks for DAPLA_LAB)
31
+ - Reads Kubernetes service-account token from filesystem
32
+ - Exchanges Kubernetes token for Keycloak token in Dapla Lab
33
+ - Overrides Google-Auth refresh handler to use custom token fetch logic
34
+ - Fetches Google ADC credentials
35
+
36
+ ## Requirements
37
+
38
+ - Python >3.8 (3.10 is preferred)
39
+ - Poetry, install via curl -sSL https://install.python-poetry.org | python3 -
40
+
41
+ ## Installation
42
+
43
+ You can install _Dapla Auth Client_ via [pip] from [PyPI]:
44
+
45
+ ```console
46
+ pip install dapla-auth-client
47
+ ```
48
+
49
+ ## Usage
50
+
51
+ ```python
52
+ # This code snippet demonstrates how to use the Dapla Auth Client to fetch a personal token.
53
+
54
+ from dapla_auth_client import AuthClient
55
+
56
+ print(AuthClient.fetch_personal_token())
57
+ ```
58
+
59
+ ## Contributing
60
+
61
+ Contributions are very welcome.
62
+ To learn more, see the [Contributor Guide].
63
+
64
+ ## License
65
+
66
+ Distributed under the terms of the [MIT license][license],
67
+ _Dapla Auth Client_ is free and open source software.
68
+
69
+ ## Issues
70
+
71
+ If you encounter any problems,
72
+ please [file an issue] along with a detailed description.
73
+
74
+ ## Credits
75
+
76
+ This project was generated from [Statistics Norway]'s [SSB PyPI Template].
77
+
78
+ [statistics norway]: https://www.ssb.no/en
79
+ [pypi]: https://pypi.org/
80
+ [ssb pypi template]: https://github.com/statisticsnorway/ssb-pypitemplate
81
+ [file an issue]: https://github.com/statisticsnorway/dapla-auth-client/issues
82
+ [pip]: https://pip.pypa.io/
83
+
84
+ <!-- github-only -->
85
+
86
+ [license]: https://github.com/statisticsnorway/dapla-auth-client/blob/main/LICENSE
87
+ [contributor guide]: https://github.com/statisticsnorway/dapla-auth-client/blob/main/CONTRIBUTING.md
88
+ [reference guide]: https://statisticsnorway.github.io/dapla-auth-client/reference.html
@@ -0,0 +1,132 @@
1
+ [tool.poetry]
2
+ name = "dapla-auth-client"
3
+ version = "0.0.1"
4
+ description = "Dapla Auth Client"
5
+ authors = ["Dapla Developers <dapla-platform-developers@ssb.no>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ homepage = "https://github.com/statisticsnorway/dapla-auth-client"
9
+ repository = "https://github.com/statisticsnorway/dapla-auth-client"
10
+ documentation = "https://statisticsnorway.github.io/dapla-auth-client"
11
+ classifiers = ["Development Status :: 5 - Production/Stable"]
12
+ packages = [{include = "dapla_auth_client", from = "src"}]
13
+
14
+ [tool.poetry.urls]
15
+ Changelog = "https://github.com/statisticsnorway/dapla-auth-client/releases"
16
+
17
+ [tool.poetry.dependencies]
18
+ python = ">=3.10,<4.0"
19
+ requests = ">=2.27.1"
20
+ google-auth = ">=2.40.2"
21
+ pytest = "^8.4.0"
22
+ deprecated = "^1.2.18"
23
+ responses = "^0.25.7"
24
+
25
+ [tool.poetry.group.dev.dependencies]
26
+ pygments = ">=2.10.0"
27
+ black = { extras = ["jupyter"], version = ">=23.1.0" }
28
+ coverage = { extras = ["toml"], version = ">=6.2" }
29
+ darglint = ">=1.8.1"
30
+ furo = ">=2021.11.12"
31
+ mypy = ">=0.930"
32
+ pre-commit = ">=2.16.0"
33
+ pre-commit-hooks = ">=4.1.0"
34
+ ruff = ">=0.0.284"
35
+ pytest = ">=6.2.5"
36
+ sphinx = ">=6.2.1"
37
+ sphinx-autobuild = ">=2021.3.14"
38
+ sphinx-autodoc-typehints = ">=1.24.0"
39
+ sphinx-click = ">=3.0.2"
40
+ typeguard = ">=2.13.3"
41
+ xdoctest = { extras = ["colors"], version = ">=0.15.10" }
42
+ myst-parser = { version = ">=0.16.1" }
43
+
44
+ [tool.pytest.ini_options]
45
+ pythonpath = ["src"]
46
+
47
+ [tool.poetry.scripts]
48
+ dapla-auth-client = "dapla_auth_client.__main__:main"
49
+
50
+ [tool.coverage.paths]
51
+ source = ["src", "*/site-packages"]
52
+ tests = ["tests", "*/tests"]
53
+
54
+ [tool.coverage.run]
55
+ branch = true
56
+ source = ["dapla_auth_client", "tests"]
57
+ relative_files = true
58
+
59
+ [tool.coverage.report]
60
+ show_missing = true
61
+ fail_under = 80
62
+
63
+ [tool.mypy]
64
+ strict = true
65
+ warn_unreachable = true
66
+ pretty = true
67
+ show_column_numbers = true
68
+ show_error_context = true
69
+
70
+ [tool.ruff]
71
+ force-exclude = true # Apply excludes to pre-commit
72
+ show-fixes = true
73
+ src = ["src", "tests"]
74
+ target-version = "py311" # Minimum Python version supported
75
+ include = ["*.py", "*.pyi", "**/pyproject.toml", "*.ipynb"]
76
+ extend-exclude = [
77
+ "__pycache__",
78
+ "old",
79
+ ".ipynb_checkpoints",
80
+ "noxfile.py",
81
+ "docs/conf.py",
82
+ ]
83
+
84
+ # Ruff rules may be customized as desired: https://docs.astral.sh/ruff/rules/
85
+ [tool.ruff.lint]
86
+ select = ["ALL"]
87
+ ignore = [
88
+ "ANN202", # Don't requiere return type annotation for private functions.
89
+ "ANN401", # Allow type annotation with type Any.
90
+ "D100", # Supress undocumented-public-module. Only doc of public api required.
91
+ "FBT001", # Allow boolean positional arguments in a function.
92
+ "FBT002", # Allow boolean default positional arguments in a function.
93
+ "E402", # Supress module-import-not-at-top-of-file, needed in jupyter notebooks.
94
+ "E501", # Supress line-too-long warnings: trust black's judgement on this one.
95
+ "PLR2004", # Allow to compare with unnamed numerical constants.
96
+ ]
97
+
98
+ [tool.ruff.lint.isort]
99
+ force-single-line = true
100
+
101
+ [tool.ruff.lint.mccabe]
102
+ max-complexity = 15
103
+
104
+ [tool.ruff.lint.pydocstyle]
105
+ convention = "google" # You can also use "numpy".
106
+
107
+ [tool.ruff.lint.pylint]
108
+ max-args = 8
109
+
110
+ [tool.ruff.lint.pep8-naming]
111
+ classmethod-decorators = ["classmethod", "validator", "root_validator", "pydantic.validator"]
112
+
113
+ [tool.ruff.lint.per-file-ignores]
114
+ "*/__init__.py" = ["F401"]
115
+ "**/tests/*" = [
116
+ "ANN001", # type annotations don't add value for test functions
117
+ "ANN002", # type annotations don't add value for test functions
118
+ "ANN003", # type annotations don't add value for test functions
119
+ "ANN201", # type annotations don't add value for test functions
120
+ "ANN204", # type annotations don't add value for test functions
121
+ "ANN205", # type annotations don't add value for test functions
122
+ "ANN206", # type annotations don't add value for test functions
123
+ "D100", # docstrings are overkill for test functions
124
+ "D101",
125
+ "D102",
126
+ "D103",
127
+ "S101", # asserts are encouraged in pytest
128
+ ]
129
+
130
+ [build-system]
131
+ requires = ["poetry-core>=1.0.0"]
132
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,7 @@
1
+ """Dapla Auth Client."""
2
+
3
+ # Expose the AuthClient class directly for easy access.
4
+ from .auth import AuthClient
5
+ from .auth import MissingConfigurationException
6
+
7
+ __all__ = ["AuthClient", "MissingConfigurationException"]
@@ -0,0 +1,340 @@
1
+ import json
2
+ import logging
3
+ import os
4
+ from datetime import datetime
5
+ from datetime import timedelta
6
+ from functools import lru_cache
7
+
8
+ import google.auth
9
+ import requests
10
+ from deprecated import deprecated
11
+ from google.auth.transport.requests import Request as GoogleAuthRequest
12
+ from google.oauth2.credentials import Credentials
13
+
14
+ from dapla_auth_client.const import DaplaEnvironment
15
+ from dapla_auth_client.const import DaplaRegion
16
+ from dapla_auth_client.const import DaplaService
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # Refresh window was modified in: https://github.com/googleapis/google-auth-library-python/commit/c6af1d692b43833baca978948376739547cf685a
21
+ # The change was directed towards high latency environments, and should not apply to us.
22
+ # Since we can't force a refresh, the threshold is lowered to keep us from waiting ~4 minutes for a new token.
23
+ # A permanent fix would be to supply credentials with a refresh endpoint
24
+ # that always returns a token that is valid for more than 3m 45s.
25
+ google.auth._helpers.REFRESH_THRESHOLD = timedelta(seconds=20)
26
+
27
+
28
+ class AuthClient:
29
+ """Client for retrieving authentication information."""
30
+
31
+ @staticmethod
32
+ def _get_current_dapla_metadata() -> (
33
+ tuple[DaplaEnvironment | None, DaplaService | None, DaplaRegion | None]
34
+ ):
35
+ try:
36
+ env = DaplaEnvironment(os.getenv("DAPLA_ENVIRONMENT"))
37
+ except ValueError:
38
+ env = None
39
+
40
+ try:
41
+ service = DaplaService(os.getenv("DAPLA_SERVICE"))
42
+ except ValueError:
43
+ service = None
44
+
45
+ try:
46
+ region = DaplaRegion(os.getenv("DAPLA_REGION"))
47
+ except ValueError:
48
+ region = None
49
+
50
+ return env, service, region
51
+
52
+ @staticmethod
53
+ def get_dapla_region() -> DaplaRegion | None:
54
+ """Checks if the current Dapla Region is Dapla Lab."""
55
+ _, _, region = AuthClient._get_current_dapla_metadata()
56
+ return region
57
+
58
+ @staticmethod
59
+ def _refresh_handler( # type: ignore[no-untyped-def]
60
+ *args,
61
+ scopes: list[str] | None,
62
+ **kwargs,
63
+ ) -> tuple[str, datetime]:
64
+ # We manually override the refresh_handler method with our custom logic for fetching tokens.
65
+ # Previously, we directly overrode the `refresh` method. However, this
66
+ # approach led to deadlock issues in gcsfs/credentials.py's maybe_refresh method.
67
+ return AuthClient.fetch_google_token()
68
+
69
+ @staticmethod
70
+ def _read_kubernetes_token() -> str:
71
+ """Fetches the Kubernetes service account token from the default file path.
72
+ This function reads the token from the file located at
73
+ "/var/run/secrets/kubernetes.io/serviceaccount/token". It ensures that
74
+ the token is not empty or invalid and raises appropriate exceptions
75
+ if the file is missing or the token is invalid.
76
+
77
+ Returns:
78
+ str: The Kubernetes service account token.
79
+
80
+ Raises:
81
+ FileNotFoundError: If the token file is not found at the specified path.
82
+ ValueError: If the token file is empty or contains invalid data.
83
+ """
84
+ token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
85
+ try:
86
+ with open(token_path) as token_file:
87
+ token = token_file.read()
88
+ if not token:
89
+ raise ValueError("Token file is empty or invalid.")
90
+ return token
91
+ except FileNotFoundError:
92
+ raise FileNotFoundError(f"Kubernetes token file not found at {token_path}")
93
+
94
+ @staticmethod
95
+ def _exchange_kubernetes_token_for_keycloak_token(
96
+ audience: list[str] | None = None,
97
+ scope: list[str] | None = None,
98
+ ) -> tuple[str, datetime]:
99
+ """Fetches a Keycloak token for the current user in Dapla Lab.
100
+
101
+ This method exchanges the Kubernetes service account token for a Keycloak token
102
+ using the LABID_TOKEN_EXCHANGE_URL environment variable. It requires the
103
+ Dapla Lab region to be set and the LABID_TOKEN_EXCHANGE_URL to be configured.
104
+
105
+ Args:
106
+ audience: Optional list of audiences to include in the token exchange request.
107
+ scope: Optional list of scopes to include in the token exchange request.
108
+
109
+ Raises:
110
+ RuntimeError: If the region is not DAPLA_LAB, or if the HTTP request fails.
111
+ MissingConfigurationException: If LABID_TOKEN_EXCHANGE_URL is not set.
112
+
113
+ Returns:
114
+ A tuple of (keycloak-token, expiry).
115
+ """
116
+ _, _, region = AuthClient._get_current_dapla_metadata()
117
+ if region != DaplaRegion.DAPLA_LAB:
118
+ raise RuntimeError("Dapla Lab region not detected.")
119
+
120
+ labid_url = os.getenv("LABID_TOKEN_EXCHANGE_URL")
121
+ if labid_url is None:
122
+ raise MissingConfigurationException("LABID_TOKEN_EXCHANGE_URL")
123
+
124
+ kubernetes_token = AuthClient._read_kubernetes_token()
125
+ try:
126
+ response = requests.post(
127
+ url=labid_url,
128
+ headers={
129
+ "Content-Type": "application/x-www-form-urlencoded",
130
+ "Authorization": f"Bearer {kubernetes_token}",
131
+ },
132
+ data={
133
+ "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
134
+ "subject_token_type": "urn:ietf:params:oauth:grant-type:id_token",
135
+ "subject_token": kubernetes_token,
136
+ **({"scope": ",".join(scope)} if scope else {}),
137
+ **({"audience": ",".join(audience)} if audience else {}),
138
+ },
139
+ )
140
+ response.raise_for_status()
141
+ auth_data = response.json()
142
+ expiry = datetime.utcnow() + timedelta(seconds=auth_data["expires_in"])
143
+ access_token = auth_data["access_token"]
144
+
145
+ return access_token, expiry
146
+
147
+ except requests.RequestException as e:
148
+ logger.error(f"Failed to fetch Keycloak token: {e}")
149
+ raise RuntimeError("Failed to fetch Keycloak token for Dapla Lab.") from e
150
+
151
+ @staticmethod
152
+ @deprecated(
153
+ reason=(
154
+ "fetch_google_token_from_oidc_exchange() is deprecated and will be removed in a future release. "
155
+ "Use Kubernetes/ADC auto-discovery instead of manually exchanging OIDC tokens."
156
+ ),
157
+ )
158
+ def fetch_google_token_from_oidc_exchange(
159
+ request: GoogleAuthRequest,
160
+ scopes: list[str] | None = None,
161
+ ) -> tuple[str, datetime]:
162
+ """Fetches the Google token by exchanging an OIDC token.
163
+
164
+ Args:
165
+ request: The GoogleAuthRequest object.
166
+ scopes: The scopes to request. This is ignored in this implementation.
167
+
168
+ Raises:
169
+ RuntimeError: If the request to the OIDC token exchange endpoint fails.
170
+
171
+ Returns:
172
+ A tuple of (google-token, expiry).
173
+ """
174
+ if os.getenv("OIDC_TOKEN_EXCHANGE_URL") is None:
175
+ raise RuntimeError(
176
+ "env variable 'OIDC_TOKEN_EXCHANGE_URL' was not found when "
177
+ "attempting token exchange with OIDC endpoint",
178
+ )
179
+
180
+ response = request.__call__(
181
+ url=os.environ["OIDC_TOKEN_EXCHANGE_URL"],
182
+ method="POST",
183
+ body={
184
+ "subject_token": os.environ["OIDC_TOKEN"],
185
+ "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
186
+ "requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
187
+ "requested_issuer": "google",
188
+ "client_id": "onyxia-api",
189
+ },
190
+ ) # type: ignore[no-untyped-call]
191
+
192
+ if response.status == 200:
193
+ auth_data = json.loads(response.data)
194
+ expiry = datetime.utcnow() + timedelta(seconds=auth_data["expires_in"])
195
+ return auth_data["access_token"], expiry
196
+ error = json.loads(response.data)
197
+ print("Error: ", error.get("error_description", "Unknown error"))
198
+ raise RuntimeError("OIDC token exchange failed.")
199
+
200
+ @staticmethod
201
+ @deprecated(
202
+ reason=(
203
+ "fetch_google_token() is deprecated and will be removed in a future release. "
204
+ "Kubernetes/ADC now auto-discovers credentials for you."
205
+ ),
206
+ )
207
+ def fetch_google_token(
208
+ request: GoogleAuthRequest | None = None,
209
+ scopes: list[str] | None = None,
210
+ ) -> tuple[str, datetime]:
211
+ """Fetches the Google token for the current user.
212
+
213
+ Scopes in the argument is ignored, but are kept for compatibility
214
+ with the Credentials refresh handler method signature.
215
+
216
+ Args:
217
+ request: The GoogleAuthRequest object.
218
+ scopes: The scopes to request. This is ignored in this implementation.
219
+
220
+ Raises:
221
+ RuntimeError: If the token exchange fails.
222
+
223
+ Returns:
224
+ A tuple of (google-token, expiry).
225
+ """
226
+ try:
227
+ if request is None:
228
+ request = GoogleAuthRequest() # type: ignore[no-untyped-call]
229
+
230
+ google_token, expiry = AuthClient.fetch_google_token_from_oidc_exchange(
231
+ request,
232
+ )
233
+ except Exception as err:
234
+ raise RuntimeError(str(err))
235
+
236
+ return google_token, expiry
237
+
238
+ @staticmethod
239
+ @deprecated(
240
+ reason=(
241
+ "fetch_google_credentials() is deprecated and will be removed in a future release. "
242
+ "On Kubernetes, Application Default Credentials (ADC) will auto-discover for you."
243
+ ),
244
+ )
245
+ def fetch_google_credentials(force_token_exchange: bool = False) -> Credentials:
246
+ """Fetches the Google credentials for the current user.
247
+
248
+ Args:
249
+ force_token_exchange: Forces authentication by token exchange.
250
+
251
+ Raises:
252
+ RuntimeError: If fails to fetch credentials.
253
+
254
+ Returns:
255
+ The Google "Credentials" object.
256
+ """
257
+ env, service, region = AuthClient._get_current_dapla_metadata()
258
+ force_token_exchange = (
259
+ os.getenv("DAPLA_TOOLBELT_FORCE_TOKEN_EXCHANGE") == "1"
260
+ or force_token_exchange
261
+ )
262
+
263
+ try:
264
+ match (env, service, region):
265
+ case (_, _, _) if force_token_exchange is True:
266
+ logger.debug("Auth - Forced token exchange")
267
+ token, expiry = AuthClient.fetch_google_token()
268
+ credentials = Credentials(
269
+ token=token,
270
+ expiry=expiry,
271
+ token_uri="https://oauth2.googleapis.com/token",
272
+ refresh_handler=AuthClient._refresh_handler,
273
+ ) # type: ignore[no-untyped-call]
274
+
275
+ case (_, DaplaService.CLOUD_RUN, _):
276
+ logger.debug("Auth - Cloud Run detected, using ADC")
277
+ credentials, _ = google.auth.default() # type: ignore[no-untyped-call]
278
+
279
+ case (_, _, DaplaRegion.DAPLA_LAB):
280
+ logger.debug("Auth - Dapla Lab detected, attempting to use ADC")
281
+ credentials, _ = google.auth.default() # type: ignore[no-untyped-call]
282
+
283
+ case (_, _, _):
284
+ logger.debug("Auth - Default authentication used (ADC)")
285
+ credentials, _ = google.auth.default() # type: ignore[no-untyped-call]
286
+
287
+ except Exception as err:
288
+ raise RuntimeError(str(err))
289
+
290
+ return credentials
291
+
292
+ @staticmethod
293
+ def fetch_personal_token() -> str:
294
+ """If Dapla Region is Dapla Lab, retrieve the Keycloak token."""
295
+ _, _, region = AuthClient._get_current_dapla_metadata()
296
+ if region != DaplaRegion.DAPLA_LAB:
297
+ raise RuntimeError("Dapla Lab region not detected.")
298
+
299
+ logger.debug("Auth - Dapla Lab detected, returning Keycloak token")
300
+ keycloak_token, _ = AuthClient._exchange_kubernetes_token_for_keycloak_token()
301
+ return keycloak_token
302
+
303
+ @staticmethod
304
+ @lru_cache(maxsize=1)
305
+ @deprecated(
306
+ reason=(
307
+ "fetch_email_from_credentials() is deprecated and will be removed in a future release. "
308
+ "Kubernetes/Google ADC now auto-discovers credentials. "
309
+ "You can rely on Application Default Credentials (ADC) instead of calling this explicitly."
310
+ ),
311
+ )
312
+ def fetch_email_from_credentials() -> str | None: # type: ignore[unused-ignore]
313
+ """Retrieves an e-mail based on current Google Credentials. Potentially makes a Google API call."""
314
+ if os.getenv("DAPLA_REGION") == DaplaRegion.DAPLA_LAB.value:
315
+ return os.getenv("DAPLA_USER")
316
+
317
+ credentials = AuthClient.fetch_google_credentials()
318
+ response = requests.get(
319
+ url=f"https://oauth2.googleapis.com/tokeninfo?access_token={credentials.token}",
320
+ )
321
+
322
+ return response.json().get("email") if response.status_code == 200 else None
323
+
324
+
325
+ class MissingConfigurationException(Exception):
326
+ """Exception raised when a required environment variable or configuration is missing."""
327
+
328
+ def __init__(self, variable_name: str) -> None:
329
+ """Initializes a new instance of the MissingConfigurationException class.
330
+
331
+ Args:
332
+ variable_name (str): The name of the missing environment variable or configuration.
333
+ """
334
+ self.variable_name = variable_name
335
+ self.message = f"Missing required environment variable: {variable_name}"
336
+ super().__init__(self.message)
337
+
338
+ def __str__(self) -> str:
339
+ """Returns a string representation of the exception."""
340
+ return f"Configuration error: {self.message}"
@@ -0,0 +1,35 @@
1
+ from enum import Enum
2
+
3
+
4
+ class DaplaEnvironment(Enum):
5
+ """Represents the 'DAPLA_ENVIRONMENT' environment variable."""
6
+
7
+ DEV = "DEV"
8
+ STAGING = "STAGING"
9
+ TEST = "TEST"
10
+ PROD = "PROD"
11
+
12
+
13
+ class DaplaService(Enum):
14
+ """Represents the 'DAPLA_SERVICE' environment variable."""
15
+
16
+ JUPYTERLAB = "JUPYTERLAB"
17
+ VS_CODE = "VS_CODE"
18
+ R_STUDIO = "R_STUDIO"
19
+ CLOUD_RUN = "CLOUD_RUN"
20
+
21
+
22
+ class DaplaRegion(Enum):
23
+ """Represents the 'DAPLA_REGION' environment variable."""
24
+
25
+ ON_PREM = "ON_PREM"
26
+ DAPLA_LAB = "DAPLA_LAB"
27
+ CLOUD_RUN = "CLOUD_RUN"
28
+
29
+
30
+ GUARDIAN_URLS = {
31
+ DaplaEnvironment.DEV: "https://guardian.intern.test.ssb.no/maskinporten/access-token",
32
+ DaplaEnvironment.STAGING: "https://guardian.intern.test.ssb.no/maskinporten/access-token",
33
+ DaplaEnvironment.TEST: "https://guardian.intern.test.ssb.no/maskinporten/access-token",
34
+ DaplaEnvironment.PROD: "https://guardian.intern.ssb.no/maskinporten/access-token",
35
+ }
File without changes