Debian Codegraph @

ibm_cloud_sdk_core/get_authenticator.py

raw
1 # coding: utf-8
2
3 # Copyright 2019, 2025 IBM All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import json
18 from .authenticators import (
19 Authenticator,
20 BasicAuthenticator,
21 BearerTokenAuthenticator,
22 ContainerAuthenticator,
23 CloudPakForDataAuthenticator,
24 IAMAuthenticator,
25 IAMAssumeAuthenticator,
26 NoAuthAuthenticator,
27 VPCInstanceAuthenticator,
28 MCSPAuthenticator,
29 MCSPV2Authenticator,
30 )
31 from .utils import read_external_sources, string_to_bool
32 from .logger import get_logger
33
34 logger = get_logger()
35
36
37 def get_authenticator_from_environment(service_name: str) -> Authenticator:
38 """Look for external configuration of authenticator.
39
40 Try to get authenticator from external sources, with the following priority:
41 1. Credentials file(ibm-credentials.env)
42 2. Environment variables
43 3. VCAP Services(Cloud Foundry)
44
45 Args:
46 service_name: The service name.
47
48 Returns:
49 The authenticator found from service information.
50 """
51 logger.debug('Get authenticator from environment, key=%s', service_name)
52 authenticator = None
53 config = read_external_sources(service_name)
54 if config:
55 authenticator = __construct_authenticator(config)
56 if authenticator is not None:
57 logger.debug('Returning authenticator, type=%s', authenticator.authentication_type())
58 return authenticator
59
60
61 # pylint: disable=too-many-branches
62 # pylint: disable=too-many-statements
63 def __construct_authenticator(config: dict) -> Authenticator:
64 # Determine the authentication type if not specified explicitly.
65 if config.get('AUTH_TYPE'):
66 auth_type = config.get('AUTH_TYPE')
67 elif config.get('AUTHTYPE'):
68 auth_type = config.get('AUTHTYPE')
69 else:
70 # If authtype wasn't specified explicitly, then determine the default.
71 # If the APIKEY property is specified, then it should be IAM, otherwise Container Auth.
72 if config.get('APIKEY'):
73 auth_type = Authenticator.AUTHTYPE_IAM
74 else:
75 auth_type = Authenticator.AUTHTYPE_CONTAINER
76
77 auth_type = auth_type.lower()
78 authenticator = None
79
80 if auth_type == Authenticator.AUTHTYPE_BASIC.lower():
81 authenticator = BasicAuthenticator(username=config.get('USERNAME'), password=config.get('PASSWORD'))
82 elif auth_type == Authenticator.AUTHTYPE_BEARERTOKEN.lower():
83 authenticator = BearerTokenAuthenticator(bearer_token=config.get('BEARER_TOKEN'))
84 elif auth_type == Authenticator.AUTHTYPE_CONTAINER.lower():
85 authenticator = ContainerAuthenticator(
86 cr_token_filename=config.get('CR_TOKEN_FILENAME'),
87 iam_profile_name=config.get('IAM_PROFILE_NAME'),
88 iam_profile_id=config.get('IAM_PROFILE_ID'),
89 url=config.get('AUTH_URL'),
90 client_id=config.get('CLIENT_ID'),
91 client_secret=config.get('CLIENT_SECRET'),
92 disable_ssl_verification=string_to_bool(config.get('AUTH_DISABLE_SSL', 'false')),
93 scope=config.get('SCOPE'),
94 )
95 elif auth_type == Authenticator.AUTHTYPE_CP4D.lower():
96 authenticator = CloudPakForDataAuthenticator(
97 username=config.get('USERNAME'),
98 password=config.get('PASSWORD'),
99 url=config.get('AUTH_URL'),
100 apikey=config.get('APIKEY'),
101 disable_ssl_verification=string_to_bool(config.get('AUTH_DISABLE_SSL', 'false')),
102 )
103 elif auth_type == Authenticator.AUTHTYPE_IAM.lower() and config.get('APIKEY'):
104 authenticator = IAMAuthenticator(
105 apikey=config.get('APIKEY'),
106 url=config.get('AUTH_URL'),
107 client_id=config.get('CLIENT_ID'),
108 client_secret=config.get('CLIENT_SECRET'),
109 disable_ssl_verification=string_to_bool(config.get('AUTH_DISABLE_SSL', 'false')),
110 scope=config.get('SCOPE'),
111 )
112 elif auth_type == Authenticator.AUTHTYPE_IAM_ASSUME.lower():
113 authenticator = IAMAssumeAuthenticator(
114 apikey=config.get('APIKEY'),
115 iam_profile_id=config.get('IAM_PROFILE_ID'),
116 iam_profile_crn=config.get('IAM_PROFILE_CRN'),
117 iam_profile_name=config.get('IAM_PROFILE_NAME'),
118 iam_account_id=config.get('IAM_ACCOUNT_ID'),
119 url=config.get('AUTH_URL'),
120 client_id=config.get('CLIENT_ID'),
121 client_secret=config.get('CLIENT_SECRET'),
122 disable_ssl_verification=string_to_bool(config.get('AUTH_DISABLE_SSL', 'false')),
123 scope=config.get('SCOPE'),
124 )
125 elif auth_type == Authenticator.AUTHTYPE_VPC.lower():
126 authenticator = VPCInstanceAuthenticator(
127 iam_profile_crn=config.get('IAM_PROFILE_CRN'),
128 iam_profile_id=config.get('IAM_PROFILE_ID'),
129 url=config.get('AUTH_URL'),
130 )
131 elif auth_type == Authenticator.AUTHTYPE_MCSP.lower():
132 authenticator = MCSPAuthenticator(
133 apikey=config.get('APIKEY'),
134 url=config.get('AUTH_URL'),
135 )
136 elif auth_type == Authenticator.AUTHTYPE_MCSPV2.lower():
137 # Required arguments.
138 apikey = config.get('APIKEY')
139 url = config.get('AUTH_URL')
140 scope_collection_type = config.get('SCOPE_COLLECTION_TYPE')
141 scope_id = config.get('SCOPE_ID')
142
143 # Optional arguments.
144 optional_args = {}
145 str_value = config.get("INCLUDE_BUILTIN_ACTIONS")
146 if str_value is not None:
147 optional_args['include_builtin_actions'] = string_to_bool(str_value)
148
149 str_value = config.get("INCLUDE_CUSTOM_ACTIONS")
150 if str_value is not None:
151 optional_args['include_custom_actions'] = string_to_bool(str_value)
152
153 str_value = config.get("INCLUDE_ROLES")
154 if str_value is not None:
155 optional_args['include_roles'] = string_to_bool(str_value)
156
157 str_value = config.get("PREFIX_ROLES")
158 if str_value is not None:
159 optional_args['prefix_roles'] = string_to_bool(str_value)
160
161 str_value = config.get("CALLER_EXT_CLAIM")
162 if str_value is not None:
163 try:
164 optional_args['caller_ext_claim'] = json.loads(str_value)
165 except Exception as caused_by:
166 msg = 'An error occurred while unmarshalling the CALLER_EXT_CLAIM configuration property: {0}'.format(
167 str_value
168 )
169 raise ValueError(msg) from caused_by
170
171 str_value = config.get("AUTH_DISABLE_SSL")
172 if str_value is not None:
173 optional_args['disable_ssl_verification'] = string_to_bool(str_value)
174
175 authenticator = MCSPV2Authenticator(
176 apikey=apikey, url=url, scope_collection_type=scope_collection_type, scope_id=scope_id, **optional_args
177 )
178 elif auth_type == Authenticator.AUTHTYPE_NOAUTH.lower():
179 authenticator = NoAuthAuthenticator()
180
181 return authenticator