Debian Codegraph @

osc_lib/cli/client_config.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12 #
13
14 """OpenStackConfig subclass for argument compatibility"""
15
16 import logging
17 import typing as ty
18
19 from keystoneauth1 import loading as ksa_loading
20 from openstack.config import exceptions as sdk_exceptions
21 from openstack.config import loader as config
22 from oslo_utils import strutils
23
24
25 LOG = logging.getLogger(__name__)
26
27
28 # Subclass OpenStackConfig in order to munge config values
29 # before auth plugins are loaded
30 class OSC_Config(config.OpenStackConfig): # type: ignore
31 def _auth_select_default_plugin(
32 self, config: dict[str, ty.Any]
33 ) -> dict[str, ty.Any]:
34 """Select a default plugin based on supplied arguments
35
36 Migrated from auth.select_auth_plugin()
37 """
38
39 identity_version = str(config.get('identity_api_version', ''))
40
41 if config.get('username', None) and not config.get('auth_type', None):
42 if identity_version == '3':
43 config['auth_type'] = 'v3password'
44 elif identity_version.startswith('2'):
45 config['auth_type'] = 'v2password'
46 else:
47 # let keystoneauth figure it out itself
48 config['auth_type'] = 'password'
49 elif config.get('token', None) and not config.get('auth_type', None):
50 if identity_version == '3':
51 config['auth_type'] = 'v3token'
52 elif identity_version.startswith('2'):
53 config['auth_type'] = 'v2token'
54 else:
55 # let keystoneauth figure it out itself
56 config['auth_type'] = 'token'
57 else:
58 # The ultimate default is similar to the original behaviour,
59 # but this time with version discovery
60 if not config.get('auth_type', None):
61 config['auth_type'] = 'password'
62
63 LOG.debug("Auth plugin {} selected".format(config['auth_type']))
64 return config
65
66 def _auth_v2_arguments(
67 self, config: dict[str, ty.Any]
68 ) -> dict[str, ty.Any]:
69 """Set up v2-required arguments from v3 info
70
71 Migrated from auth.build_auth_params()
72 """
73
74 if 'auth_type' in config and config['auth_type'].startswith("v2"):
75 if 'project_id' in config['auth']:
76 config['auth']['tenant_id'] = config['auth']['project_id']
77 if 'project_name' in config['auth']:
78 config['auth']['tenant_name'] = config['auth']['project_name']
79 return config
80
81 def _auth_v2_ignore_v3(
82 self, config: dict[str, ty.Any]
83 ) -> dict[str, ty.Any]:
84 """Remove v3 arguments if present for v2 plugin
85
86 Migrated from clientmanager.setup_auth()
87 """
88 # NOTE(hieulq): If USER_DOMAIN_NAME, USER_DOMAIN_ID, PROJECT_DOMAIN_ID
89 # or PROJECT_DOMAIN_NAME is present and API_VERSION is 2.0, then
90 # ignore all domain related configs.
91 if not str(config.get('identity_api_version', '')).startswith('2'):
92 return config
93
94 if not config.get('auth_type') or not config['auth_type'].endswith(
95 'password'
96 ):
97 return config
98
99 domain_props = [
100 'project_domain_id',
101 'project_domain_name',
102 'user_domain_id',
103 'user_domain_name',
104 ]
105 for prop in domain_props:
106 if config['auth'].pop(prop, None) is not None:
107 if config.get('cloud'):
108 LOG.warning(
109 "Ignoring domain related config {} for {}"
110 "because identity API version is 2.0".format(
111 prop, config['cloud']
112 )
113 )
114 else:
115 LOG.warning(
116 f"Ignoring domain related config {prop} because"
117 " identity API version is 2.0"
118 )
119 return config
120
121 def _auth_default_domain(
122 self, config: dict[str, ty.Any]
123 ) -> dict[str, ty.Any]:
124 """Set a default domain from available arguments
125
126 Migrated from clientmanager.setup_auth()
127 """
128
129 identity_version = str(config.get('identity_api_version', ''))
130 auth_type = config.get('auth_type', None)
131
132 # TODO(mordred): This is a usability improvement that's broadly useful
133 # We should port it back up into os-client-config.
134 default_domain = config.get('default_domain', None)
135 if (
136 identity_version == '3'
137 and (auth_type and not auth_type.startswith('v2'))
138 and default_domain
139 ):
140 # NOTE(stevemar): If PROJECT_DOMAIN_ID or PROJECT_DOMAIN_NAME is
141 # present, then do not change the behaviour. Otherwise, set the
142 # PROJECT_DOMAIN_ID to 'OS_DEFAULT_DOMAIN' for better usability.
143 if (
144 auth_type in ("password", "v3password", "v3totp")
145 and not config['auth'].get('project_domain_id')
146 and not config['auth'].get('project_domain_name')
147 ):
148 config['auth']['project_domain_id'] = default_domain
149
150 # NOTE(stevemar): If USER_DOMAIN_ID or USER_DOMAIN_NAME is present,
151 # then do not change the behaviour. Otherwise, set the
152 # USER_DOMAIN_ID to 'OS_DEFAULT_DOMAIN' for better usability.
153 # NOTE(aloga): this should only be set if there is a username.
154 # TODO(dtroyer): Move this to os-client-config after the plugin has
155 # been loaded so we can check directly if the options are accepted.
156 if (
157 auth_type in ("password", "v3password", "v3totp")
158 and not config['auth'].get('user_domain_id')
159 and not config['auth'].get('user_domain_name')
160 ):
161 config['auth']['user_domain_id'] = default_domain
162 return config
163
164 def auth_config_hook(self, config: dict[str, ty.Any]) -> dict[str, ty.Any]:
165 """Allow examination of config values before loading auth plugin
166
167 OpenStackClient will override this to perform additional checks
168 on auth_type.
169 """
170
171 config = self._auth_select_default_plugin(config)
172 config = self._auth_v2_arguments(config)
173 config = self._auth_v2_ignore_v3(config)
174 config = self._auth_default_domain(config)
175
176 if LOG.isEnabledFor(logging.DEBUG):
177 LOG.debug(
178 "auth_config_hook(): %s", strutils.mask_password(str(config))
179 )
180 return config
181
182 def _validate_auth(
183 self,
184 config: dict[str, ty.Any],
185 loader: ksa_loading.BaseLoader[ty.Any],
186 ) -> dict[str, ty.Any]:
187 """Validate auth plugin arguments"""
188 # May throw a keystoneauth1.exceptions.NoMatchingPlugin
189
190 plugin_options = loader.get_options()
191
192 msgs = []
193 prompt_options = []
194 for p_opt in plugin_options:
195 # if it's in config, win, move it and kill it from config dict
196 # if it's in config.auth but not in config we're good
197 # deprecated loses to current
198 # provided beats default, deprecated or not
199 winning_value = self._find_winning_auth_value(p_opt, config)
200 if not winning_value:
201 winning_value = self._find_winning_auth_value(
202 p_opt, config['auth']
203 )
204
205 # if the plugin tells us that this value is required
206 # then error if it's doesn't exist now
207 if not winning_value and p_opt.required:
208 msgs.append(
209 'Missing value {auth_key}'
210 ' required for auth plugin {plugin}'.format(
211 auth_key=p_opt.name,
212 plugin=config.get('auth_type'),
213 )
214 )
215
216 # Clean up after ourselves
217 for opt in [p_opt.name] + [o.name for o in p_opt.deprecated]:
218 opt = opt.replace('-', '_')
219 config.pop(opt, None)
220 config['auth'].pop(opt, None)
221
222 if winning_value:
223 # Prefer the plugin configuration dest value if the value's key
224 # is marked as depreciated.
225 if p_opt.dest is None:
226 config['auth'][p_opt.name.replace('-', '_')] = (
227 winning_value
228 )
229 else:
230 config['auth'][p_opt.dest] = winning_value
231
232 # See if this needs a prompting
233 if (
234 'prompt' in vars(p_opt)
235 and p_opt.prompt is not None
236 and p_opt.dest not in config['auth']
237 and self._pw_callback is not None
238 ):
239 # Defer these until we know all required opts are present
240 prompt_options.append(p_opt)
241
242 if msgs:
243 raise sdk_exceptions.OpenStackConfigException('\n'.join(msgs))
244
245 if prompt_options:
246 if self._pw_callback is None:
247 # we have no way to get the missing options from the user, so
248 # error out
249 raise sdk_exceptions.OpenStackConfigException(
250 'Missing authentication information: {prompt_options}'
251 )
252
253 for p_opt in prompt_options:
254 config['auth'][p_opt.dest] = self._pw_callback(p_opt.prompt)
255
256 return config
257
258 # TODO(stephenfin): Add type once we have typing for SDK
259 def load_auth_plugin(self, config: dict[str, ty.Any]) -> ty.Any:
260 """Get auth plugin and validate args"""
261
262 loader = self._get_auth_loader(config)
263 config = self._validate_auth(config, loader)
264 auth_plugin = loader.load_from_options(**config['auth'])
265 return auth_plugin