rucio-clients 32.8.6__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.

Potentially problematic release.


This version of rucio-clients might be problematic. Click here for more details.

Files changed (88) hide show
  1. rucio/__init__.py +18 -0
  2. rucio/alembicrevision.py +16 -0
  3. rucio/client/__init__.py +16 -0
  4. rucio/client/accountclient.py +413 -0
  5. rucio/client/accountlimitclient.py +155 -0
  6. rucio/client/baseclient.py +929 -0
  7. rucio/client/client.py +77 -0
  8. rucio/client/configclient.py +113 -0
  9. rucio/client/credentialclient.py +54 -0
  10. rucio/client/didclient.py +691 -0
  11. rucio/client/diracclient.py +48 -0
  12. rucio/client/downloadclient.py +1674 -0
  13. rucio/client/exportclient.py +44 -0
  14. rucio/client/fileclient.py +51 -0
  15. rucio/client/importclient.py +42 -0
  16. rucio/client/lifetimeclient.py +74 -0
  17. rucio/client/lockclient.py +99 -0
  18. rucio/client/metaclient.py +137 -0
  19. rucio/client/pingclient.py +45 -0
  20. rucio/client/replicaclient.py +444 -0
  21. rucio/client/requestclient.py +109 -0
  22. rucio/client/rseclient.py +664 -0
  23. rucio/client/ruleclient.py +287 -0
  24. rucio/client/scopeclient.py +88 -0
  25. rucio/client/subscriptionclient.py +161 -0
  26. rucio/client/touchclient.py +78 -0
  27. rucio/client/uploadclient.py +871 -0
  28. rucio/common/__init__.py +14 -0
  29. rucio/common/cache.py +74 -0
  30. rucio/common/config.py +796 -0
  31. rucio/common/constants.py +92 -0
  32. rucio/common/constraints.py +18 -0
  33. rucio/common/didtype.py +187 -0
  34. rucio/common/exception.py +1092 -0
  35. rucio/common/extra.py +37 -0
  36. rucio/common/logging.py +404 -0
  37. rucio/common/pcache.py +1387 -0
  38. rucio/common/policy.py +84 -0
  39. rucio/common/schema/__init__.py +143 -0
  40. rucio/common/schema/atlas.py +411 -0
  41. rucio/common/schema/belleii.py +406 -0
  42. rucio/common/schema/cms.py +478 -0
  43. rucio/common/schema/domatpc.py +399 -0
  44. rucio/common/schema/escape.py +424 -0
  45. rucio/common/schema/generic.py +431 -0
  46. rucio/common/schema/generic_multi_vo.py +410 -0
  47. rucio/common/schema/icecube.py +404 -0
  48. rucio/common/schema/lsst.py +423 -0
  49. rucio/common/stomp_utils.py +160 -0
  50. rucio/common/stopwatch.py +56 -0
  51. rucio/common/test_rucio_server.py +148 -0
  52. rucio/common/types.py +158 -0
  53. rucio/common/utils.py +1946 -0
  54. rucio/rse/__init__.py +97 -0
  55. rucio/rse/protocols/__init__.py +14 -0
  56. rucio/rse/protocols/cache.py +123 -0
  57. rucio/rse/protocols/dummy.py +112 -0
  58. rucio/rse/protocols/gfal.py +701 -0
  59. rucio/rse/protocols/globus.py +243 -0
  60. rucio/rse/protocols/gsiftp.py +93 -0
  61. rucio/rse/protocols/http_cache.py +83 -0
  62. rucio/rse/protocols/mock.py +124 -0
  63. rucio/rse/protocols/ngarc.py +210 -0
  64. rucio/rse/protocols/posix.py +251 -0
  65. rucio/rse/protocols/protocol.py +530 -0
  66. rucio/rse/protocols/rclone.py +365 -0
  67. rucio/rse/protocols/rfio.py +137 -0
  68. rucio/rse/protocols/srm.py +339 -0
  69. rucio/rse/protocols/ssh.py +414 -0
  70. rucio/rse/protocols/storm.py +207 -0
  71. rucio/rse/protocols/webdav.py +547 -0
  72. rucio/rse/protocols/xrootd.py +295 -0
  73. rucio/rse/rsemanager.py +752 -0
  74. rucio/vcsversion.py +11 -0
  75. rucio/version.py +46 -0
  76. rucio_clients-32.8.6.data/data/etc/rse-accounts.cfg.template +25 -0
  77. rucio_clients-32.8.6.data/data/etc/rucio.cfg.atlas.client.template +42 -0
  78. rucio_clients-32.8.6.data/data/etc/rucio.cfg.template +257 -0
  79. rucio_clients-32.8.6.data/data/requirements.txt +55 -0
  80. rucio_clients-32.8.6.data/data/rucio_client/merge_rucio_configs.py +147 -0
  81. rucio_clients-32.8.6.data/scripts/rucio +2540 -0
  82. rucio_clients-32.8.6.data/scripts/rucio-admin +2434 -0
  83. rucio_clients-32.8.6.dist-info/METADATA +50 -0
  84. rucio_clients-32.8.6.dist-info/RECORD +88 -0
  85. rucio_clients-32.8.6.dist-info/WHEEL +5 -0
  86. rucio_clients-32.8.6.dist-info/licenses/AUTHORS.rst +94 -0
  87. rucio_clients-32.8.6.dist-info/licenses/LICENSE +201 -0
  88. rucio_clients-32.8.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,929 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright European Organization for Nuclear Research (CERN) since 2012
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ '''
17
+ Client class for callers of the Rucio system
18
+ '''
19
+
20
+ import errno
21
+ import getpass
22
+ import os
23
+ import random
24
+ import sys
25
+ import time
26
+ from configparser import NoOptionError, NoSectionError
27
+ from os import environ, fdopen, path, makedirs, geteuid
28
+ from shutil import move
29
+ from tempfile import mkstemp
30
+ from urllib.parse import urlparse
31
+
32
+ from dogpile.cache import make_region
33
+ from requests import Session, Response
34
+ from requests.exceptions import ConnectionError
35
+ from requests.status_codes import codes
36
+
37
+ from rucio import version
38
+ from rucio.common import exception
39
+ from rucio.common.config import config_get, config_get_bool, config_get_int
40
+ from rucio.common.exception import (CannotAuthenticate, ClientProtocolNotSupported,
41
+ NoAuthInformation, MissingClientParameter,
42
+ MissingModuleException, ServerConnectionException)
43
+ from rucio.common.extra import import_extras
44
+ from rucio.common.utils import build_url, get_tmp_dir, my_key_generator, parse_response, ssh_sign, setup_logger
45
+
46
+ EXTRA_MODULES = import_extras(['requests_kerberos'])
47
+
48
+ if EXTRA_MODULES['requests_kerberos']:
49
+ from requests_kerberos import HTTPKerberosAuth # pylint: disable=import-error
50
+
51
+ LOG = setup_logger(module_name=__name__)
52
+
53
+ REGION = make_region(function_key_generator=my_key_generator).configure(
54
+ 'dogpile.cache.memory',
55
+ expiration_time=60,
56
+ )
57
+
58
+ STATUS_CODES_TO_RETRY = [502, 503, 504]
59
+ MAX_RETRY_BACK_OFF_SECONDS = 10
60
+
61
+
62
+ @REGION.cache_on_arguments(namespace='host_to_choose')
63
+ def choice(hosts):
64
+ """
65
+ Select randomly a host
66
+
67
+ :param hosts: Lost of hosts
68
+ :return: A randomly selected host.
69
+ """
70
+ return random.choice(hosts)
71
+
72
+
73
+ class BaseClient(object):
74
+
75
+ """Main client class for accessing Rucio resources. Handles the authentication."""
76
+
77
+ AUTH_RETRIES, REQUEST_RETRIES = 2, 3
78
+ TOKEN_PATH_PREFIX = get_tmp_dir() + '/.rucio_'
79
+ TOKEN_PREFIX = 'auth_token_'
80
+ TOKEN_EXP_PREFIX = 'auth_token_exp_'
81
+
82
+ def __init__(self, rucio_host=None, auth_host=None, account=None, ca_cert=None, auth_type=None, creds=None, timeout=600, user_agent='rucio-clients', vo=None, logger=None):
83
+ """
84
+ Constructor of the BaseClient.
85
+ :param rucio_host: The address of the rucio server, if None it is read from the config file.
86
+ :param rucio_port: The port of the rucio server, if None it is read from the config file.
87
+ :param auth_host: The address of the rucio authentication server, if None it is read from the config file.
88
+ :param auth_port: The port of the rucio authentication server, if None it is read from the config file.
89
+ :param account: The account to authenticate to rucio.
90
+ :param use_ssl: Enable or disable ssl for commucation. Default is enabled.
91
+ :param ca_cert: The path to the rucio server certificate.
92
+ :param auth_type: The type of authentication (e.g.: 'userpass', 'kerberos' ...)
93
+ :param creds: Dictionary with credentials needed for authentication.
94
+ :param user_agent: Indicates the client.
95
+ :param vo: The VO to authenticate into.
96
+ :param logger: Logger object to use. If None, use the default LOG created by the module
97
+ """
98
+
99
+ self.host = rucio_host
100
+ self.list_hosts = []
101
+ self.auth_host = auth_host
102
+ self.logger = logger or LOG
103
+ self.session = Session()
104
+ self.user_agent = "%s/%s" % (user_agent, version.version_string()) # e.g. "rucio-clients/0.2.13"
105
+ sys.argv[0] = sys.argv[0].split('/')[-1]
106
+ self.script_id = '::'.join(sys.argv[0:2])
107
+ if self.script_id == '': # Python interpreter used
108
+ self.script_id = 'python'
109
+ try:
110
+ if self.host is None:
111
+ self.host = config_get('client', 'rucio_host')
112
+ if self.auth_host is None:
113
+ self.auth_host = config_get('client', 'auth_host')
114
+ except (NoOptionError, NoSectionError) as error:
115
+ raise MissingClientParameter('Section client and Option \'%s\' cannot be found in config file' % error.args[0])
116
+
117
+ try:
118
+ self.trace_host = config_get('trace', 'trace_host')
119
+ except (NoOptionError, NoSectionError):
120
+ self.trace_host = self.host
121
+ self.logger.debug('No trace_host passed. Using rucio_host instead')
122
+
123
+ self.account = account
124
+ self.vo = vo
125
+ self.ca_cert = ca_cert
126
+ self.auth_type = auth_type
127
+ self.creds = creds
128
+ self.auth_token = None
129
+ self.auth_token_file_path = config_get('client', 'auth_token_file_path', False, None)
130
+ self.headers = {}
131
+ self.timeout = timeout
132
+ self.request_retries = self.REQUEST_RETRIES
133
+ self.token_exp_epoch = None
134
+ self.token_exp_epoch_file = None
135
+ self.auth_oidc_refresh_active = config_get_bool('client', 'auth_oidc_refresh_active', False, False)
136
+ # defining how many minutes before token expires, oidc refresh (if active) should start
137
+ self.auth_oidc_refresh_before_exp = config_get_int('client', 'auth_oidc_refresh_before_exp', False, 20)
138
+
139
+ if auth_type is None:
140
+ self.logger.debug('No auth_type passed. Trying to get it from the environment variable RUCIO_AUTH_TYPE and config file.')
141
+ if 'RUCIO_AUTH_TYPE' in environ:
142
+ if environ['RUCIO_AUTH_TYPE'] not in ['userpass', 'x509', 'x509_proxy', 'gss', 'ssh', 'saml', 'oidc']:
143
+ raise MissingClientParameter('Possible RUCIO_AUTH_TYPE values: userpass, x509, x509_proxy, gss, ssh, saml, oidc, vs. ' + environ['RUCIO_AUTH_TYPE'])
144
+ self.auth_type = environ['RUCIO_AUTH_TYPE']
145
+ else:
146
+ try:
147
+ self.auth_type = config_get('client', 'auth_type')
148
+ except (NoOptionError, NoSectionError) as error:
149
+ raise MissingClientParameter('Option \'%s\' cannot be found in config file' % error.args[0])
150
+
151
+ if self.auth_type == 'oidc':
152
+ if not self.creds:
153
+ self.creds = {}
154
+ # if there are defautl values, check if rucio.cfg does not specify them, otherwise put default
155
+ if 'oidc_refresh_lifetime' not in self.creds or self.creds['oidc_refresh_lifetime'] is None:
156
+ self.creds['oidc_refresh_lifetime'] = config_get('client', 'oidc_refresh_lifetime', False, None)
157
+ if 'oidc_issuer' not in self.creds or self.creds['oidc_issuer'] is None:
158
+ self.creds['oidc_issuer'] = config_get('client', 'oidc_issuer', False, None)
159
+ if 'oidc_audience' not in self.creds or self.creds['oidc_audience'] is None:
160
+ self.creds['oidc_audience'] = config_get('client', 'oidc_audience', False, None)
161
+ if 'oidc_auto' not in self.creds or self.creds['oidc_auto'] is False:
162
+ self.creds['oidc_auto'] = config_get_bool('client', 'oidc_auto', False, False)
163
+ if self.creds['oidc_auto']:
164
+ if 'oidc_username' not in self.creds or self.creds['oidc_username'] is None:
165
+ self.creds['oidc_username'] = config_get('client', 'oidc_username', False, None)
166
+ if 'oidc_password' not in self.creds or self.creds['oidc_password'] is None:
167
+ self.creds['oidc_password'] = config_get('client', 'oidc_password', False, None)
168
+ if 'oidc_scope' not in self.creds or self.creds['oidc_scope'] == 'openid profile':
169
+ self.creds['oidc_scope'] = config_get('client', 'oidc_scope', False, 'openid profile')
170
+ if 'oidc_polling' not in self.creds or self.creds['oidc_polling'] is False:
171
+ self.creds['oidc_polling'] = config_get_bool('client', 'oidc_polling', False, False)
172
+
173
+ if not self.creds:
174
+ self.logger.debug('No creds passed. Trying to get it from the config file.')
175
+ self.creds = {}
176
+ try:
177
+ if self.auth_type in ['userpass', 'saml']:
178
+ self.creds['username'] = config_get('client', 'username')
179
+ self.creds['password'] = config_get('client', 'password')
180
+ elif self.auth_type == 'x509':
181
+ if "RUCIO_CLIENT_CERT" in environ:
182
+ client_cert = environ["RUCIO_CLIENT_CERT"]
183
+ else:
184
+ client_cert = config_get('client', 'client_cert')
185
+ self.creds['client_cert'] = path.abspath(path.expanduser(path.expandvars(client_cert)))
186
+ if not path.exists(self.creds['client_cert']):
187
+ raise MissingClientParameter('X.509 client certificate not found: %s' % self.creds['client_cert'])
188
+
189
+ if "RUCIO_CLIENT_KEY" in environ:
190
+ client_key = environ["RUCIO_CLIENT_KEY"]
191
+ else:
192
+ client_key = config_get('client', 'client_key')
193
+ self.creds['client_key'] = path.abspath(path.expanduser(path.expandvars(client_key)))
194
+ if not path.exists(self.creds['client_key']):
195
+ raise MissingClientParameter('X.509 client key not found: %s' % self.creds['client_key'])
196
+ else:
197
+ perms = oct(os.stat(self.creds['client_key']).st_mode)[-3:]
198
+ if perms not in ['400', '600']:
199
+ raise CannotAuthenticate('X.509 authentication selected, but private key (%s) permissions are liberal (required: 400 or 600, found: %s)' % (self.creds['client_key'], perms))
200
+
201
+ elif self.auth_type == 'x509_proxy':
202
+ try:
203
+ self.creds['client_proxy'] = path.abspath(path.expanduser(path.expandvars(config_get('client', 'client_x509_proxy'))))
204
+ except NoOptionError:
205
+ # Recreate the classic GSI logic for locating the proxy:
206
+ # - $X509_USER_PROXY, if it is set.
207
+ # - /tmp/x509up_u`id -u` otherwise.
208
+ # If neither exists (at this point, we don't care if it exists but is invalid), then rethrow
209
+ if 'X509_USER_PROXY' in environ:
210
+ self.creds['client_proxy'] = environ['X509_USER_PROXY']
211
+ else:
212
+ fname = '/tmp/x509up_u%d' % geteuid()
213
+ if path.exists(fname):
214
+ self.creds['client_proxy'] = fname
215
+ else:
216
+ raise MissingClientParameter('Cannot find a valid X509 proxy; not in %s, $X509_USER_PROXY not set, and '
217
+ '\'x509_proxy\' not set in the configuration file.' % fname)
218
+ elif self.auth_type == 'ssh':
219
+ self.creds['ssh_private_key'] = path.abspath(path.expanduser(path.expandvars(config_get('client', 'ssh_private_key'))))
220
+ except (NoOptionError, NoSectionError) as error:
221
+ if error.args[0] != 'client_key':
222
+ raise MissingClientParameter('Option \'%s\' cannot be found in config file' % error.args[0])
223
+
224
+ rucio_scheme = urlparse(self.host).scheme
225
+ auth_scheme = urlparse(self.auth_host).scheme
226
+
227
+ if rucio_scheme != 'http' and rucio_scheme != 'https':
228
+ raise ClientProtocolNotSupported('\'%s\' not supported' % rucio_scheme)
229
+
230
+ if auth_scheme != 'http' and auth_scheme != 'https':
231
+ raise ClientProtocolNotSupported('\'%s\' not supported' % auth_scheme)
232
+
233
+ if (rucio_scheme == 'https' or auth_scheme == 'https') and ca_cert is None:
234
+ self.logger.debug('HTTPS is required, but no ca_cert was passed. Trying to get it from X509_CERT_DIR.')
235
+ self.ca_cert = os.environ.get('X509_CERT_DIR', None)
236
+ if self.ca_cert is None:
237
+ self.logger.debug('HTTPS is required, but no ca_cert was passed and X509_CERT_DIR is not defined. Trying to get it from the config file.')
238
+ try:
239
+ self.ca_cert = path.expandvars(config_get('client', 'ca_cert'))
240
+ except (NoOptionError, NoSectionError):
241
+ self.logger.debug('No ca_cert found in configuration. Falling back to Mozilla default CA bundle (certifi).')
242
+ self.ca_cert = True
243
+
244
+ self.list_hosts = [self.host]
245
+
246
+ if account is None:
247
+ self.logger.debug('No account passed. Trying to get it from the RUCIO_ACCOUNT environment variable or the config file.')
248
+ try:
249
+ self.account = environ['RUCIO_ACCOUNT']
250
+ except KeyError:
251
+ try:
252
+ self.account = config_get('client', 'account')
253
+ except (NoOptionError, NoSectionError):
254
+ pass
255
+
256
+ if vo is None:
257
+ self.logger.debug('No VO passed. Trying to get it from environment variable RUCIO_VO.')
258
+ try:
259
+ self.vo = environ['RUCIO_VO']
260
+ except KeyError:
261
+ self.logger.debug('No VO found. Trying to get it from the config file.')
262
+ try:
263
+ self.vo = config_get('client', 'vo')
264
+ except (NoOptionError, NoSectionError):
265
+ self.logger.debug('No VO found. Using default VO.')
266
+ self.vo = 'def'
267
+
268
+ token_filename_suffix = "for_default_account" if self.account is None else "for_account_" + self.account
269
+
270
+ # if token file path is defined in the rucio.cfg file, use that file. Currently this prevents authenticating as another user or VO.
271
+ if self.auth_token_file_path:
272
+ self.token_file = self.auth_token_file_path
273
+ self.token_path = '/'.join(self.token_file.split('/')[:-1])
274
+ else:
275
+ self.token_path = self.TOKEN_PATH_PREFIX + getpass.getuser()
276
+ if self.vo != 'def':
277
+ self.token_path += '@%s' % self.vo
278
+ self.token_file = self.token_path + '/' + self.TOKEN_PREFIX + token_filename_suffix
279
+
280
+ self.token_exp_epoch_file = self.token_path + '/' + self.TOKEN_EXP_PREFIX + token_filename_suffix
281
+
282
+ self.__authenticate()
283
+
284
+ try:
285
+ self.request_retries = config_get_int('client', 'request_retries')
286
+ except (NoOptionError, RuntimeError):
287
+ LOG.debug('request_retries not specified in config file. Taking default.')
288
+ except ValueError:
289
+ self.logger.debug('request_retries must be an integer. Taking default.')
290
+
291
+ def _get_exception(self, headers, status_code=None, data=None):
292
+ """
293
+ Helper method to parse an error string send by the server and transform it into the corresponding rucio exception.
294
+
295
+ :param headers: The http response header containing the Rucio exception details.
296
+ :param status_code: The http status code.
297
+ :param data: The data with the ExceptionMessage.
298
+
299
+ :return: A rucio exception class and an error string.
300
+ """
301
+ try:
302
+ data = parse_response(data)
303
+ except ValueError:
304
+ data = {}
305
+
306
+ exc_cls = 'RucioException'
307
+ exc_msg = 'no error information passed (http status code: %s)' % status_code
308
+ if 'ExceptionClass' in data:
309
+ exc_cls = data['ExceptionClass']
310
+ elif 'ExceptionClass' in headers:
311
+ exc_cls = headers['ExceptionClass']
312
+ if 'ExceptionMessage' in data:
313
+ exc_msg = data['ExceptionMessage']
314
+ elif 'ExceptionMessage' in headers:
315
+ exc_msg = headers['ExceptionMessage']
316
+
317
+ if hasattr(exception, exc_cls):
318
+ return getattr(exception, exc_cls), exc_msg
319
+ else:
320
+ return exception.RucioException, "%s: %s" % (exc_cls, exc_msg)
321
+
322
+ def _load_json_data(self, response):
323
+ """
324
+ Helper method to correctly load json data based on the content type of the http response.
325
+
326
+ :param response: the response received from the server.
327
+ """
328
+ if 'content-type' in response.headers and response.headers['content-type'] == 'application/x-json-stream':
329
+ for line in response.iter_lines():
330
+ if line:
331
+ yield parse_response(line)
332
+ elif 'content-type' in response.headers and response.headers['content-type'] == 'application/json':
333
+ yield parse_response(response.text)
334
+ else: # Exception ?
335
+ if response.text:
336
+ yield response.text
337
+
338
+ def _reduce_data(self, data, maxlen=132):
339
+ text = data if isinstance(data, str) else data.decode("utf-8")
340
+ if len(text) > maxlen:
341
+ text = "%s ... %s" % (text[:maxlen - 15], text[-10:])
342
+ return text
343
+
344
+ def _back_off(self, retry_number, reason):
345
+ """
346
+ Sleep a certain amount of time which increases with the retry count
347
+ :param retry_number: the retry iteration
348
+ :param reason: the reason to backoff which will be shown to the user
349
+ """
350
+ sleep_time = min(MAX_RETRY_BACK_OFF_SECONDS, 0.25 * 2 ** retry_number)
351
+ self.logger.warning("Waiting {}s due to reason: {} ".format(sleep_time, reason))
352
+ time.sleep(sleep_time)
353
+
354
+ def _send_request(self, url, headers=None, type_='GET', data=None, params=None, stream=False, get_token=False,
355
+ cert=None, auth=None, verify=None):
356
+ """
357
+ Helper method to send requests to the rucio server. Gets a new token and retries if an unauthorized error is returned.
358
+
359
+ :param url: the http url to use.
360
+ :param headers: additional http headers to send.
361
+ :param type_: the http request type to use.
362
+ :param data: post data.
363
+ :param params: (optional) Dictionary or bytes to be sent in the url query string.
364
+ :param get_token: (optional) if it is called from a _get_token function.
365
+ :param cert: (optional) if String, path to the SSL client cert file (.pem). If Tuple, (cert, key) pair.
366
+ :param auth: (optional) auth tuple to enable Basic/Digest/Custom HTTP Auth.
367
+ :param verify: (optional) either a boolean, in which case it controls whether we verify the server's TLS
368
+ certificate, or a string, in which case it must be a path to a CA bundle to use.
369
+ :return: the HTTP return body.
370
+ """
371
+ hds = {'X-Rucio-Auth-Token': self.auth_token, 'X-Rucio-VO': self.vo,
372
+ 'Connection': 'Keep-Alive', 'User-Agent': self.user_agent,
373
+ 'X-Rucio-Script': self.script_id}
374
+
375
+ if self.account is not None:
376
+ hds['X-Rucio-Account'] = self.account
377
+
378
+ if headers is not None:
379
+ hds.update(headers)
380
+ if verify is None:
381
+ verify = self.ca_cert or False # Maybe unnecessary but make sure to convert "" -> False
382
+
383
+ self.logger.debug("HTTP request: %s %s" % (type_, url))
384
+ for h, v in hds.items():
385
+ if h == 'X-Rucio-Auth-Token':
386
+ v = "[hidden]"
387
+ self.logger.debug("HTTP header: %s: %s" % (h, v))
388
+ if type_ != "GET" and data:
389
+ text = self._reduce_data(data)
390
+ self.logger.debug("Request data (length=%d): [%s]" % (len(data), text))
391
+
392
+ result = None
393
+ for retry in range(self.AUTH_RETRIES + 1):
394
+ try:
395
+ if type_ == 'GET':
396
+ result = self.session.get(url, headers=hds, verify=verify, timeout=self.timeout, params=params, stream=True, cert=cert, auth=auth)
397
+ elif type_ == 'PUT':
398
+ result = self.session.put(url, headers=hds, data=data, verify=verify, timeout=self.timeout)
399
+ elif type_ == 'POST':
400
+ result = self.session.post(url, headers=hds, data=data, verify=verify, timeout=self.timeout, stream=stream)
401
+ elif type_ == 'DEL':
402
+ result = self.session.delete(url, headers=hds, data=data, verify=verify, timeout=self.timeout)
403
+ else:
404
+ self.logger.debug("Unknown request type %s. Request was not sent" % (type_,))
405
+ return None
406
+ self.logger.debug("HTTP Response: %s %s" % (result.status_code, result.reason))
407
+ if result.status_code in STATUS_CODES_TO_RETRY:
408
+ self._back_off(retry, 'server returned {}'.format(result.status_code))
409
+ continue
410
+ if result.status_code // 100 != 2 and result.text:
411
+ # do not do this for successful requests because the caller may be expecting streamed response
412
+ self.logger.debug("Response text (length=%d): [%s]" % (len(result.text), result.text))
413
+ except ConnectionError as error:
414
+ self.logger.error('ConnectionError: ' + str(error))
415
+ if retry > self.request_retries:
416
+ raise
417
+ continue
418
+ except IOError as error:
419
+ # Handle Broken Pipe
420
+ # While in python3 we can directly catch 'BrokenPipeError', in python2 it doesn't exist.
421
+ if getattr(error, 'errno') != errno.EPIPE:
422
+ raise
423
+ self.logger.error('BrokenPipe: ' + str(error))
424
+ if retry > self.request_retries:
425
+ raise
426
+ continue
427
+
428
+ if result is not None and result.status_code == codes.unauthorized and not get_token: # pylint: disable-msg=E1101
429
+ self.session = Session()
430
+ self.__get_token()
431
+ hds['X-Rucio-Auth-Token'] = self.auth_token
432
+ else:
433
+ break
434
+
435
+ if result is None:
436
+ raise ServerConnectionException
437
+ return result
438
+
439
+ def __get_token_userpass(self):
440
+ """
441
+ Sends a request to get an auth token from the server and stores it as a class attribute. Uses username/password.
442
+
443
+ :returns: True if the token was successfully received. False otherwise.
444
+ """
445
+
446
+ headers = {'X-Rucio-Username': self.creds['username'],
447
+ 'X-Rucio-Password': self.creds['password']}
448
+
449
+ url = build_url(self.auth_host, path='auth/userpass')
450
+
451
+ result = self._send_request(url, headers=headers, get_token=True)
452
+
453
+ if not result:
454
+ # result is either None or not OK.
455
+ if isinstance(result, Response):
456
+ if 'ExceptionClass' in result.headers and result.headers['ExceptionClass']:
457
+ if 'ExceptionMessage' in result.headers and result.headers['ExceptionMessage']:
458
+ raise CannotAuthenticate('%s: %s' % (result.headers['ExceptionClass'], result.headers['ExceptionMessage']))
459
+ else:
460
+ raise CannotAuthenticate(result.headers["ExceptionClass"])
461
+ elif result.text:
462
+ raise CannotAuthenticate(result.text)
463
+ self.logger.error('Cannot retrieve authentication token!')
464
+ return False
465
+
466
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
467
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
468
+ status_code=result.status_code,
469
+ data=result.content)
470
+ raise exc_cls(exc_msg)
471
+
472
+ self.auth_token = result.headers['x-rucio-auth-token']
473
+ return True
474
+
475
+ def __refresh_token_OIDC(self):
476
+ """
477
+ Checks if there is active refresh token and if so returns
478
+ either active token with expiration timestamp or requests a new
479
+ refresh and returns new access token with new expiration timestamp
480
+ and saves these in the token directory.
481
+
482
+ :returns: True if the token was successfully received. False otherwise.
483
+ """
484
+
485
+ if not self.auth_oidc_refresh_active:
486
+ return False
487
+ if path.exists(self.token_exp_epoch_file):
488
+ with open(self.token_exp_epoch_file, 'r') as token_epoch_file:
489
+ try:
490
+ self.token_exp_epoch = int(token_epoch_file.readline())
491
+ except:
492
+ self.token_exp_epoch = None
493
+
494
+ if self.token_exp_epoch is None:
495
+ # check expiration time for a new token
496
+ pass
497
+ elif time.time() > self.token_exp_epoch - self.auth_oidc_refresh_before_exp * 60 and time.time() < self.token_exp_epoch:
498
+ # attempt to refresh token
499
+ pass
500
+ else:
501
+ return False
502
+
503
+ request_refresh_url = build_url(self.auth_host, path='auth/oidc_refresh')
504
+ refresh_result = self._send_request(request_refresh_url, get_token=True)
505
+ if refresh_result.status_code == codes.ok:
506
+ if 'X-Rucio-Auth-Token-Expires' not in refresh_result.headers or \
507
+ 'X-Rucio-Auth-Token' not in refresh_result.headers:
508
+ print("Rucio Server response does not contain the expected headers.")
509
+ return False
510
+ else:
511
+ new_token = refresh_result.headers['X-Rucio-Auth-Token']
512
+ new_exp_epoch = refresh_result.headers['X-Rucio-Auth-Token-Expires']
513
+ if new_token and new_exp_epoch:
514
+ self.logger.debug("Saving token %s and expiration epoch %s to files" % (str(new_token), str(new_exp_epoch)))
515
+ # save to the file
516
+ self.auth_token = new_token
517
+ self.token_exp_epoch = new_exp_epoch
518
+ self.__write_token()
519
+ self.headers['X-Rucio-Auth-Token'] = self.auth_token
520
+ return True
521
+ self.logger.debug("No new token was received, possibly invalid/expired \
522
+ \ntoken or a token with no refresh token in Rucio DB")
523
+ return False
524
+ else:
525
+ print("Rucio Client did not succeed to contact the \
526
+ \nRucio Auth Server when attempting token refresh.")
527
+ return False
528
+
529
+ def __get_token_OIDC(self):
530
+ """
531
+ First authenticates the user via a Identity Provider server
532
+ (with user's username & password), by specifying oidc_scope,
533
+ user agrees to share the relevant information with Rucio.
534
+ If all proceeds well, an access token is requested from the Identity Provider.
535
+ Access Tokens are not stored in Rucio DB.
536
+ Refresh Tokens are granted only in case no valid access token exists in user's
537
+ local storage, oidc_scope includes 'offline_access'. In such case, refresh token
538
+ is stored in Rucio DB.
539
+
540
+ :returns: True if the token was successfully received. False otherwise.
541
+ """
542
+ oidc_scope = str(self.creds['oidc_scope'])
543
+ headers = {'X-Rucio-Client-Authorize-Auto': str(self.creds['oidc_auto']),
544
+ 'X-Rucio-Client-Authorize-Polling': str(self.creds['oidc_polling']),
545
+ 'X-Rucio-Client-Authorize-Scope': str(self.creds['oidc_scope']),
546
+ 'X-Rucio-Client-Authorize-Refresh-Lifetime': str(self.creds['oidc_refresh_lifetime'])}
547
+ if self.creds['oidc_audience']:
548
+ headers['X-Rucio-Client-Authorize-Audience'] = str(self.creds['oidc_audience'])
549
+ if self.creds['oidc_issuer']:
550
+ headers['X-Rucio-Client-Authorize-Issuer'] = str(self.creds['oidc_issuer'])
551
+ if self.creds['oidc_auto']:
552
+ userpass = {'username': self.creds['oidc_username'], 'password': self.creds['oidc_password']}
553
+
554
+ result = None
555
+ request_auth_url = build_url(self.auth_host, path='auth/oidc')
556
+ # requesting authorization URL specific to the user & Rucio OIDC Client
557
+ self.logger.debug("Initial auth URL request headers %s to files" % str(headers))
558
+ OIDC_auth_res = self._send_request(request_auth_url, headers=headers, get_token=True)
559
+ self.logger.debug("Response headers %s and text %s" % (str(OIDC_auth_res.headers), str(OIDC_auth_res.text)))
560
+ # with the obtained authorization URL we will contact the Identity Provider to get to the login page
561
+ if 'X-Rucio-OIDC-Auth-URL' not in OIDC_auth_res.headers:
562
+ print("Rucio Client did not succeed to get AuthN/Z URL from the Rucio Auth Server. \
563
+ \nThis could be due to wrongly requested/configured scope, audience or issuer.")
564
+ return False
565
+ auth_url = OIDC_auth_res.headers['X-Rucio-OIDC-Auth-URL']
566
+ if not self.creds['oidc_auto']:
567
+ print("\nPlease use your internet browser, go to:")
568
+ print("\n " + auth_url + " \n")
569
+ print("and authenticate with your Identity Provider.")
570
+
571
+ headers['X-Rucio-Client-Fetch-Token'] = 'True'
572
+ if self.creds['oidc_polling']:
573
+ timeout = 180
574
+ start = time.time()
575
+ print("In the next 3 minutes, Rucio Client will be polling \
576
+ \nthe Rucio authentication server for a token.")
577
+ print("----------------------------------------------")
578
+ while time.time() - start < timeout:
579
+ result = self._send_request(auth_url, headers=headers, get_token=True)
580
+ if 'X-Rucio-Auth-Token' in result.headers and result.status_code == codes.ok:
581
+ break
582
+ time.sleep(2)
583
+ else:
584
+ print("Copy paste the code from the browser to the terminal and press enter:")
585
+ count = 0
586
+ while count < 3:
587
+ fetchcode = input()
588
+ fetch_url = build_url(self.auth_host, path='auth/oidc_redirect', params=fetchcode)
589
+ result = self._send_request(fetch_url, headers=headers, get_token=True)
590
+ if 'X-Rucio-Auth-Token' in result.headers and result.status_code == codes.ok:
591
+ break
592
+ else:
593
+ print("The Rucio Auth Server did not respond as expected. Please, "
594
+ + "try again and make sure you typed the correct code.") # NOQA: W503
595
+ count += 1
596
+
597
+ else:
598
+ print("\nAccording to the OAuth2/OIDC standard you should NOT be sharing \n"
599
+ + "your password with any 3rd party appplication, therefore, \n" # NOQA: W503
600
+ + "we strongly discourage you from following this --oidc-auto approach.") # NOQA: W503
601
+ print("-------------------------------------------------------------------------")
602
+ auth_res = self._send_request(auth_url, get_token=True)
603
+ # getting the login URL and logging in the user
604
+ login_url = auth_res.url
605
+ start = time.time()
606
+ result = self._send_request(login_url, type_='POST', data=userpass)
607
+
608
+ # if the Rucio OIDC Client configuration does not match the one registered at the Identity Provider
609
+ # the user will get an OAuth error
610
+ if 'OAuth Error' in result.text:
611
+ self.logger.error('Identity Provider does not allow to proceed. Could be due \
612
+ \nto misconfigured redirection server name of the Rucio OIDC Client.')
613
+ return False
614
+ # In case Rucio Client is not authorized to request information about this user yet,
615
+ # it will automatically authorize itself on behalf of the user.
616
+ if result.url == auth_url:
617
+ form_data = {}
618
+ for scope_item in oidc_scope.split():
619
+ form_data["scope_" + scope_item] = scope_item
620
+ default_data = {"remember": "until-revoked",
621
+ "user_oauth_approval": True,
622
+ "authorize": "Authorize"}
623
+ form_data.update(default_data)
624
+ print('Automatically authorising request of the following info on behalf of user: %s', str(form_data))
625
+ self.logger.warning('Automatically authorising request of the following info on behalf of user: %s',
626
+ str(form_data))
627
+ # authorizing info request on behalf of the user until he/she revokes this authorization !
628
+ result = self._send_request(result.url, type_='POST', data=form_data)
629
+
630
+ if not result:
631
+ self.logger.error('Cannot retrieve authentication token!')
632
+ return False
633
+
634
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
635
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
636
+ status_code=result.status_code,
637
+ data=result.content)
638
+ raise exc_cls(exc_msg)
639
+
640
+ self.auth_token = result.headers['x-rucio-auth-token']
641
+ if self.auth_oidc_refresh_active:
642
+ self.logger.debug("Reseting the token expiration epoch file content.")
643
+ # reset the token expiration epoch file content
644
+ # at new CLI OIDC authentication
645
+ self.token_exp_epoch = None
646
+ file_d, file_n = mkstemp(dir=self.token_path)
647
+ with fdopen(file_d, "w") as f_exp_epoch:
648
+ f_exp_epoch.write(str(self.token_exp_epoch))
649
+ move(file_n, self.token_exp_epoch_file)
650
+ self.__refresh_token_OIDC()
651
+ return True
652
+
653
+ def __get_token_x509(self):
654
+ """
655
+ Sends a request to get an auth token from the server and stores it as a class attribute. Uses x509 authentication.
656
+
657
+ :returns: True if the token was successfully received. False otherwise.
658
+ """
659
+ client_cert = None
660
+ client_key = None
661
+ if self.auth_type == 'x509':
662
+ url = build_url(self.auth_host, path='auth/x509')
663
+ client_cert = self.creds['client_cert']
664
+ if 'client_key' in self.creds:
665
+ client_key = self.creds['client_key']
666
+ elif self.auth_type == 'x509_proxy':
667
+ url = build_url(self.auth_host, path='auth/x509_proxy')
668
+ client_cert = self.creds['client_proxy']
669
+
670
+ if not path.exists(client_cert):
671
+ self.logger.error('given client cert (%s) doesn\'t exist' % client_cert)
672
+ return False
673
+ if client_key is not None and not path.exists(client_key):
674
+ self.logger.error('given client key (%s) doesn\'t exist' % client_key)
675
+
676
+ if client_key is None:
677
+ cert = client_cert
678
+ else:
679
+ cert = (client_cert, client_key)
680
+
681
+ result = self._send_request(url, get_token=True, cert=cert)
682
+
683
+ # Note a response object for a failed request evaluates to false, so we cannot
684
+ # use "not result" here
685
+ if result is None:
686
+ self.logger.error('Internal error: Request for authentication token returned no result!')
687
+ return False
688
+
689
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
690
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
691
+ status_code=result.status_code,
692
+ data=result.content)
693
+ raise exc_cls(exc_msg)
694
+
695
+ self.auth_token = result.headers['x-rucio-auth-token']
696
+ return True
697
+
698
+ def __get_token_ssh(self):
699
+ """
700
+ Sends a request to get an auth token from the server and stores it as a class attribute. Uses SSH key exchange authentication.
701
+
702
+ :returns: True if the token was successfully received. False otherwise.
703
+ """
704
+ headers = {}
705
+
706
+ private_key_path = self.creds['ssh_private_key']
707
+ if not path.exists(private_key_path):
708
+ self.logger.error('given private key (%s) doesn\'t exist' % private_key_path)
709
+ return False
710
+ if private_key_path is not None and not path.exists(private_key_path):
711
+ self.logger.error('given private key (%s) doesn\'t exist' % private_key_path)
712
+ return False
713
+
714
+ url = build_url(self.auth_host, path='auth/ssh_challenge_token')
715
+
716
+ result = self._send_request(url, get_token=True)
717
+
718
+ if not result:
719
+ self.logger.error('cannot get ssh_challenge_token')
720
+ return False
721
+
722
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
723
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
724
+ status_code=result.status_code,
725
+ data=result.content)
726
+ raise exc_cls(exc_msg)
727
+
728
+ self.ssh_challenge_token = result.headers['x-rucio-ssh-challenge-token']
729
+ self.logger.debug('got new ssh challenge token \'%s\'' % self.ssh_challenge_token)
730
+
731
+ # sign the challenge token with the private key
732
+ with open(private_key_path, 'r') as fd_private_key_path:
733
+ private_key = fd_private_key_path.read()
734
+ signature = ssh_sign(private_key, self.ssh_challenge_token)
735
+ headers['X-Rucio-SSH-Signature'] = signature
736
+
737
+ url = build_url(self.auth_host, path='auth/ssh')
738
+
739
+ result = self._send_request(url, headers=headers, get_token=True)
740
+
741
+ if not result:
742
+ self.logger.error('Cannot retrieve authentication token!')
743
+ return False
744
+
745
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
746
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
747
+ status_code=result.status_code,
748
+ data=result.content)
749
+ raise exc_cls(exc_msg)
750
+
751
+ self.auth_token = result.headers['x-rucio-auth-token']
752
+ return True
753
+
754
+ def __get_token_gss(self):
755
+ """
756
+ Sends a request to get an auth token from the server and stores it as a class attribute. Uses Kerberos authentication.
757
+
758
+ :returns: True if the token was successfully received. False otherwise.
759
+ """
760
+ if not EXTRA_MODULES['requests_kerberos']:
761
+ raise MissingModuleException('The requests-kerberos module is not installed.')
762
+
763
+ url = build_url(self.auth_host, path='auth/gss')
764
+
765
+ result = self._send_request(url, get_token=True, auth=HTTPKerberosAuth())
766
+
767
+ if not result:
768
+ self.logger.error('Cannot retrieve authentication token!')
769
+ return False
770
+
771
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
772
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
773
+ status_code=result.status_code,
774
+ data=result.content)
775
+ raise exc_cls(exc_msg)
776
+
777
+ self.auth_token = result.headers['x-rucio-auth-token']
778
+ return True
779
+
780
+ def __get_token_saml(self):
781
+ """
782
+ Sends a request to get an auth token from the server and stores it as a class attribute. Uses saml authentication.
783
+
784
+ :returns: True if the token was successfully received. False otherwise.
785
+ """
786
+ userpass = {'username': self.creds['username'], 'password': self.creds['password']}
787
+ url = build_url(self.auth_host, path='auth/saml')
788
+
789
+ result = None
790
+ SAML_auth_result = self._send_request(url, get_token=True)
791
+ if SAML_auth_result.headers['X-Rucio-Auth-Token']:
792
+ return SAML_auth_result.headers['X-Rucio-Auth-Token']
793
+ SAML_auth_url = SAML_auth_result.headers['X-Rucio-SAML-Auth-URL']
794
+ result = self._send_request(SAML_auth_url, type_='POST', data=userpass, verify=False)
795
+ result = self._send_request(url, get_token=True)
796
+
797
+ if not result:
798
+ self.logger.error('Cannot retrieve authentication token!')
799
+ return False
800
+
801
+ if result.status_code != codes.ok: # pylint: disable-msg=E1101
802
+ exc_cls, exc_msg = self._get_exception(headers=result.headers,
803
+ status_code=result.status_code,
804
+ data=result.content)
805
+ raise exc_cls(exc_msg)
806
+
807
+ self.auth_token = result.headers['X-Rucio-Auth-Token']
808
+ return True
809
+
810
+ def __get_token(self):
811
+ """
812
+ Calls the corresponding method to receive an auth token depending on the auth type. To be used if a 401 - Unauthorized error is received.
813
+ """
814
+
815
+ self.logger.debug('get a new token')
816
+ for retry in range(self.AUTH_RETRIES + 1):
817
+ if self.auth_type == 'userpass':
818
+ if not self.__get_token_userpass():
819
+ raise CannotAuthenticate('userpass authentication failed for account=%s with identity=%s' % (self.account,
820
+ self.creds['username']))
821
+ elif self.auth_type == 'x509' or self.auth_type == 'x509_proxy':
822
+ if not self.__get_token_x509():
823
+ raise CannotAuthenticate('x509 authentication failed for account=%s with identity=%s' % (self.account,
824
+ self.creds))
825
+ elif self.auth_type == 'oidc':
826
+ if not self.__get_token_OIDC():
827
+ raise CannotAuthenticate('OIDC authentication failed for account=%s' % self.account)
828
+
829
+ elif self.auth_type == 'gss':
830
+ if not self.__get_token_gss():
831
+ raise CannotAuthenticate('kerberos authentication failed for account=%s with identity=%s' % (self.account,
832
+ self.creds))
833
+ elif self.auth_type == 'ssh':
834
+ if not self.__get_token_ssh():
835
+ raise CannotAuthenticate('ssh authentication failed for account=%s with identity=%s' % (self.account,
836
+ self.creds))
837
+ elif self.auth_type == 'saml':
838
+ if not self.__get_token_saml():
839
+ raise CannotAuthenticate('saml authentication failed for account=%s with identity=%s' % (self.account,
840
+ self.creds))
841
+ else:
842
+ raise CannotAuthenticate('auth type \'%s\' not supported' % self.auth_type)
843
+
844
+ if self.auth_token is not None:
845
+ self.__write_token()
846
+ self.headers['X-Rucio-Auth-Token'] = self.auth_token
847
+ break
848
+
849
+ if self.auth_token is None:
850
+ raise CannotAuthenticate('cannot get an auth token from server')
851
+
852
+ def __read_token(self):
853
+ """
854
+ Checks if a local token file exists and reads the token from it.
855
+
856
+ :return: True if a token could be read. False if no file exists.
857
+ """
858
+ if not path.exists(self.token_file):
859
+ return False
860
+
861
+ try:
862
+ token_file_handler = open(self.token_file, 'r')
863
+ self.auth_token = token_file_handler.readline()
864
+ self.headers['X-Rucio-Auth-Token'] = self.auth_token
865
+ except IOError as error:
866
+ print("I/O error({0}): {1}".format(error.errno, error.strerror))
867
+ except Exception:
868
+ raise
869
+ if self.auth_oidc_refresh_active and self.auth_type == 'oidc':
870
+ self.__refresh_token_OIDC()
871
+ self.logger.debug('got token from file')
872
+ return True
873
+
874
+ def __write_token(self):
875
+ """
876
+ Write the current auth_token to the local token file.
877
+ """
878
+ # check if rucio temp directory is there. If not create it with permissions only for the current user
879
+ if not path.isdir(self.token_path):
880
+ try:
881
+ self.logger.debug('rucio token folder \'%s\' not found. Create it.' % self.token_path)
882
+ makedirs(self.token_path, 0o700)
883
+ except Exception:
884
+ raise
885
+
886
+ try:
887
+ file_d, file_n = mkstemp(dir=self.token_path)
888
+ with fdopen(file_d, "w") as f_token:
889
+ f_token.write(self.auth_token)
890
+ move(file_n, self.token_file)
891
+ if self.auth_type == 'oidc' and self.token_exp_epoch and self.auth_oidc_refresh_active:
892
+ file_d, file_n = mkstemp(dir=self.token_path)
893
+ with fdopen(file_d, "w") as f_exp_epoch:
894
+ f_exp_epoch.write(str(self.token_exp_epoch))
895
+ move(file_n, self.token_exp_epoch_file)
896
+ except IOError as error:
897
+ print("I/O error({0}): {1}".format(error.errno, error.strerror))
898
+ except Exception:
899
+ raise
900
+
901
+ def __authenticate(self):
902
+ """
903
+ Main method for authentication. It first tries to read a locally saved token. If not available it requests a new one.
904
+ """
905
+ if self.auth_type == 'userpass':
906
+ if self.creds['username'] is None or self.creds['password'] is None:
907
+ raise NoAuthInformation('No username or password passed')
908
+ elif self.auth_type == 'oidc':
909
+ if self.creds['oidc_auto'] and (self.creds['oidc_username'] is None or self.creds['oidc_password'] is None):
910
+ raise NoAuthInformation('For automatic OIDC log-in with your Identity Provider username and password are required.')
911
+ elif self.auth_type == 'x509':
912
+ if self.creds['client_cert'] is None:
913
+ raise NoAuthInformation('The path to the client certificate is required')
914
+ elif self.auth_type == 'x509_proxy':
915
+ if self.creds['client_proxy'] is None:
916
+ raise NoAuthInformation('The client proxy has to be defined')
917
+ elif self.auth_type == 'ssh':
918
+ if self.creds['ssh_private_key'] is None:
919
+ raise NoAuthInformation('The SSH private key has to be defined')
920
+ elif self.auth_type == 'gss':
921
+ pass
922
+ elif self.auth_type == 'saml':
923
+ if self.creds['username'] is None or self.creds['password'] is None:
924
+ raise NoAuthInformation('No SAML username or password passed')
925
+ else:
926
+ raise CannotAuthenticate('auth type \'%s\' not supported' % self.auth_type)
927
+
928
+ if not self.__read_token():
929
+ self.__get_token()