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