def test_set_voms(self): """ The server must regenerate a proxy with VOMS extensions Need a real proxy for this one """ self.setup_gridsite_environment() creds = self.get_user_credentials() # Need to push a real proxy :/ proxy_pem = self.get_real_x509_proxy() if proxy_pem is None: raise SkipTest('Could not get a valid real proxy for test_set_voms') proxy = Credential() proxy.dn = creds.user_dn proxy.dlg_id = creds.delegation_id proxy.termination_time = datetime.utcnow() + timedelta(hours=1) proxy.proxy = proxy_pem Session.merge(proxy) Session.commit() # Now, request the voms extensions self.app.post(url="/delegation/%s/voms" % creds.delegation_id, content_type='application/json', params=json.dumps(['dteam:/dteam/Role=lcgadmin']), status=203) # And validate proxy2 = Session.query(Credential).get((creds.delegation_id, creds.user_dn)) self.assertNotEqual(proxy.proxy, proxy2.proxy) self.assertEqual('dteam:/dteam/Role=lcgadmin', proxy2.voms_attrs)
def test_refresh_access_token(self): self.oidc_manager.setup(self.config) access_token = self._get_xdc_access_token() refresh_token = self.oidc_manager.generate_refresh_token( self.issuer, access_token) credential = Credential() credential.proxy = ':'.join([access_token, refresh_token]) new_credential = self.oidc_manager.refresh_access_token(credential) self.assertIsNotNone(new_credential.termination_time)
def test_set_voms(self): """ The server must regenerate a proxy with VOMS extensions Need a real proxy for this one """ self.setup_gridsite_environment() creds = self.get_user_credentials() # Need to push a real proxy :/ proxy_pem = self.get_real_x509_proxy() if proxy_pem is None: raise SkipTest( 'Could not get a valid real proxy for test_set_voms') proxy = Credential() proxy.dn = creds.user_dn proxy.dlg_id = creds.delegation_id proxy.termination_time = datetime.utcnow() + timedelta(hours=1) proxy.proxy = proxy_pem Session.merge(proxy) Session.commit() # Now, request the voms extensions self.app.post_json(url="/delegation/%s/voms" % creds.delegation_id, params=['dteam:/dteam/Role=lcgadmin'], status=203) # And validate proxy2 = Session.query(Credential).get( (creds.delegation_id, creds.user_dn)) self.assertNotEqual(proxy.proxy, proxy2.proxy) self.assertEqual('dteam:/dteam/Role=lcgadmin', proxy2.voms_attrs)
def pushDelegation(self, lifetime=timedelta(hours=7)): creds = self.getUserCredentials() delegated = Credential() delegated.dlg_id = creds.delegation_id delegated.dn = creds.user_dn delegated.proxy = '-NOT USED-' delegated.voms_attrs = None delegated.termination_time = datetime.now() + lifetime Session.merge(delegated) Session.commit()
def pushDelegation(self, lifetime = timedelta(hours = 7)): creds = self.getUserCredentials() delegated = Credential() delegated.dlg_id = creds.delegation_id delegated.dn = creds.user_dn delegated.proxy = '-NOT USED-' delegated.voms_attrs = None delegated.termination_time = datetime.now() + lifetime Session.merge(delegated) Session.commit()
def push_delegation(self, lifetime=timedelta(hours=7)): """ Push into the database a mock delegated credential Args: lifetime: The mock credential lifetime """ creds = self.get_user_credentials() delegated = Credential() delegated.dlg_id = creds.delegation_id delegated.dn = creds.user_dn delegated.proxy = '-NOT USED-' delegated.voms_attrs = None delegated.termination_time = datetime.utcnow() + lifetime Session.merge(delegated) Session.commit()
def __init__(self): super(MockedJobController, self).__init__() # Register into paste the fake request and response objects registry = Registry() registry.prepare() registry.register(request, MockRequest()) registry.register(response, MockResponse()) # This is expected to be set by Pylons, so we set it here self._py_object = type( "", (), {"__init__": (lambda s, **kwargs: s.__dict__.update(kwargs))})( request=request, response=response) # Inject fake proxy, so the submission works delegated = Credential(dlg_id='12345', dn='/DN=1234', proxy='', termination_time=datetime.utcnow() + timedelta(hours=5)) Session.merge(delegated) Session.commit()
def credential(self, id, start_response): user = request.environ['fts3.User.Credentials'] credentialCache = Session.query(CredentialCache).get( (id, user.user_dn)) x509ProxyPEM = request.body x509Proxy = X509.load_cert_string(x509ProxyPEM) proxyExpirationTime = x509Proxy.get_not_after().get_datetime().replace( tzinfo=None) x509FullProxyPEM = self._buildFullProxyPEM(x509ProxyPEM, credentialCache.priv_key) credential = Credential(dlg_id=id, dn=user.user_dn, proxy=x509FullProxyPEM, voms_attrs=credentialCache.voms_attrs, termination_time=proxyExpirationTime) Session.merge(credential) Session.commit() start_response('201 CREATED', []) return ''
def _become_root(self): """ Helper function to become root superuser """ self.app.extra_environ.update({ 'GRST_CRED_AURI_0': 'dn:/C=CH/O=CERN/OU=hosts/OU=cern.ch/CN=ftsdummyhost.cern.ch' }) self.app.extra_environ.update({ 'SSL_SERVER_S_DN': '/C=CH/O=CERN/OU=hosts/OU=cern.ch/CN=ftsdummyhost.cern.ch' }) creds = self.get_user_credentials() delegated = Credential() delegated.dlg_id = creds.delegation_id delegated.dn = '/C=CH/O=CERN/OU=hosts/OU=cern.ch/CN=ftsdummyhost.cern.ch' delegated.proxy = '-NOT USED-' delegated.voms_attrs = None delegated.termination_time = datetime.utcnow() + timedelta(hours=7) Session.merge(delegated) Session.commit()
class DelegationController(BaseController): """ Operations to perform the delegation of credentials """ def __init__(self): """ Constructor """ M2Crypto.threading.init() vomses_dir = '/etc/vomses' vo_set = set() try: vomses = os.listdir(vomses_dir) for voms in vomses: voms_cfg = os.path.join(vomses_dir, voms) lines = filter( lambda l: len(l) and l[0] != '#', map(str.strip, open(voms_cfg).readlines()) ) for l in lines: vo_set.add(shlex.split(l)[0]) self.vo_list = list(sorted(vo_set)) except: pass @require_certificate def certificate(self): """ Returns the user certificate """ response.headers['Content-Type'] = 'application/x-pem-file' n = 0 full_cert = '' cert = request.environ.get('SSL_CLIENT_CERT', None) while cert: full_cert += cert cert = request.environ.get('SSL_CLIENT_CERT_CHAIN_%d' % n, None) n += 1 if len(full_cert) > 0: return full_cert else: return None @jsonify def whoami(self): """ Returns the active credentials of the user """ whoami = request.environ['fts3.User.Credentials'] whoami.base_id = str(get_base_id()) for vo in whoami.vos: whoami.vos_id.append(str(get_vo_id(vo))) return whoami @doc.return_type('dateTime') @jsonify def view(self, dlg_id, start_response): """ Get the termination time of the current delegated credential, if any """ user = request.environ['fts3.User.Credentials'] if dlg_id != user.delegation_id: raise HTTPForbidden('The requested ID and the credentials ID do not match') cred = Session.query(Credential).get((user.delegation_id, user.user_dn)) if not cred: return None else: return { 'termination_time': cred.termination_time, 'voms_attrs': cred.voms_attrs.split('\n') } @doc.response(403, 'The requested delegation ID does not belong to the user') @doc.response(404, 'The credentials do not exist') @doc.response(204, 'The credentials were deleted successfully') @require_certificate def delete(self, dlg_id, start_response): """ Delete the delegated credentials from the database """ user = request.environ['fts3.User.Credentials'] if dlg_id != user.delegation_id: raise HTTPForbidden('The requested ID and the credentials ID do not match') cred = Session.query(Credential).get((user.delegation_id, user.user_dn)) if not cred: raise HTTPNotFound('Delegated credentials not found') else: try: Session.delete(cred) Session.commit() except Exception: Session.rollback() raise start_response('204 No Content', []) return [''] @doc.response(403, 'The requested delegation ID does not belong to the user') @doc.response(200, 'The request was generated succesfully') @doc.return_type('PEM encoded certificate request') @require_certificate def request(self, dlg_id, start_response): """ First step of the delegation process: get a certificate request The returned certificate request must be signed with the user's original credentials. """ user = request.environ['fts3.User.Credentials'] if dlg_id != user.delegation_id: raise HTTPForbidden('The requested ID and the credentials ID do not match') credential_cache = Session.query(CredentialCache)\ .get((user.delegation_id, user.user_dn)) if credential_cache is None or credential_cache.cert_request is None: (x509_request, private_key) = _generate_proxy_request() credential_cache = CredentialCache(dlg_id=user.delegation_id, dn=user.user_dn, cert_request=x509_request.as_pem(), priv_key=private_key.as_pem(cipher=None), voms_attrs=' '.join(user.voms_cred)) try: Session.merge(credential_cache) Session.commit() except Exception: Session.rollback() raise log.debug("Generated new credential request for %s" % dlg_id) else: log.debug("Using cached request for %s" % dlg_id) start_response('200 Ok', [('X-Delegation-ID', str(credential_cache.dlg_id)), ('Content-Type', 'text/plain')]) return [credential_cache.cert_request] @doc.input('Signed certificate', 'PEM encoded certificate') @doc.response(403, 'The requested delegation ID does not belong to the user') @doc.response(400, 'The proxy failed the validation process') @doc.response(201, 'The proxy was stored successfully') @require_certificate def credential(self, dlg_id, start_response): """ Second step of the delegation process: put the generated certificate The certificate being PUT will have to pass the following validation: - There is a previous certificate request done - The certificate subject matches the certificate issuer + '/CN=Proxy' - The certificate modulus matches the stored private key modulus """ user = request.environ['fts3.User.Credentials'] if dlg_id != user.delegation_id: raise HTTPForbidden('The requested ID and the credentials ID do not match') credential_cache = Session.query(CredentialCache)\ .get((user.delegation_id, user.user_dn)) if credential_cache is None: raise HTTPBadRequest('No credential cache found') x509_proxy_pem = request.body log.debug("Received delegated credentials for %s" % dlg_id) log.debug(x509_proxy_pem) try: expiration_time = _validate_proxy(x509_proxy_pem, credential_cache.priv_key) x509_full_proxy_pem = _build_full_proxy(x509_proxy_pem, credential_cache.priv_key) except ProxyException, e: raise HTTPBadRequest('Could not process the proxy: ' + str(e)) credential = Credential(dlg_id = user.delegation_id, dn = user.user_dn, proxy = x509_full_proxy_pem, voms_attrs = credential_cache.voms_attrs, termination_time = expiration_time) try: Session.merge(credential) Session.commit() except Exception: Session.rollback() raise start_response('201 Created', []) return ['']