def __init__(self):
        """
        Get plugins for use in other class methods.

        Set unique keys.
        """
        super(OMemberAuthorityResourceManager, self).__init__()
        self._resource_manager_tools = pm.getService('resourcemanagertools')
        self._set_unique_keys()
        #<UT>
        config = pm.getService("config")
        cert_path = expand_amsoil_path(config.get("delegatetools.trusted_cert_path"))
        cert_key_path = expand_amsoil_path(config.get("delegatetools.trusted_cert_keys_path"))
        hostname = config.get('flask.cbas_hostname')
        self._ma_crl_path = expand_amsoil_path(config.get("delegatetools.trusted_crl_path")) + '/' \
                                                    + hostname + '.authority.ma'
        self._ma_cert_str = self._resource_manager_tools.read_file(cert_path + '/' +
                                                            OMemberAuthorityResourceManager.MA_CERT_FILE)
        self._ma_cert_key_str = self._resource_manager_tools.read_file(cert_key_path + '/' +
                                                             OMemberAuthorityResourceManager.MA_KEY_FILE)

        self.gfed_ex = pm.getService('apiexceptionsv2')
        self._urn = self.urn()

        self._cert_revoke_reasons = crypto.Revoked().all_reasons()
        self._ma_cert = crypto.load_certificate(crypto.FILETYPE_PEM, self._ma_cert_str)
        self._ma_cert_key = crypto.load_privatekey(crypto.FILETYPE_PEM, self._ma_cert_key_str)
Exemplo n.º 2
0
def convert_project_urn_to_uid(project_urn, session):
    db = pm.getService('chdbengine')
    config = pm.getService('config')
    authority = config.get("chrm.authority")

    project_urns = project_urn
    if not isinstance(project_urn, list): project_urns = [project_urn]

    if len(project_urns) == 0:
        return []


    cache = cache_get('project_urn_to_uid')
    uncached_urns = [id for id in project_urns if id not in cache]

    if len(uncached_urns) > 0:
        uncached_names = [from_project_urn(urn) for urn in uncached_urns]
        q = session.query(db.PROJECT_TABLE.c.project_name, \
                              db.PROJECT_TABLE.c.project_id)
        q = q.filter(db.PROJECT_TABLE.c.project_name.in_(uncached_names))
        rows = q.all()
        for row in rows:
            project_id = row.project_id
            project_name = row.project_name
            project_urn = to_project_urn(authority, project_name)
            cache[project_urn] = project_id

    if not isinstance(project_urn, list):
        if project_urn in cache:
            return cache[project_urn]
        else:
            raise CHAPIv1ArgumentError("Unknown project urn: %s " % \
                                           project_urn)
    else:
        return validate_uid_list(project_urns, cache, 'project')
Exemplo n.º 3
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Set unique keys.
        """
        super(OSliceAuthorityResourceManager, self).__init__()
        self._resource_manager_tools = pm.getService('resourcemanagertools')
        self._set_unique_keys()

        #<UT>
        config = pm.getService("config")
        cert_path = expand_amsoil_path(
            config.get("delegatetools.trusted_cert_path"))
        cert_key_path = expand_amsoil_path(
            config.get("delegatetools.trusted_cert_keys_path"))

        self._sa_c = self._resource_manager_tools.read_file(
            cert_path + '/' + OSliceAuthorityResourceManager.SA_CERT_FILE)
        self._sa_pr = self._resource_manager_tools.read_file(
            cert_key_path + '/' + OSliceAuthorityResourceManager.SA_KEY_FILE)

        #<UT>
        self._delegate_tools = pm.getService('delegatetools')
        self.gfed_ex = pm.getService('apiexceptionsv2')
Exemplo n.º 4
0
def setup():

    xmlrpc = pm.getService('xmlrpc')
    api_tools = pm.getService('apitools')

    greg_handler = GRegistryv2Handler()
    pm.registerService('gregistryv2handler', greg_handler)
    pm.registerService('gregistryv2delegatebase', GRegistryv2DelegateBase)
    xmlrpc.registerXMLRPC('gregv2', greg_handler,
                          '/reg/2')  # name, handlerObj, endpoint
    api_tools.register_endpoint(name='gregv2',
                                type='reg',
                                version='2',
                                url='/reg/2')

    gma_handler = GMAv2Handler()
    pm.registerService('gmav2handler', gma_handler)
    pm.registerService('gmav2delegatebase', GMAv2DelegateBase)
    xmlrpc.registerXMLRPC('gmav2', gma_handler,
                          '/ma/2')  # name, handlerObj, endpoint
    api_tools.register_endpoint(name='gmav2',
                                type='ma',
                                version='2',
                                url='/ma/2')

    gsa_handler = GSAv2Handler()
    pm.registerService('gsav2handler', gsa_handler)
    pm.registerService('gsav2delegatebase', GSAv2DelegateBase)
    xmlrpc.registerXMLRPC('gsav2', gsa_handler,
                          '/sa/2')  # name, handlerObj, endpoint
    api_tools.register_endpoint(name='gsav2',
                                type='sa',
                                version='2',
                                url='/sa/2')
Exemplo n.º 5
0
def setup():

   # set up config keys                                                        
   config = pm.getService('config')

   # register xmlrpc endpoint                                                  
   xmlrpc = pm.getService('xmlrpc')

   pgch_handler = PGCHv1Handler()
   pgch_delegate = PGCHv1Delegate()
   pgch_handler.setDelegate(pgch_delegate)

   pgch_handler2 = PGCHv1Handler()
   pgch_delegate2 = PGCHv1Delegate()
   pgch_handler2.setDelegate(pgch_delegate2)

   pgch_handler3 = PGCHv1Handler()
   pgch_delegate3 = PGCHv1Delegate()
   pgch_handler3.setDelegate(pgch_delegate3)

   pm.registerService('pgchv1handler', pgch_handler)

   # name, handler, endpoint                                                   
   xmlrpc.registerXMLRPC('pgch2v1', pgch_handler2, '/PGCH')
   xmlrpc.registerXMLRPC('pgch3v1', pgch_handler3, '/PGCH/ch')
   xmlrpc.registerXMLRPC('pgchv1', pgch_handler, '/')
Exemplo n.º 6
0
def setup():
    # setup config keys
    config = pm.getService("config")
    config.install("opennaas.db_dir", "/opt/amsoil", "(Sqlite) database directory")
    config.install("opennaas.db_dump_stat", False, "(Sqlite) database dump statements")
    config.install("opennaas.reservation_timeout", 600, "Reservation timeout (minutes)")
    config.install("opennaas.server_address", "localhost", "OpenNaas server address")
    config.install("opennaas.server_port", 8888, "OpenNaas server port")
    config.install("opennaas.user", "admin", "OpenNaas user")
    config.install("opennaas.password", "123456", "OpenNaas password")
    config.install("opennaas.update_timeout", 5, "Update resources timeout (secs)")
    config.install("opennaas.update_step", 100, "Update resources step")
    config.install("opennaas.check_expire_timeout", 60, "Check resources expiration timeout (secs)")
    config.install("opennaas.check_credentials", False, "Check credentials for incoming requests")

    # resource manager
    import resourceexceptions as ons_exceptions_package
    pm.registerService('opennaas_exceptions', ons_exceptions_package)
    import models as ons_models_package
    pm.registerService('opennaas_models', ons_models_package)
    import commandsmanager as ons_commands_mngr_package
    pm.registerService('opennaas_commands', ons_commands_mngr_package)
    import fsmmanager as ons_fsm_mngr_package
    pm.registerService('opennaas_fsm', ons_fsm_mngr_package)
    from resourcemanager import RMRoadmManager
    pm.registerService('opennaas_resourcemanager', RMRoadmManager())

    # delegate
    from geni3delegate import OpenNaasGENI3Delegate
    handler = pm.getService('geniv3handler')
    handler.setDelegate(OpenNaasGENI3Delegate())
Exemplo n.º 7
0
 def __init__(self):
     GuardBase.__init__(self)
     self.db = pm.getService('chdbengine')
     self.config = pm.getService('config')
     self.key_file = self.config.get("chapiv1rpc.ch_key")
     self.cert_file = self.config.get("chapiv1rpc.ch_cert")
     self.authority = self.config.get("chrm.authority")
Exemplo n.º 8
0
 def __init__(self):
     GuardBase.__init__(self)
     self.db = pm.getService('chdbengine')
     self.config = pm.getService('config')
     self.key_file = self.config.get("chapiv1rpc.ch_key")
     self.cert_file = self.config.get("chapiv1rpc.ch_cert")
     self.authority = self.config.get("chrm.authority")
Exemplo n.º 9
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Set unique keys.
        """
        super(OMemberAuthorityResourceManager, self).__init__()
        self._resource_manager_tools = pm.getService('resourcemanagertools')
        self._set_unique_keys()
        #<UT>
        config = pm.getService("config")
        cert_path = expand_amsoil_path(
            config.get("delegatetools.trusted_cert_path"))
        cert_key_path = expand_amsoil_path(
            config.get("delegatetools.trusted_cert_keys_path"))
        hostname = config.get('flask.cbas_hostname')
        self._ma_crl_path = expand_amsoil_path(config.get("delegatetools.trusted_crl_path")) + '/' \
                                                    + hostname + '.authority.ma'
        self._ma_cert_str = self._resource_manager_tools.read_file(
            cert_path + '/' + OMemberAuthorityResourceManager.MA_CERT_FILE)
        self._ma_cert_key_str = self._resource_manager_tools.read_file(
            cert_key_path + '/' + OMemberAuthorityResourceManager.MA_KEY_FILE)

        self.gfed_ex = pm.getService('apiexceptionsv2')
        self._urn = self.urn()

        self._cert_revoke_reasons = crypto.Revoked().all_reasons()
        self._ma_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                self._ma_cert_str)
        self._ma_cert_key = crypto.load_privatekey(crypto.FILETYPE_PEM,
                                                   self._ma_cert_key_str)
Exemplo n.º 10
0
def setup():
    pm.registerService('gfedv1exceptions', gfed_exceptions)

    xmlrpc = pm.getService('xmlrpc')
    _api_tools = pm.getService('apitools')

    greg_handler = GRegistryv1Handler()
    pm.registerService('gregistryv1handler', greg_handler)
    pm.registerService('gregistryv1delegatebase', GRegistryv1DelegateBase)
    xmlrpc.registerXMLRPC('greg', greg_handler,
                          '/reg/1')  # name, handlerObj, endpoint
    _api_tools.register_endpoint(name='gregv1',
                                 type='reg',
                                 version='1',
                                 url='/reg/1')

    gma_handler = GMAv1Handler()
    pm.registerService('gmav1handler', gma_handler)
    pm.registerService('gmav1delegatebase', GMAv1DelegateBase)
    xmlrpc.registerXMLRPC('gma', gma_handler,
                          '/ma/1')  # name, handlerObj, endpoint
    _api_tools.register_endpoint(name='gmav1',
                                 type='ma',
                                 version='1',
                                 url='/ma/1')

    gsa_handler = GSAv1Handler()
    pm.registerService('gsav1handler', gsa_handler)
    pm.registerService('gsav1delegatebase', GSAv1DelegateBase)
    xmlrpc.registerXMLRPC('gsav1', gsa_handler,
                          '/sa/1')  # name, handlerObj, endpoint
    _api_tools.register_endpoint(name='gsav1',
                                 type='sa',
                                 version='1',
                                 url='/sa/1')
Exemplo n.º 11
0
def convert_project_urn_to_uid(project_urn, session):
    db = pm.getService('chdbengine')
    sa = pm.getService('sav1handler')
    authority = sa.getDelegate().authority

    project_urns = project_urn
    if not isinstance(project_urn, list): project_urns = [project_urn]

    if len(project_urns) == 0:
        return []


    cache = cache_get('project_urn_to_uid')
    uncached_urns = [id for id in project_urns if id not in cache]

    if len(uncached_urns) > 0:
        uncached_names = [from_project_urn(urn) for urn in uncached_urns]
        q = session.query(db.PROJECT_TABLE.c.project_name, \
                              db.PROJECT_TABLE.c.project_id)
        q = q.filter(db.PROJECT_TABLE.c.project_name.in_(uncached_names))
        rows = q.all()
        for row in rows:
            project_id = row.project_id
            project_name = row.project_name
            project_urn = to_project_urn(authority, project_name)
            cache[project_urn] = project_id

    if not isinstance(project_urn, list):
        if project_urn in cache:
            return cache[project_urn]
        else:
            raise CHAPIv1ArgumentError("Unknown project urn: %s " % \
                                           project_urn)
    else:
        return validate_uid_list(project_urns, cache, 'project')
Exemplo n.º 12
0
def convert_project_uid_to_urn(project_uid, session):
    db = pm.getService('chdbengine')
    sa = pm.getService('sav1handler')
    authority = sa.getDelegate().authority

    project_uids = project_uid
    if not isinstance(project_uid, list): project_uids = [project_uid]

    if len(project_uids) == 0:
        return []


    cache = cache_get('project_uid_to_urn')
    uncached_uids = [id for id in project_uids if id not in cache]

    if len(uncached_uids) > 0:
        q = session.query(db.PROJECT_TABLE.c.project_name, \
                              db.PROJECT_TABLE.c.project_id)
        q = q.filter(db.PROJECT_TABLE.c.project_id.in_(uncached_uids))
        rows = q.all()
        for row in rows:
            project_id = row.project_id
            project_name = row.project_name
            project_urn = to_project_urn(authority, project_name)
            cache[project_id] = project_urn

    if not isinstance(project_uid, list):
        if project_uid in cache:
            return cache[project_uid]
        else:
            raise CHAPIv1ArgumentError("Unknown project uid: %s " % \
                                           project_uid)
    else:
        return validate_uid_list(project_uids, cache, 'project')
Exemplo n.º 13
0
    def verify_project_credentials_context(self, credentials, certificate, method, fields=None, target_urn=None):
        """
        Verify project to slice relationship
        :param credentials: credential string in SFA format
        :param method: Name of the method e.g., CREATE, UPDATE, LOOKUP, DELETE, CHANGE_ROLE etc.
        """

        geniutil = pm.getService('geniutil')
        slice_authority_resource_manager = pm.getService('osliceauthorityrm')
        _, target_urn_from_cred = geniutil.get_privileges_and_target_urn(credentials)
        verification_passed = True

        if method == 'CREATE':
            if not fields['SLICE_PROJECT_URN'] == target_urn_from_cred:
                verification_passed = False
        elif method == 'UPDATE':
            lookup_result = slice_authority_resource_manager.lookup_slice(certificate, credentials,
                                                                        {'SLICE_URN': str(target_urn)}, [], {})
            if not lookup_result or not lookup_result[0]['SLICE_PROJECT_URN'] == target_urn_from_cred:
                    verification_passed = False
        elif method == 'LOOKUP':
            pass
        elif method == 'DELETE':
            pass

        if not verification_passed:
            raise GFedv2AuthorizationError("Your project credentials do not provide enough privileges to execute "+ method + " call on slice object")
Exemplo n.º 14
0
def register_user(first_name, last_name, user_name, user_email, public_key=None):
    """
    Register user by creating public ssh Keys and credentials

    Args:
        first_name: The first name of the user which will be included in the URN
        last_name: The last name of the user which will be included in the URN
        username: A name that might be used to reference a certail user
        email : The User Email
        public_key: An optional field, allows a user-generated public key

    Return:
        User generated data such as keys, credentials, etc.
    """

    geniutil = pm.getService('geniutil')
    resource_manager_tools = pm.getService('resourcemanagertools')
    urn = geniutil.encode_urn(AUTHORITY, 'user', str(user_name))
    lookup_result = resource_manager_tools.object_lookup(AUTHORITY_NAME, 'key', {'KEY_MEMBER' : urn}, [])

    if public_key:
        if not lookup_result:

        # Generating The Credentials (TO-DO | Solve Problems with geni_utils)
            ma_c = read_file(KEY_PATH + MA_CERT_FILE)
            ma_pr = read_file(KEY_PATH + MA_KEY_FILE)
            u_c,u_pu,u_pr = geniutil.create_certificate(urn, issuer_key=ma_pr, issuer_cert=ma_c,
                                                        email=str(user_email))
            user_cred = geniutil.create_credential(u_c, u_c, ma_pr, ma_c, "user", CRED_EXPIRY)

        # Receiving public key and saving it in the Member Authority Data-base
            resource_manager_tools = pm.getService('resourcemanagertools')
            ssh_public_key = public_key
            registration_fields_member = dict( MEMBER_URN = urn,
                                       MEMBER_FIRSTNAME = first_name,
                                       MEMBER_LASTNAME 	= last_name,
                                       MEMBER_USERNAME =  user_name ,
                                       MEMBER_EMAIL =user_email)

            registration_fields_key = dict(KEY_MEMBER= urn,
                                       KEY_TYPE = 'rsa-ssh',
                                       KEY_DESCRIPTION='SSH key for user ' + user_name,
                                       KEY_PUBLIC= ssh_public_key,
                                       KEY_ID= hashlib.sha224(ssh_public_key).hexdigest())


            registration_fields_credentials = dict(CREDENTIAL_MEMBER = urn,
                                                   CREDENTIAL_DESCRIPTION = 'Credentials for' + urn,
                                                   CREDENTIAL_VALUE = user_cred)

            resource_manager_tools.object_create(AUTHORITY_NAME, registration_fields_key, 'key')
            resource_manager_tools.object_create(AUTHORITY_NAME, registration_fields_member, 'member')
            resource_manager_tools.object_create(AUTHORITY_NAME, registration_fields_credentials, 'member')

            return registration_fields_member, registration_fields_key, registration_fields_credentials
        else:
            return "User already registerd, try looking up the user with its URN instead !!"

    return "Public key missing, please provide you public key"
Exemplo n.º 15
0
 def __init__(self):
     """
     Get plugins for use in other class methods.
     """
     super(ORegistryResourceManager, self).__init__()
     self._resource_manager_tools = pm.getService('resourcemanagertools')
     #TODO: this isn't a a delegate!
     self._delegate_tools = pm.getService('delegatetools')
Exemplo n.º 16
0
def setup():
    # setup config keys
    # config = pm.getService("config")

    xmlrpc = pm.getService('xmlrpc')
    handler = pm.getService('geniv3handler')
    xmlrpc.registerXMLRPC('tn_rm_geni_v3', handler, '/xmlrpc/geni/3/')
    delegate = TNRMGENI3Delegate()
    handler.setDelegate(delegate)
Exemplo n.º 17
0
def setup():
    # setup config keys
    # config = pm.getService("config")

    xmlrpc = pm.getService('xmlrpc')
    handler = pm.getService('geniv3handler')
    xmlrpc.registerXMLRPC('tn_rm_geni_v3', handler, '/xmlrpc/geni/3/')
    delegate = TNRMGENI3Delegate()
    handler.setDelegate(delegate)
    def create_slice(self, client_cert, credentials, fields, options):
        """
        Create a slice object.

        Generate fields for a new object:
            * SLICE_URN: retrieve the hostname from the Flask AMsoil plugin
                and form into a valid URN
            * SLICE_UID: generate a new UUID4 value
            * SLICE_CREATION: get the time now and convert it into RFC3339 form
            * SLICE_EXPIRED: slice object has just been created, so it is has not
                yet expired
        """

        self._resource_manager_tools.validate_credentials(credentials)
        geniutil = pm.getService('geniutil')

        #<UT> Shall we enforce existence of project to which this new slice would belong?
        #The information about project is sent in fields under SLICE_PROJECT_URN key
        config = pm.getService('config')
        hostname = config.get('flask.cbas_hostname')

        slice_urn = geniutil.encode_urn(hostname, 'slice', str(fields.get('SLICE_NAME')))
        fields['SLICE_URN'] =  slice_urn
        fields['SLICE_UID'] = str(uuid.uuid4())
        fields['SLICE_CREATION'] = pyrfc3339.generate(datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
        fields['SLICE_EXPIRED'] = False

        #Generating Slice certificate
        s_cert, s_pu, s_pr = geniutil.create_certificate(slice_urn, self._sa_pr, self._sa_c)
        fields['SLICE_CERTIFICATE'] = s_cert

        #Try to get the user credentials for use as owner
        user_cert = geniutil.extract_owner_certificate(credentials)

        #Extract user info from his certificate
        user_urn, user_uuid, user_email = geniutil.extract_certificate_info(user_cert)
        #Get the privileges user would get as owner in the slice credential
        user_pri = self._delegate_tools.get_default_privilege_list(role_='LEAD', context_='SLICE')
        #Create slice cred for owner
        slice_cred = geniutil.create_credential_ex(owner_cert=user_cert, target_cert=s_cert, issuer_key=self._sa_pr,
                                                   issuer_cert=self._sa_c, privileges_list=user_pri, expiration=self.CRED_EXPIRY)

        #Let's make the owner as LEAD
        fields['SLICE_LEAD'] = user_urn

        #Finally, create slice object
        ret_values = self._resource_manager_tools.object_create(self.AUTHORITY_NAME, fields, 'slice')

        #Add slice credentials to the return values
        ret_values['SLICE_CREDENTIALS'] = slice_cred

        #Create SLICE_MEMBER object
        options = {'members_to_add' : [{'SLICE_MEMBER' : user_urn, 'SLICE_CREDENTIALS': slice_cred, 'SLICE_CERTIFICATE': s_cert, 'SLICE_ROLE': 'LEAD'}]}
        self._resource_manager_tools.member_modify(self.AUTHORITY_NAME, 'slice_member', slice_urn, options, 'SLICE_MEMBER', 'SLICE_URN')

        return ret_values
Exemplo n.º 19
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Retrieve whitelists for use in validity checking.
        """
        self._member_authority_resource_manager = pm.getService('omemberauthorityrm')
        self._delegate_tools = pm.getService('delegatetools')
        self._member_whitelist = self._delegate_tools.get_whitelist('MEMBER')
        self._key_whitelist = self._delegate_tools.get_whitelist('KEY')
Exemplo n.º 20
0
 def __init__(self):
     # Capture singleton instance
     OpsMonHandler._instance = self
     config = pm.getService('config')
     authority = config.get('chrm.authority')
     self._base_url = "https://%s" % authority
     self._authority = authority
     self._authority_urn = generate_urn(authority, 'authority', 'ch')
     self._authority_href = self.generate_href('authority', authority)
     self._db = pm.getService('chdbengine')
Exemplo n.º 21
0
 def __init__(self):
     # Capture singleton instance
     OpsMonHandler._instance = self
     config = pm.getService('config')
     authority = config.get('chrm.authority')
     self._base_url = "https://%s" % authority
     self._authority = authority
     self._authority_urn = generate_urn(authority, 'authority', 'ch')
     self._authority_href = self.generate_href('authority', authority)
     self._db = pm.getService('chdbengine')
Exemplo n.º 22
0
    def create_slice(self, client_cert, credentials, fields, options):
        """
        Create a slice object.

        Generate fields for a new object:
            * SLICE_URN: retrieve the hostname from the Flask AMsoil plugin
                and form into a valid URN
            * SLICE_UID: generate a new UUID4 value
            * SLICE_CREATION: get the time now and convert it into RFC3339 form
            * SLICE_EXPIRED: slice object has just been created, so it is has not
                yet expired
        """

        u_c = None
        #credentials_testing = credentials #self._resource_manager_tools.read_file(OSliceAuthorityResourceManager.KEY_PATH + "credentials_test")
        root = ET.fromstring(
            credentials[0]['SFA']
        )  #FIXME: short-term solution to fix string handling, take first credential of SFA format

        #print '-->'
        #print credentials
        #print '<--'

        self._resource_manager_tools.validate_credentials(credentials)
        config = pm.getService('config')
        geniutil = pm.getService('geniutil')
        hostname = config.get('flask.hostname')

        fields['SLICE_URN'] = geniutil.encode_urn(
            OSliceAuthorityResourceManager.AUTHORITY_NAME, 'slice',
            str(fields.get('SLICE_NAME')))
        fields['SLICE_UID'] = str(uuid.uuid4())
        fields['SLICE_CREATION'] = pyrfc3339.generate(
            datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
        fields['SLICE_EXPIRED'] = False

        #Generating Slice Credentials
        s_c, s_pu, s_pr = geniutil.create_certificate(fields['SLICE_URN'],
                                                      self._sa_pr, self._sa_c)

        #default owner is slice itself
        u_c = s_c

        #Try to get the user credentials for use as owner
        for child in root:
            if child.tag == 'credential':
                u_c = child[2].text
                break

        fields['SLICE_CREDENTIALS'] = geniutil.create_credential(
            u_c, s_c, self._sa_pr, self._sa_c, "slice",
            OSliceAuthorityResourceManager.CRED_EXPIRY)

        return self._resource_manager_tools.object_create(
            self.AUTHORITY_NAME, fields, 'slice')
Exemplo n.º 23
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Checks consistency of 'SERVICES' fields defined in configuration
        (config.json).
        """
        self._federation_registry_resource_manager = pm.getService('oregistryrm')
        self._delegate_tools = pm.getService('delegatetools')
        for service in self._delegate_tools.get_registry()['SERVICES']:
            self._delegate_tools.object_consistency_check('SERVICE', service)
Exemplo n.º 24
0
def setup():
    config = pm.getService('config')
    config.install("ofed.cert_root", "deploy/trusted", "Folder which includes trusted certificates (in .pem format). If relative path, the root is assumed to be git repo root.")
    
    reg_delegate = ORegistryv1Delegate()
    reg_handler = pm.getService('gregistryv1handler')
    reg_handler.setDelegate(reg_delegate)

    ma_delegate = OMAv1DelegateGuard()
    ma_handler = pm.getService('gmav1handler')
    ma_handler.setDelegate(ma_delegate)
Exemplo n.º 25
0
def setup():

    config = pm.getService('config')

    delegate = MAv1Implementation()

    guard = MAv1Guard()

    handler = pm.getService('mav1handler')
    handler.setDelegate(delegate)
    handler.setGuard(guard)
Exemplo n.º 26
0
def setup():

    config = pm.getService('config')

    delegate = MAv1Implementation()

    guard = MAv1Guard()

    handler = pm.getService('mav1handler')
    handler.setDelegate(delegate)
    handler.setGuard(guard)
Exemplo n.º 27
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Retrieve whitelists for use in validity checking.
        """
        self._member_authority_resource_manager = pm.getService(
            'omemberauthorityrm')
        self._delegate_tools = pm.getService('delegatetools')
        self._member_whitelist = self._delegate_tools.get_whitelist('MEMBER')
        self._key_whitelist = self._delegate_tools.get_whitelist('KEY')
    def create_project(self, client_cert, credentials, fields, options):
        """
        Create a project object.

        Generate fields for a new object:
            * PROJECT_URN: retrieve the hostname from the Flask AMsoil plugin
                and form into a valid URN
            * PROJECT_UID: generate a new UUID4 value
            * PROJECT_CREATION: get the time now and convert it into RFC3339 form
            * PROJECT_EXPIRED: project object has just been created, so it is
                has not yet expired

        """
        config = pm.getService('config')
        hostname = config.get('flask.cbas_hostname')
        p_urn = 'urn:publicid:IDN+' + hostname + '+project+' + fields.get('PROJECT_NAME')

        fields['PROJECT_URN'] = p_urn
        fields['PROJECT_UID'] = str(uuid.uuid4())
        fields['PROJECT_CREATION'] = pyrfc3339.generate(datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
        fields['PROJECT_EXPIRED'] = False


        #<UT>
        geniutil = pm.getService('geniutil')
        #Generating Project Certificate
        p_cert, p_pu, p_pr = geniutil.create_certificate(p_urn, self._sa_pr, self._sa_c)
        fields['PROJECT_CERTIFICATE'] = p_cert

        #Try to get the user credentials for use as owner
        user_cert = geniutil.extract_owner_certificate(credentials)

        #Extract user info from his certificate
        user_urn, user_uuid, user_email = geniutil.extract_certificate_info(user_cert)
        #Get the privileges user would get as owner in the project credential
        user_pri = self._delegate_tools.get_default_privilege_list(role_='LEAD', context_='PROJECT')
        #Create project cred for owner
        p_creds = geniutil.create_credential_ex(owner_cert=user_cert, target_cert=p_cert, issuer_key=self._sa_pr, issuer_cert=self._sa_c, privileges_list=user_pri,
                                                    expiration=OSliceAuthorityResourceManager.CRED_EXPIRY)

        #Let's make the owner as LEAD
        fields['PROJECT_LEAD'] = user_urn

        #Finally, create project object
        ret_values = self._resource_manager_tools.object_create(self.AUTHORITY_NAME, fields, 'project')
        #Add Project credentials to ret values
        ret_values['PROJECT_CREDENTIALS'] = p_creds

        #Create PROJECT_MEMBER object
        options = {'members_to_add' : [{'PROJECT_MEMBER': user_urn, 'PROJECT_CREDENTIALS': p_creds, 'PROJECT_ROLE': 'LEAD'}]}
        self._resource_manager_tools.member_modify(self.AUTHORITY_NAME, 'project_member', p_urn, options, 'PROJECT_MEMBER', 'PROJECT_URN')

        return ret_values
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Checks consistency of 'SERVICES' fields defined in configuration
        (config.json).
        """
        self._federation_registry_resource_manager = pm.getService(
            'oregistryrm')
        self._delegate_tools = pm.getService('delegatetools')
        for service in self._delegate_tools.get_registry()['SERVICES']:
            self._delegate_tools.object_consistency_check('SERVICE', service)
Exemplo n.º 30
0
    def api_versions(self):
        """
        Get the different endpoints (of type 'ma'), registered with AMsoil.

        Form these endpoints into a dictionary suitable for the API call response.

        """
        config = pm.getService('config')
        hostname = config.get('flask.hostname')
        port = str(config.get('flask.app_port'))
        endpoints = pm.getService('apitools').get_endpoints(type=self.AUTHORITY_NAME)
        return self._resource_manager_tools.form_api_versions(hostname, port, endpoints)
Exemplo n.º 31
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Retrieve whitelists for use in validity checking.
        """
        self._slice_authority_resource_manager = pm.getService('osliceauthorityrm')
        self._delegate_tools = pm.getService('delegatetools')
        self._api_tools = pm.getService('apitools')
        self._slice_whitelist = self._delegate_tools.get_whitelist('SLICE')
        self._sliver_info_whitelist = self._delegate_tools.get_whitelist('SLIVER_INFO')
        self._project_whitelist = self._delegate_tools.get_whitelist('PROJECT')
    def api_versions(self):
        """
        Get the different endpoints (of type 'ma'), registered with AMsoil.

        Form these endpoints into a dictionary suitable for the API call response.

        """
        config = pm.getService('config')
        hostname = config.get('flask.hostname')
        port = str(config.get('flask.app_port'))
        endpoints = pm.getService('apitools').get_endpoints(type=self.AUTHORITY_NAME)
        return self._resource_manager_tools.form_api_versions(hostname, port, endpoints)
Exemplo n.º 33
0
def setup():
    # setup config keys
    config = pm.getService("config")
    config.install("geniv3rpc.cert_root", "deploy/trusted", "Folder which includes trusted clearinghouse certificates for GENI API v3 (in .pem format). If relative path, the root is assumed to be git repo root.")
    config.install("geniv3rpc.rspec_validation", True, "Determines if RSpec shall be validated by the given xs:schemaLocations in the document (may cause downloads of the given schema from the given URL per request).")
    
    # register xmlrpc endpoint
    xmlrpc = pm.getService('xmlrpc')
    geni_handler = GENIv3Handler()
    pm.registerService('geniv3handler', geni_handler)
    pm.registerService('geniv3delegatebase', GENIv3DelegateBase)
    pm.registerService('geniv3exceptions', geni_exceptions)
    xmlrpc.registerXMLRPC('geni3', geni_handler, '/RPC2') # name, handlerObj, endpoint
Exemplo n.º 34
0
def setup():
    config = pm.getService('config')
    config.install(
        "ofed.cert_root", "deploy/trusted",
        "Folder which includes trusted certificates (in .pem format). If relative path, the root is assumed to be git repo root."
    )

    reg_delegate = ORegistryv1Delegate()
    reg_handler = pm.getService('gregistryv1handler')
    reg_handler.setDelegate(reg_delegate)

    ma_delegate = OMAv1DelegateGuard()
    ma_handler = pm.getService('gmav1handler')
    ma_handler.setDelegate(ma_delegate)
Exemplo n.º 35
0
    def __init__(self):
        """
        Get plugins for use in other class methods.

        Retrieve whitelists for use in validity checking.
        """
        self._slice_authority_resource_manager = pm.getService(
            'osliceauthorityrm')
        self._delegate_tools = pm.getService('delegatetools')
        self._api_tools = pm.getService('apitools')
        self._slice_whitelist = self._delegate_tools.get_whitelist('SLICE')
        self._sliver_info_whitelist = self._delegate_tools.get_whitelist(
            'SLIVER_INFO')
        self._project_whitelist = self._delegate_tools.get_whitelist('PROJECT')
Exemplo n.º 36
0
def shares_slice(member1_urn, member2_urns, session, slice_uid = None):
    if member2_urns is None or len(member2_urns) == 0:
        return []
    db = pm.getService("chdbengine")
    st = aliased(db.SLICE_TABLE)
    sm1 = aliased(db.SLICE_MEMBER_TABLE)
    sm2 = aliased(db.SLICE_MEMBER_TABLE)
    ma1 = aliased(db.MEMBER_ATTRIBUTE_TABLE)
    ma2 = aliased(db.MEMBER_ATTRIBUTE_TABLE)

    q = session.query(st.c.expired, sm1.c.slice_id, sm2.c.slice_id, 
                      ma1.c.value.label('member1'), 
                      ma2.c.value.label('member2'))
    if slice_uid is not None:
        q = q.filter(sm1.c.slice_id == slice_uid)
    q = q.filter(st.c.slice_id == sm1.c.slice_id)
    q = q.filter(st.c.expired == False)
    q = q.filter(sm1.c.slice_id == sm2.c.slice_id)
    q = q.filter(sm1.c.member_id == ma1.c.member_id)
    q = q.filter(sm2.c.member_id == ma2.c.member_id)
    q = q.filter(ma1.c.name == 'urn')
    q = q.filter(ma2.c.name == 'urn')
    q = q.filter(ma1.c.value == member1_urn)
    q = q.filter(ma2.c.value.in_(member2_urns))

    rows = q.all()

    sharers = [row.member2 for row in rows]
    return sharers
Exemplo n.º 37
0
def setup():
    # setup config keys
    # config = pm.getService("config")

    delegate = DHCPGENI3Delegate()
    handler = pm.getService('geniv3handler')
    handler.setDelegate(delegate)
Exemplo n.º 38
0
    def update_project_credentials_for_member(self, member_urn, certificate,
                                              credentials, options):
        """
        updates project credentials after member certificate update due to membership renewal or revocation
        """
        member_cert = options['MEMBER_CERTIFICATE']
        project_memberships = self.lookup_project_membership_for_member(
            member_urn, certificate, credentials, None)
        geniutil = pm.getService('geniutil')

        for membership in project_memberships:
            project_cert = membership['PROJECT_CERTIFICATE']
            project_creds_old = membership['PROJECT_CREDENTIALS']
            project_prvlg, project_urn = geniutil.get_privileges_and_target_urn(
                [{
                    'SFA': project_creds_old
                }])
            project_exp = geniutil.get_expiration(project_creds_old)
            project_creds_new = geniutil.create_credential_ex(
                owner_cert=member_cert,
                target_cert=project_cert,
                issuer_key=self._sa_pr,
                issuer_cert=self._sa_c,
                privileges_list=project_prvlg,
                expiration=project_exp)

            update_data = {
                'members_to_modify': [{
                    'PROJECT_CREDENTIALS': project_creds_new
                }]
            }
            self._resource_manager_tools.member_modify(
                self.AUTHORITY_NAME, 'project_member', project_urn,
                update_data, 'PROJECT_MEMBER', 'PROJECT_URN')
Exemplo n.º 39
0
    def GetVersion(self, client_cert):
        self.logger.info("Called GetVersion")

        user_email = get_email_from_cert(client_cert)
        # Load the authority from the config
        config = pm.getService('config')
        authority = config.get('chrm.authority')

        # Which API? What is the right value?
        API_VERSION = 1
        CH_HOSTNAME = authority

        # Read code tag from a file
        code_tag = get_code_tag(PGCH_LOG_PREFIX)

        # Templated URN. Should we get this from
        # the authority certificate?
        urn = 'urn:publicid:IDN+' + CH_HOSTNAME + '+authority+ch'

        # At present there are no peers
        peers = dict()
        version = dict(peers=peers,
                       api=API_VERSION,
                       urn=urn,
                       hrn=CH_HOSTNAME,
                       url='https://' + CH_HOSTNAME + '/PGCH',
                       interface='registry',
                       code_tag=code_tag,
                       hostname=CH_HOSTNAME)
        return self._successReturn(version)
Exemplo n.º 40
0
def setup():
    # setup config items
    config = pm.getService("config")
    config.install("worker.dbpath", "deploy/worker.db", "Path to the worker's database (if relative, AMsoil's root will be assumed).")
    
    import workers as worker_package
    pm.registerService('worker', worker_package)
Exemplo n.º 41
0
def setup():

    pm.registerService('apiexceptionsv1', apiexceptionsv1)
    pm.registerService('apiexceptionsv2', apiexceptionsv2)

    api_tools = APITools()
    pm.registerService('apitools', api_tools)

    resource_manager_tools = ResourceManagerTools()
    pm.registerService('resourcemanagertools', resource_manager_tools)

    config = pm.getService("config")
    config.install("delegatetools.config_path", "deploy/config.json",
                   "JSON file with configuration data for CH, SA, MA")
    config.install("delegatetools.supplemetary_fileds_path",
                   "deploy/supplementary_fields.json",
                   "JSON file with Supplementary Fields for CH, SA, MA", True)
    config.install("delegatetools.service_registry_path",
                   "deploy/registry.json",
                   "JSON file with Services supported by the registry", True)
    config.install("delegatetools.defaults_path",
                   "src/plugins/fedtools/defaults.json",
                   "JSON file with default data for CH, SA, MA", True)

    delegate_tools = DelegateTools()
    pm.registerService('delegatetools', delegate_tools)
Exemplo n.º 42
0
def setup():

    pm.registerService('apiexceptionsv1', apiexceptionsv1)
    pm.registerService('apiexceptionsv2', apiexceptionsv2)

    api_tools = APITools()
    pm.registerService('apitools', api_tools)

    resource_manager_tools = ResourceManagerTools()
    pm.registerService('resourcemanagertools', resource_manager_tools)

    config = pm.getService("config")
    config.install("delegatetools.config_path", "deploy/config.json", "JSON file with configuration data for CH, SA, MA")
    config.install("delegatetools.supplemetary_fileds_path", "deploy/supplementary_fields.json", "JSON file with Supplementary Fields for CH, SA, MA",True)
    config.install("delegatetools.service_registry_path","deploy/registry.json", "JSON file with Services supported by the registry",True)
    config.install("delegatetools.defaults_path", "src/plugins/fedtools/defaults.json", "JSON file with default data for CH, SA, MA", True)
    #<UT>
    config.install("delegatetools.authz_path", "src/plugins/fedtools/authz.json", "JSON file with mapping between privileges and methods", True)
    config.install("delegatetools.roles_path", "src/plugins/fedtools/roles.json", "JSON file with default privileges for CH roles", True)
    config.install("delegatetools.trusted_cert_path", "deploy/trusted/certs/", "Path to trusted certificates", True)
    config.install("delegatetools.trusted_cert_keys_path", "deploy/trusted/cert_keys", "Path to trusted certificate keys", True)
    config.install("delegatetools.trusted_crl_path", "deploy/trusted/crl", "Path to CRLs", True)

    delegate_tools = DelegateTools()
    pm.registerService('delegatetools', delegate_tools)
Exemplo n.º 43
0
def setup():
    # setup config keys
    # config = pm.getService("config")
    
    delegate = ISLANDdelegate()
    handler = pm.getService('geniv3handler')
    handler.setDelegate(delegate)
Exemplo n.º 44
0
    def delegate_credentials(self, delegetee_cert, issuer_key, privileges_list,
                             expiration, delegatable, certificate,
                             credentials):
        """
        Creates delegated credentials
        """

        if credentials is None or len(credentials) <= 0 or not isinstance(
                credentials[0], dict):
            raise GFedv2ArgumentError("Passed invalid or no credentials")

        geniutil = pm.getService('geniutil')

        priv_from_cred, target_urn_from_cred = geniutil.get_privileges_and_target_urn(
            credentials)

        self.verify_credentials(credentials, certificate, target_urn_from_cred)

        if not set(priv_from_cred).issuperset(privileges_list):
            raise GFedv2AuthorizationError(
                "You cannot delegate privileges that you don't own")

        object_cert = geniutil.extract_object_certificate(credentials)

        return geniutil.create_credential_ex(delegetee_cert, object_cert,
                                             issuer_key, certificate,
                                             privileges_list, expiration,
                                             delegatable, credentials)
Exemplo n.º 45
0
    def verify_credentials(self, credentials, certificate, target_urn=None):
        """
        Verifies if credentials are valid and trusted. If yes, then returns a list of associated privileges
        :param credentials: credentials to verify
        :param certificate: certificate of owner of these credentials
        :param target_urn:  Target object's urn of these credentials
        :return: If verification passed, the a list of privileges associated with the passed credentials
        """

        if credentials is None or len(credentials) <= 0 or not isinstance(
                credentials[0], dict):
            raise GFedv2ArgumentError("Passed invalid or no credentials")

        geniutil = pm.getService('geniutil')

        priv_from_cred, target_urn_from_cred = geniutil.get_privileges_and_target_urn(
            credentials)
        user_urn_from_cert, _, _ = geniutil.extract_certificate_info(
            certificate)

        #If given are system member credentials then target_urn cannot be used in verification
        if user_urn_from_cert == target_urn_from_cred:
            geniutil.verify_credential_ex(credentials,
                                          certificate,
                                          user_urn_from_cert,
                                          self.TRUSTED_CERT_PATH,
                                          crl_path=self.TRUSTED_CRL_PATH)
        else:
            geniutil.verify_credential_ex(credentials,
                                          certificate,
                                          target_urn,
                                          self.TRUSTED_CERT_PATH,
                                          crl_path=self.TRUSTED_CRL_PATH)

        return priv_from_cred
Exemplo n.º 46
0
 def __init__(self):
     """
     Initialise logger and clear delegate.
     """
     super(GSAv2Handler, self).__init__(logger)
     self._api_tools = pm.getService('apitools')
     self._delegate = None
Exemplo n.º 47
0
    def lxml_parse_rspec(self, rspec_string):
        """Returns a the root element of the given {rspec_string} as lxml.Element.
        If the config key is set, the rspec is validated with the schemas found at the URLs specified in schemaLocation of the the given RSpec."""
        # parse
        rspec_root = etree.fromstring(rspec_string)
        # validate RSpec against specified schemaLocations
        config = pm.getService("config")
        should_validate = config.get("geniv3rpc.rspec_validation")

        if should_validate:
            schema_locations = rspec_root.get(
                "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation")
            if schema_locations:
                schema_location_list = schema_locations.split(" ")
                schema_location_list = map(
                    lambda x: x.strip(),
                    schema_location_list)  # strip whitespaces
                for sl in schema_location_list:
                    try:
                        xmlschema_contents = urllib2.urlopen(
                            sl)  # try to download the schema
                        xmlschema_doc = etree.parse(xmlschema_contents)
                        xmlschema = etree.XMLSchema(xmlschema_doc)
                        xmlschema.validate(rspec_root)
                    except Exception as e:
                        logger.warning(
                            "RSpec validation failed failed (%s: %s)" % (
                                sl,
                                str(e),
                            ))
            else:
                logger.warning("RSpec does not specify any schema locations")
        return rspec_root
Exemplo n.º 48
0
    def auth(self, client_cert, credentials, slice_urn=None, privileges=()):
        # check variables
        if not isinstance(privileges, tuple):
            raise TypeError("Privileges need to be a tuple.")
        # collect credentials (only GENI certs, version ignored)
        geni_credentials = []
        for c in credentials:
             if c['geni_type'] == 'geni_sfa':
                 geni_credentials.append(c['geni_value'])

        # get the cert_root
        config = pm.getService("config")
        cert_root = expand_amsoil_path(config.get("chapiv1rpc.ch_cert_root"))
        
        if client_cert == None:
            # work around if the certificate could not be acquired due to the shortcommings of the werkzeug library
            if config.get("flask.debug"):
                import gcf.sfa.trust.credential as cred
                client_cert = cred.Credential(string=geni_credentials[0]).gidCaller.save_to_string(save_parents=True)
            else:
                raise CHAPIv1ForbiddenError("Could not determine the client SSL certificate")
        # test the credential
        try:
            cred_verifier = gcf.geni.cred_util.CredentialVerifier(cert_root)
            cred_verifier.verify_from_strings(client_cert, geni_credentials, slice_urn, privileges)
        except Exception as e:
            raise CHAPIv1ForbiddenError(str(e))
        
        user_gid = gid.GID(string=client_cert)
        user_urn = user_gid.get_urn()
        user_uuid = user_gid.get_uuid()
        user_email = user_gid.get_email()
        return user_urn, user_uuid, user_email # TODO document return
Exemplo n.º 49
0
    def GetVersion(self, client_cert):
        self.logger.info("Called GetVersion")

        user_email = get_email_from_cert(client_cert)
        # Load the authority from the config
        config = pm.getService('config')
        authority = config.get('chrm.authority')

        # Which API? What is the right value?
        API_VERSION = 1
        CH_HOSTNAME = authority

        # Read code tag from a file
        code_tag = get_code_tag(PGCH_LOG_PREFIX)

        # Templated URN. Should we get this from
        # the authority certificate?
        urn = 'urn:publicid:IDN+' + CH_HOSTNAME + '+authority+ch'

        # At present there are no peers
        peers = dict()
        version = dict(peers=peers,
                       api=API_VERSION,
                       urn=urn,
                       hrn=CH_HOSTNAME,
                       url='https://' + CH_HOSTNAME + '/PGCH',
                       interface='registry',
                       code_tag=code_tag,
                       hostname=CH_HOSTNAME)
        return self._successReturn(version)
Exemplo n.º 50
0
    def lxml_parse_rspec(self, rspec_string):
        """Returns a the root element of the given {rspec_string} as lxml.Element.
        If the config key is set, the rspec is validated with the schemas found at the URLs specified in schemaLocation of the the given RSpec."""
        # parse
        rspec_root = etree.fromstring(rspec_string)
        # validate RSpec against specified schemaLocations
        config = pm.getService("config")
        should_validate = config.get("geniv3rpc.rspec_validation")

        if should_validate:
            schema_locations = rspec_root.get("{http://www.w3.org/2001/XMLSchema-instance}schemaLocation")
            if schema_locations:
                schema_location_list = schema_locations.split(" ")
                schema_location_list = map(lambda x: x.strip(), schema_location_list) # strip whitespaces
                for sl in schema_location_list:
                    try:
                        xmlschema_contents = urllib2.urlopen(sl) # try to download the schema
                        xmlschema_doc = etree.parse(xmlschema_contents)
                        xmlschema = etree.XMLSchema(xmlschema_doc)
                        xmlschema.validate(rspec_root)
                    except Exception as e:
                        logger.warning("RSpec validation failed failed (%s: %s)" % (sl, str(e),))
            else:
                logger.warning("RSpec does not specify any schema locations")
        return rspec_root
Exemplo n.º 51
0
def shares_project(member1_urn, member2_urns, session, project_uid = None):
    if member2_urns is None or len(member2_urns) == 0:
        return []
    db = pm.getService("chdbengine")
    pm1 = aliased(db.PROJECT_MEMBER_TABLE)
    pm2 = aliased(db.PROJECT_MEMBER_TABLE)
    ma1 = aliased(db.MEMBER_ATTRIBUTE_TABLE)
    ma2 = aliased(db.MEMBER_ATTRIBUTE_TABLE)

    q = session.query(pm1.c.project_id, 
                      ma1.c.value.label('member1'), 
                      ma2.c.value.label('member2'))
    if project_uid is not None:
        q = q.filter(pm1.c.project_id == project_uid)
    q = q.filter(pm1.c.project_id == pm2.c.project_id)
    q = q.filter(pm1.c.member_id == ma1.c.member_id)
    q = q.filter(pm2.c.member_id == ma2.c.member_id)
    q = q.filter(ma1.c.name == 'urn')
    q = q.filter(ma2.c.name == 'urn')
    q = q.filter(ma1.c.value == member1_urn)
    q = q.filter(ma2.c.value.in_(member2_urns))

    rows = q.all()

    sharers = [row.member2 for row in rows]
    return sharers
Exemplo n.º 52
0
def shares_slice(member1_urn, member2_urns, session, slice_uid = None):
    if member2_urns is None or len(member2_urns) == 0:
        return []
    db = pm.getService("chdbengine")
    st = aliased(db.SLICE_TABLE)
    sm1 = aliased(db.SLICE_MEMBER_TABLE)
    sm2 = aliased(db.SLICE_MEMBER_TABLE)
    ma1 = aliased(db.MEMBER_ATTRIBUTE_TABLE)
    ma2 = aliased(db.MEMBER_ATTRIBUTE_TABLE)

    q = session.query(st.c.expired, sm1.c.slice_id, sm2.c.slice_id, 
                      ma1.c.value.label('member1'), 
                      ma2.c.value.label('member2'))
    if slice_uid is not None:
        q = q.filter(sm1.c.slice_id == slice_uid)
    q = q.filter(st.c.slice_id == sm1.c.slice_id)
    q = q.filter(st.c.expired == False)
    q = q.filter(sm1.c.slice_id == sm2.c.slice_id)
    q = q.filter(sm1.c.member_id == ma1.c.member_id)
    q = q.filter(sm2.c.member_id == ma2.c.member_id)
    q = q.filter(ma1.c.name == 'urn')
    q = q.filter(ma2.c.name == 'urn')
    q = q.filter(ma1.c.value == member1_urn)
    q = q.filter(ma2.c.value.in_(member2_urns))

    rows = q.all()

    sharers = [row.member2 for row in rows]
    return sharers
Exemplo n.º 53
0
    def create_project(self, client_cert, credentials, fields, options):
        """
        Create a project object.

        Generate fields for a new object:
            * PROJECT_URN: retrieve the hostname from the Flask AMsoil plugin
                and form into a valid URN
            * PROJECT_UID: generate a new UUID4 value
            * PROJECT_CREATION: get the time now and convert it into RFC3339 form
            * PROJECT_EXPIRED: project object has just been created, so it is
                has not yet expired

        """
        config = pm.getService('config')
        hostname = config.get('flask.hostname')

        fields[
            'PROJECT_URN'] = 'urn:publicid+IDN+' + hostname + '+project+' + fields.get(
                'PROJECT_NAME')
        fields['PROJECT_UID'] = str(uuid.uuid4())
        fields['PROJECT_CREATION'] = pyrfc3339.generate(
            datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
        fields['PROJECT_EXPIRED'] = False
        return self._resource_manager_tools.object_create(
            self.AUTHORITY_NAME, fields, 'project')
 def lookup_authorities_for_urns(self, client_cert, urns):
     regrm = pm.getService('oregistryrm')
     try:
         result = regrm.get_authory_mappings(urns)
     except ValueError as e:
         raise gfed_ex.GFedv1ArgumentError(str(e))
     return result
Exemplo n.º 55
0
def setup():
    rest = pm.getService("rest")
    opsmon_handler = OpsMonHandler()
    pm.registerService("opsmon_handler", opsmon_handler)
    rest.registerREST(
        "opsmon", OpsMonHandler.handle_opsmon_request, "/info/<variety>/<id>", methods=["GET"], defaults={}
    )
Exemplo n.º 56
0
 def __init__(self):
     """
     Initialise logger and clear delegate.
     """
     super(GSAv2Handler, self).__init__(logger)
     self._api_tools = pm.getService('apitools')
     self._delegate = None
Exemplo n.º 57
0
    def _get_paths(self):
        """
        Get full file paths for JSON files to load (config.json and defaults.json).

        Returns:
            dictionary containing the loaded JSON content
        """

        config = pm.getService("config")
        config_path = config.get("delegatetools.config_path")
        supplemetary_fields_path = config.get(
            "delegatetools.supplemetary_fileds_path")
        service_registry_path = config.get(
            "delegatetools.service_registry_path")
        defaults_path = config.get("delegatetools.defaults_path")
        authz_path = config.get("delegatetools.authz_path")  #<UT>
        roles_path = config.get("delegatetools.roles_path")  #<UT>
        return {
            'CONFIG': expand_amsoil_path(config_path),
            'DEFAULTS': expand_amsoil_path(defaults_path),
            'SUPPLEMENTARY_FIELDS':
            expand_amsoil_path(supplemetary_fields_path),
            'REGISTRY': expand_amsoil_path(service_registry_path),
            'AUTHZ': expand_amsoil_path(authz_path),  #<UT>
            'ROLES': expand_amsoil_path(roles_path),  #<UT>
        }
Exemplo n.º 58
0
    def _checkMaintenanceMode(self):
        """Check wheter the clearinghouse is in a maintenance outage. If so,
        raise an authorization error so calls are not made during the
        outage. Only operators and authorities can use the
        clearinghouse during a maintenance outage.

        """
        config = pm.getService('config')
        maintenance_outage_location = \
            config.get('geni.maintenance_outage_location')
        outage_mode = os.path.exists(maintenance_outage_location)
        if outage_mode:
            if self._session and self._client_cert:
                user_urn = get_urn_from_cert(self._client_cert)
                is_operator = lookup_operator_privilege(user_urn,
                                                        self._session)
                is_authority = lookup_authority_privilege(user_urn,
                                                          self._session)
                if not is_operator and not is_authority:
                    msg = "User %s denied access during maintenance outage"
                    msg = msg % (user_urn)
                    chapi_info("OUTAGE", msg)
                    msg = ("Cannot access GENI Clearinghouse during"
                           + " maintenance outage.")
                    raise CHAPIv1AuthorizationError(msg)
Exemplo n.º 59
0
    def check_if_ma_info_update_authorized(self, credentials, certificate,
                                           type_, target_urn):
        """
        Performs authorization check on member/key info update
        :param credentials:
        :param options:
        :param type_:
        :return:
        """
        if credentials is None or len(credentials) <= 0 or not isinstance(
                credentials[0], dict):
            raise GFedv2ArgumentError("Passed invalid or no credentials")

        geniutil = pm.getService('geniutil')
        user_urn_from_cert, _, _ = geniutil.extract_certificate_info(
            certificate)

        #Update is allowed for owner himself. Otherwise, proper credentials should be presented
        if user_urn_from_cert == target_urn:
            geniutil.verify_credential_ex(credentials,
                                          certificate,
                                          target_urn,
                                          self.TRUSTED_CERT_PATH,
                                          crl_path=self.TRUSTED_CRL_PATH)
        else:
            self.check_if_authorized(credentials=credentials,
                                     certificate=certificate,
                                     method='UPDATE',
                                     type_=type_,
                                     target_urn=None)