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