apheris-auth 0.16.0__py3-none-any.whl

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,18 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .core.auth import login, logout, set_login_token
4
+
5
+ try:
6
+ __version__ = version("apheris-auth")
7
+ except PackageNotFoundError:
8
+ __version__ = "UNDEFINED"
9
+
10
+
11
+ def version():
12
+ """
13
+ Current version of Apheris Auth.
14
+ """
15
+ return __version__
16
+
17
+
18
+ __all__ = ["login", "set_login_token", "logout", "version"]
apheris_auth/config.py ADDED
@@ -0,0 +1,204 @@
1
+ import os
2
+ import sys
3
+ from enum import IntFlag
4
+ from operator import xor
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Iterator, List, Literal, Optional, Union
7
+
8
+ from pydantic.v1 import AnyHttpUrl, BaseSettings, root_validator
9
+
10
+
11
+ def get_env_file() -> Union[str, os.PathLike]:
12
+ """Supports multiple environment configurations based on the
13
+ APH_ENV environment variable.
14
+
15
+ The default environment will be always local.
16
+ """
17
+ # Make sure we don't load a spurious .env file by mistake
18
+ env_name = os.getenv("APH_ENV", "local")
19
+ env_file_prefix = ".env"
20
+ env_file_path = f"{env_file_prefix}-{env_name.lower()}"
21
+ if not os.path.exists(env_file_path):
22
+ return Path(__file__).parent.parent.parent / env_file_path
23
+ return env_file_path
24
+
25
+
26
+ def is_interactive():
27
+ """
28
+ Return whether we are in an interactive environment (e.g. Jupyter notebook) or whether
29
+ we are running a script. The method might not return the correct answer in every case.
30
+ """
31
+ # https://stackoverflow.com/questions/2356399/tell-if-python-is-in-interactive-mode
32
+ return hasattr(sys, "ps1")
33
+
34
+
35
+ class LoginType(IntFlag):
36
+ """
37
+ We support multiple login types and methods, This enum is
38
+ to make some order when each login type is being used.
39
+ """
40
+
41
+ LEGACY = 0
42
+ RESOURCE_OWNER = 2 << 1
43
+ CLIENT_CREDENTIALS = 2 << 2
44
+ AUTHORIZATION_CODE_PKCE = 2 << 3
45
+
46
+ @classmethod
47
+ def __get_validators__(cls) -> Iterator[Callable[..., Any]]:
48
+ yield cls.validate
49
+
50
+ @classmethod
51
+ def validate(cls, v: Union[str, "LoginType"]) -> "LoginType":
52
+ valid_types = [name for name in dir(LoginType) if not name.startswith("_")]
53
+ value_error = ValueError(
54
+ f"'{v}' Must be an one of `{cls.__name__}` types: " f"{valid_types}"
55
+ )
56
+
57
+ if isinstance(v, str):
58
+ try:
59
+ return LoginType[v]
60
+ except KeyError as ke:
61
+ raise value_error from ke
62
+ if not isinstance(v, cls):
63
+ raise value_error
64
+ return v
65
+
66
+ @classmethod
67
+ def is_resource_owner_login_type(cls, login_flag: IntFlag) -> bool:
68
+ """
69
+ Checks if the current flag assemble a resource owner login type,
70
+ Resource owner is the username/password login.
71
+ Args:
72
+ login_flag (IntFlag): The current flag to check.
73
+
74
+ Returns:
75
+ bool: true if login_flag is resource owner, false otherwise.
76
+ """
77
+ return bool(login_flag & LoginType.RESOURCE_OWNER)
78
+
79
+
80
+ class Settings(BaseSettings):
81
+ LOGIN_TYPE: LoginType = LoginType.AUTHORIZATION_CODE_PKCE
82
+ CLIENT_APP_ID: str = "lFhmB6ru98fH4ivVqeuaV4BKSIpnzm8O3lXJjTP4"
83
+ DEBUG: bool = False
84
+ VERBOSE: bool = is_interactive()
85
+ ENABLE_REFRESH_TOKEN: bool = True
86
+ CLOUD: str = None
87
+ RAISE_PERMISSION_EXCEPTIONS: bool = True
88
+ CREDENTIALS_FILE: Path = Path.home() / ".config/apheris/credentials.json"
89
+ NODE_CREDENTIALS_FILE: Path = Path.home() / ".config/apheris/credentials-node.json"
90
+ # Urls
91
+ API_BASE_URL: AnyHttpUrl = "https://api.app.apheris.net"
92
+ API_SESSION_MAX_RETRIES: int = 8
93
+ CODE_AUDIT_API_BASE_URL: AnyHttpUrl = "https://code-audit.app.apheris.net"
94
+ API_ORCHESTRATOR_BASE_URL: AnyHttpUrl = "https://orchestrator.app.apheris.net"
95
+ API_JOBS_SUBDOMAIN: Optional[str]
96
+ API_AUTHENTICATION_URL: Optional[AnyHttpUrl]
97
+ API_REVOKE_TOKEN_URL: Optional[AnyHttpUrl]
98
+ API_MFA_AUTHENTICATION_URL: Optional[AnyHttpUrl]
99
+ API_DATASETS_URL: Optional[AnyHttpUrl]
100
+ API_ASSET_POLICIES_URL: Optional[AnyHttpUrl]
101
+ API_FLOWS_URL: Optional[AnyHttpUrl]
102
+ API_USER_INFO_URL: Optional[AnyHttpUrl]
103
+ API_DAL_URL: Optional[AnyHttpUrl]
104
+
105
+ # SSO
106
+ AUTH0_SSO_ENABLED: bool = False
107
+ AUTH0_BASE_URL: AnyHttpUrl = "https://auth.app.apheris.net"
108
+ AUTH0_AUTHORIZE_ENDPOINT: Optional[AnyHttpUrl]
109
+ AUTH0_TOKEN_ENDPOINT: Optional[AnyHttpUrl]
110
+ AUTH0_REVOKE_REFRESH_TOKEN_ENDPOINT: Optional[AnyHttpUrl]
111
+ AUTH0_AUDIENCE: str = "https://api.app.apheris.net"
112
+ AUTH0_NODE_AUDIENCE: str = "urn:node:apheris:app"
113
+ AUTH0_ALWAYS_REFRESH_NODE_TOKEN: bool = True
114
+ # Auth0 APP specifics
115
+ AUTH0_CLIENT_ID: str = "rcA0bCnWhkzg0SuCDporxRUKUDPBhRt3"
116
+ AUTH0_SCOPES: str = "openid email profile offline_access"
117
+ AUTH0_CALLBACK_URL: str = "https://web.app.apheris.net/authorization-code"
118
+ AUTH0_LOOPBACK_CALLBACK_URL_PATH: str = "authorization-code"
119
+ AUTH0_LOOPBACK_CALLBACK_URL_PORTS: List[int] = [8083, 8085, 8087]
120
+
121
+ # Login
122
+ LOGIN_DISABLE_GATEWAY_TOKEN: bool = True
123
+ LOGIN_ORGANIZATION_ID: str = None
124
+ LOGIN_FALLBACK_FLOW: bool = Path(
125
+ "/.dockerenv"
126
+ ).exists() # TODO: this should be `not path.exists()` but it breaks local flow
127
+
128
+ # Serializer, allowed values drived by apheris_statistics.serializers._get_dumpers
129
+ # keys
130
+ DATA_SERIALIZER_NAME: Literal["secure-v1", "pickle-v5"] = "secure-v1"
131
+
132
+ # Service user
133
+ SERVICE_USER_CLIENT_ID: Optional[str]
134
+ SERVICE_USER_CLIENT_SECRET: Optional[str]
135
+
136
+ STREAMING_CHUNK_SIZE: int = 8 * 1024 # 8K
137
+
138
+ # Pre=False is necessary here, with Pre=True the default values are not assigned yet.
139
+ @root_validator(pre=False)
140
+ def set_dependent_variables(cls, values):
141
+ """Set configurations that are dynamic created based on other ones."""
142
+ try:
143
+ api_base_url = values["API_BASE_URL"]
144
+ except KeyError:
145
+ raise RuntimeError(
146
+ f"APH_API_BASE_URL environment variable is not a valid url."
147
+ f"The current value is {os.environ['APH_API_BASE_URL']}, please fix it."
148
+ )
149
+
150
+ # Set dependant URL vars
151
+ dependent_envs = (
152
+ ("API_AUTHENTICATION_URL", "/j/token/"),
153
+ ("API_MFA_AUTHENTICATION_URL", "/j/token/code/"),
154
+ ("API_DATASETS_URL", "/datastore/datasets/"),
155
+ ("API_ASSET_POLICIES_URL", "/datastore/asset_policy/"),
156
+ ("API_FLOWS_URL", "/flows/"),
157
+ ("API_USER_INFO_URL", "/accounts/user_info/"),
158
+ ("API_REVOKE_TOKEN_URL", "/j/token/revoke/"),
159
+ )
160
+ for env_name, api_path in dependent_envs:
161
+ values[env_name] = values.get(env_name) or f"{api_base_url}{api_path}"
162
+
163
+ try:
164
+ auth0_base_url = values["AUTH0_BASE_URL"]
165
+ except KeyError:
166
+ raise RuntimeError(
167
+ f"AUTH0_BASE_URL environment variable is not a valid url."
168
+ f"The current value is {os.environ['AUTH0_BASE_URL']}, please fix it."
169
+ )
170
+
171
+ auth0_dependent_envs = (
172
+ ("AUTH0_AUTHORIZE_ENDPOINT", "/authorize"),
173
+ ("AUTH0_TOKEN_ENDPOINT", "/oauth/token"),
174
+ ("AUTH0_REVOKE_REFRESH_TOKEN_ENDPOINT", "/oauth/revoke"),
175
+ )
176
+ for auth0_env_name, auth0_path in auth0_dependent_envs:
177
+ values[auth0_env_name] = (
178
+ values.get(auth0_env_name) or f"{auth0_base_url}{auth0_path}"
179
+ )
180
+
181
+ if xor(
182
+ bool(values["SERVICE_USER_CLIENT_ID"]),
183
+ bool(values["SERVICE_USER_CLIENT_SECRET"]),
184
+ ):
185
+ raise ValueError(
186
+ "Please set both SERVICE_USER_CLIENT_ID and SERVICE_USER_CLIENT_SECRET "
187
+ "to enable login via service account. Or unset both to disable it."
188
+ )
189
+
190
+ return values
191
+
192
+ def m2m_enabled(self) -> bool:
193
+ """Return the service account configuration status."""
194
+ return bool(self.SERVICE_USER_CLIENT_ID and self.SERVICE_USER_CLIENT_SECRET)
195
+
196
+ # TODO: remove this mapping once we
197
+ # change the variable names in the deployed environments.
198
+ class Config:
199
+ env_prefix = "APH_"
200
+ env_file_encoding = "utf-8"
201
+
202
+
203
+ # The .env file is loaded into the environment variables before settings are built
204
+ settings = Settings(_env_file=get_env_file())
File without changes
@@ -0,0 +1,188 @@
1
+ import functools
2
+ import json
3
+ from typing import Dict, List
4
+
5
+ import jwt
6
+ import requests
7
+
8
+ from ..config import settings
9
+ from . import auth, exceptions
10
+
11
+
12
+ def create_token_debug_msg(access_token: str) -> str:
13
+ claims = jwt.decode(access_token, options={"verify_signature": False})
14
+ payload = json.dumps(claims, indent=2)
15
+ return f"\nAccess token details used in the unauthorized API call:\n{payload}"
16
+
17
+
18
+ def handle_api_exception(func):
19
+ """
20
+ Decorator to treat exceptions raised by API calls.
21
+ If we know what happened, we add a reason to the response object.
22
+ """
23
+
24
+ def _add_reason(response):
25
+ """
26
+ Add the reason for failure to the `response` if available.
27
+ """
28
+ # Only add reason if it was our API
29
+ if response.url.startswith(settings.API_BASE_URL):
30
+ try:
31
+ res = response.json()
32
+ except (json.JSONDecodeError, requests.exceptions.JSONDecodeError):
33
+ details = response.text
34
+ else:
35
+ details = res.get("detail", res)
36
+
37
+ if details:
38
+ response.reason = details
39
+
40
+ @functools.wraps(func)
41
+ def wrapper(*args, **kwargs):
42
+ try:
43
+ return func(*args, **kwargs)
44
+
45
+ except requests.exceptions.ConnectionError:
46
+ msg = (
47
+ "Failed to connect to the Apheris Platform.\n"
48
+ "Please check your network connection."
49
+ )
50
+ raise exceptions.ConnectionError(msg) from None
51
+
52
+ except requests.exceptions.HTTPError as exc:
53
+ # Map to our own exceptions
54
+ if exc.response.status_code == 500:
55
+ ex = exceptions.ServerError
56
+ elif exc.response.status_code == 403:
57
+ ex = exceptions.AccessDenied
58
+ elif exc.response.status_code == 404:
59
+ ex = exceptions.ObjectNotFound
60
+ try:
61
+ detail = exc.response.json().get("detail")
62
+ # caller might set a proper reason before raising an error
63
+ # otherwise it would still be default http.client.responses[404] value
64
+ if detail and exc.response.reason == "Not Found":
65
+ exc.response.reason = detail
66
+ except requests.exceptions.InvalidJSONError:
67
+ pass
68
+ elif exc.response.status_code == 401:
69
+ ex = exceptions.Unauthorized
70
+ msg = "You are not logged in.\nPlease run 'apheris login' in the CLI."
71
+ if auth_header := exc.request.headers.get("Authorization"):
72
+ try:
73
+ access_token = auth_header.split()[1]
74
+ except IndexError:
75
+ pass
76
+ else:
77
+ msg += create_token_debug_msg(access_token)
78
+
79
+ exc.response.reason = msg
80
+
81
+ elif exc.response.status_code == 400 or exc.response.status_code == 424:
82
+ # apheris API bad request errors contain the details key
83
+ # We may also use other APIs, that don't have details
84
+ ex = exceptions.BadRequest
85
+ _add_reason(exc.response)
86
+ else:
87
+ # Generic error for everything else
88
+ ex = requests.exceptions.HTTPError
89
+ _add_reason(exc.response)
90
+
91
+ raise ex(exc.response.reason) from None
92
+
93
+ return wrapper
94
+
95
+
96
+ class ApherisAPI:
97
+ """
98
+ Wrapper around the Apheris API.
99
+ """
100
+
101
+ def __init__(self) -> None:
102
+ self._session, self._session_type = auth.get_session()
103
+
104
+ @handle_api_exception
105
+ def get_dataset(self, dataset_id: str) -> Dict:
106
+ """
107
+ Return information of dataset with `dataset_id` (slug).
108
+ """
109
+ response = self._session.get(settings.API_DATASETS_URL + dataset_id + "/")
110
+
111
+ if response.status_code == 403:
112
+ response.reason = (
113
+ f"You do not have permissions to access the dataset `{dataset_id}`."
114
+ )
115
+
116
+ if response.status_code == 404:
117
+ response.reason = "No dataset found for id " + dataset_id
118
+
119
+ response.raise_for_status()
120
+ return response.json()
121
+
122
+ @handle_api_exception
123
+ def get_dataset_file_details(self, dataset_id: str) -> Dict:
124
+ """
125
+ Return file details of the dataset with `dataset_id`.
126
+ """
127
+ # TODO: Return directly with get_dataset from API
128
+ response = self._session.get(f"{settings.API_DATASETS_URL}{dataset_id}/download/")
129
+
130
+ try:
131
+ response.raise_for_status()
132
+ return response.json()
133
+ except requests.exceptions.RequestException:
134
+ if settings.VERBOSE:
135
+ print(
136
+ f"Could not get dataset file details for RemoteData object "
137
+ f"with id='{dataset_id}': {response.reason}: {response.text}",
138
+ )
139
+ return {"data": {}}
140
+
141
+ @handle_api_exception
142
+ def get_datasets(self) -> List[Dict]:
143
+ """
144
+ Return available datasets for the current user.
145
+ """
146
+ response = self._session.get(settings.API_DATASETS_URL)
147
+ response.raise_for_status()
148
+
149
+ return response.json()
150
+
151
+ @handle_api_exception
152
+ def get_asset_policy_settings(self, dataset_id: str) -> Dict:
153
+ """
154
+ Return the settings (permission and privacy) of an Asset policy of the dataset
155
+ with `dataset_id`.
156
+ """
157
+ response = self._session.get(
158
+ f"{settings.API_ASSET_POLICIES_URL}settings/{dataset_id}/"
159
+ )
160
+
161
+ if response.status_code == 403:
162
+ response.reason = (
163
+ "You do not have permissions to view the asset policy for this dataset."
164
+ )
165
+
166
+ if response.status_code == 404:
167
+ response.reason = (
168
+ "Asset policy not found. Please verify the ID of the dataset."
169
+ )
170
+
171
+ response.raise_for_status()
172
+ return response.json()
173
+
174
+ @handle_api_exception
175
+ def get_user_info(self) -> Dict:
176
+ """
177
+ Returns user info payload
178
+ """
179
+ response = self._session.get(f"{settings.API_USER_INFO_URL}")
180
+ response.raise_for_status()
181
+ return response.json()
182
+
183
+
184
+ def get_client() -> ApherisAPI:
185
+ """
186
+ Apheris API client factory.
187
+ """
188
+ return ApherisAPI()