Пример #1
0
 def init_tests(self):
     self.maps = load_json_file('data/attributeMaps.json', encoding='utf8')
     self.datasets = []
     datasets = load_json_file('data/testDatasets.json')
     for dt in datasets:
         d = Dataset()
         self.datasets.append(d.unmarshall(dt))
Пример #2
0
    def test_Dataset(self):
        datasets = load_json_file('data/testDatasets.json')

        d = Dataset()
        d.unmarshall(datasets[0])

        self.assertEqual(d.properties['test'],
                         datasets[0]['properties']['test'])
Пример #3
0
 def __init__(self):
     self.id = str
     self.uri = str
     self.issuer = str
     self.type = str
     self.lloa = str
     self.issued = str
     self.expiration = str
     self.datasetA = Dataset()
     self.datasetB = Dataset()
     self.evidence = [FileObject()]
     self.conversation = [ChatMessage()]
Пример #4
0
    def init_tests(self):
        # Test data sets
        self.datasets = []
        datasets = load_json_file('data/testDatasets.json')
        for dt in datasets:
            d = Dataset()
            self.datasets.append(d.unmarshall(dt))

        self.mappings = []
        mappings = load_json_file('data/attributeMaps.json')
        for mt in mappings:
            m = AttributeMap()
            self.mappings.append(m.unmarshall(mt))
Пример #5
0
def cancel_linking_request(request_id):
    clean_expired()

    # Check msToken against SM
    if 'msToken' in request.form:
        msToken = request.form['msToken']
    elif 'msToken' in request.args:
        msToken = request.args['msToken']
    else:
        return "missing msToken POST/GET parameter or bad content-type", 404
    smh = get_session_manager()
    try:
        smh.validateToken(msToken)
    except SessionManagerError as err:
        return "Error validating msToken: " + str(err), 403

    try:
        dest_url = smh.getSessionVar('ClientCallbackAddr')
    except SessionManagerError as err:
        return "Error retrieving ClientCallbackAddr from SM: " + str(err), 403

    req = get_request(request_id)
    if not req:
        # return "Request ID not found", 403
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Request ID not found")

    if not check_owner(smh.sessId, req.request_owner):
        # return "Request does not belong to the authenticated user", 403
        return redirect_return(
            smh, dest_url, 'ERROR', msID, apigwID,
            "Request does not belong to the authenticated user")

    # First we delete it from the dataStore by rebuilding the persistent ID
    try:
        datasetA = Dataset()
        datasetA.json_unmarshall(req.dataset_a)
        datasetB = Dataset()
        datasetB.json_unmarshall(req.dataset_b)
        entry_id = build_store_id_from_req(
            "seal-autorecon", issuer, datasetA,
            datasetB)  # TODO: change when the module is parametrised
        smh.deleteDatastoreEntry(entry_id)
    except SessionManagerError as err:
        return redirect_return(
            smh, dest_url, 'ERROR', msID, apigwID,
            "Error deleting linkRequest from dataStore: " + str(err))
    except StoreIDBuildError as err:
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Error building store ID: " + str(err))
    try:
        delete_request(request_id)
        # return "Request Deleted", 200
        return redirect_return(smh, dest_url, 'OK', msID, apigwID)

    except RegisterNotFound:
        # return "Request not found", 403
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Request not found")
Пример #6
0
    def searchDatastoreEntries(self, type=None):
        if not type:
            logging.debug('Searching all datastore entries')
        else:
            logging.debug('Searching datastore entries of type:' + type)
        queryParams = {'sessionId': self.sessId}
        body = {
            'sessionId': self.sessId,
            'id': None,
            'type': type,
            'data': None,
        }
        url = self._getApiUrl('SM', 'datastoreSearch') + "?" + urlencode(queryParams)

        res = self.httpsig.postJson(url, body)
        res = self._parseResponse(res)
        logging.debug('Received response:' + str(res))

        if res.code != SessionMngrCode.OK:
            raise SessionManagerError("store entry search failed: " + str(res.error))

        if not res.additionalData:
            raise SessionManagerError("No additionalData on response")

        storeObjListofDicts = json.loads(res.additionalData)
        storeObjList = []
        for storeObjDict in storeObjListofDicts:
            storeObj = StoreEntry()
            storeObj.unmarshall(storeObjDict)
            storeObjList.append(storeObj)

        idx = 0
        for storeObj in storeObjList:
            if not storeObj.id:
                raise SessionManagerError("store entry search failed: no data id at idx " + str(idx))
            if not storeObj.type:
                raise SessionManagerError("store entry search failed: no data type at idx " + str(idx))
            if not storeObj.data:
                raise SessionManagerError("store entry search failed: no data object at idx " + str(idx))

            if storeObj.type == "linkRequest":  # TODO: parametrise and check the types of object
                obj = LinkRequest()
            elif storeObj.type == "dataSet":
                obj = Dataset()
            else:
                raise SessionManagerError("Unknown store entry type: " + storeObj.type + " at idx " + str(idx))

            obj.json_unmarshall(storeObj.data)
            storeObj.data = obj
            idx += 1

        return storeObjList
Пример #7
0
    def getDatastoreEntry(self, id):
        logging.debug('Requesting datastore entry:' + id)
        queryParams = {'sessionId': self.sessId}
        body = {
            'sessionId': self.sessId,
            'id': id,
            'type': None,
            'data': None,
        }
        url = self._getApiUrl('SM', 'datastoreGet') + "?" + urlencode(queryParams)

        res = self.httpsig.postJson(url, body)
        res = self._parseResponse(res)
        logging.debug('Received response:' + str(res))

        if res.code != SessionMngrCode.OK or res.additionalData == SessionMngrCode.ERROR:
            raise SessionManagerError("store entry fetch failed: " + str(res.error))

        if not res.additionalData:
            raise SessionManagerError("No additionalData on response")

        storeObj = StoreEntry()
        storeObj.json_unmarshall(res.additionalData)

        if not storeObj.id:
            raise SessionManagerError("store entry fetch failed: no data id")
        if not storeObj.type:
            raise SessionManagerError("store entry fetch failed: no data type")
        if not storeObj.data:
            raise SessionManagerError("store entry fetch failed: no data object")

        if storeObj.type == "linkRequest":  # TODO: parametrise and check the types of object
            obj = LinkRequest()
        elif storeObj.type == "dataSet":
            obj = Dataset()
        else:
            raise SessionManagerError("Unknown store entry type: " + storeObj.type)

        obj.json_unmarshall(storeObj.data)
        storeObj.data = obj

        return storeObj
Пример #8
0
    def match_set(self, dataset: Dataset(), attr_map: AttributeMap()):

        # Get the issuer of the data set
        set_issuer = None
        if dataset.issuerId is not None and dataset.issuerId != '':
            iss = None
            for attr in dataset.attributes:
                if attr.name == dataset.issuerId:
                    iss = attr.values[0]
                    break
            if iss is not None and iss != '':
                set_issuer = iss

        # Check all pairings to see if they are valid for this dataset
        valid_pairings = set()
        for pair in attr_map.pairings:

            # If there is a fixed issuer in the pairing, check it
            if pair.issuer is not None and set_issuer is not None:
                if pair.issuer == set_issuer:
                    valid_pairings.add(pair)
                continue

            # If there's type and does not match, skip
            if dataset.type is not None and pair.profile is not None:
                if dataset.type == pair.profile:
                    valid_pairings.add(pair)
                continue

            # If there are fixed categories to find (one found is ok)
            if pair.categories is not None and pair.categories != []:
                for cat in pair.categories:
                    if cat in dataset.categories:
                        valid_pairings.add(pair)
                        break

        return valid_pairings
Пример #9
0
def linking_request_result(request_id):
    clean_expired()

    # Check msToken against SM
    if 'msToken' in request.form:
        msToken = request.form['msToken']
    elif 'msToken' in request.args:
        msToken = request.args['msToken']
    else:
        return "missing msToken POST/GET parameter or bad content-type", 404
    smh = get_session_manager()
    try:
        smh.validateToken(msToken)
    except SessionManagerError as err:
        return "Error validating msToken: " + str(err), 403

    try:
        dest_url = smh.getSessionVar('ClientCallbackAddr')
    except SessionManagerError as err:
        return "Error retrieving ClientCallbackAddr from SM: " + str(err), 403

    req = get_request(request_id)
    if not req:
        # return "Request ID not found", 403
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Request ID not found")

    if not check_owner(smh.sessId, req.request_owner):
        # return "Request does not belong to the authenticated user", 403
        return redirect_return(
            smh, dest_url, 'ERROR', msID, apigwID,
            "Request does not belong to the authenticated user")

    datasetA = Dataset()
    datasetA.json_unmarshall(req.dataset_a)
    datasetB = Dataset()
    datasetB.json_unmarshall(req.dataset_b)

    if req.status != "ACCEPTED":
        # Delete request from dataStore
        try:
            entry_id = build_store_id_from_req(
                "seal-autorecon", issuer, datasetA,
                datasetB)  # TODO: change when the module is parametrised
            smh.deleteDatastoreEntry(entry_id)
        except SessionManagerError as err:
            return redirect_return(
                smh, dest_url, 'ERROR', msID, apigwID,
                "Error deleting linkRequest from dataStore: " + str(err))
        except StoreIDBuildError as err:
            return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                                   "Error building store ID: " + str(err))
        try:
            delete_request(request_id)
        except RegisterNotFound:
            logging.warning(
                "This should not happen. Can't delete a register I have just read"
            )

        # return "Linking request was not accepted", 403
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Linking request was not accepted")

    # Calculate expiration date
    expiration = None
    if validity_days > 0:
        expiration = datetime.now() + timedelta(days=validity_days)
        expiration = expiration.isoformat()

    # Build Response object
    result = LinkRequest()
    result.id = req.request_id
    result.issuer = issuer
    result.type = dataset_type
    result.lloa = lloa
    result.issued = datetime.now().isoformat()
    result.expiration = expiration
    result.datasetA = datasetA
    result.datasetB = datasetB
    result.evidence = None
    result.conversation = None
    try:
        result.uri = build_uri_representation_from_req(issuer, lloa, datasetA,
                                                       datasetB)
    except LinkURIBuildError as err:
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Error building link URI: " + str(err))

    result_json = result.json_marshall()
    # TODO: sign the response json string

    # Overwrite the response in the SM session
    try:
        smh.writeSessionVar(result.marshall(), 'linkRequest')
    except SessionManagerError as err:
        # return "Error writing updated linkRequest to SM: " + str(err), 403
        return redirect_return(
            smh, dest_url, 'ERROR', msID, apigwID,
            "Error writing updated linkRequest to SM: " + str(err))

    try:
        # Build the unique persistent storeEntry identifier # TODO: parametrise module name (search more incidences)
        entry_id = build_store_id_from_req("seal-autorecon", issuer,
                                           result.datasetA, result.datasetB)
        smh.addDatastoreEntry(entry_id, "linkRequest",
                              result.marshall())  # TODO: parametrise type
    except SessionManagerError as err:
        return redirect_return(
            smh, dest_url, 'ERROR', msID, apigwID,
            "Error writing updated linkRequest to dataStore: " + str(err))
    except StoreIDBuildError as err:
        return redirect_return(smh, dest_url, 'ERROR', msID, apigwID,
                               "Error building store ID: " + str(err))
    try:
        delete_request(request_id)
    except RegisterNotFound:
        logging.warning(
            "This should not happen. Can't delete a register I have just read")

    # return Response(result_json,
    #                status=200,
    #                mimetype='application/json')
    return redirect_return(smh, dest_url, 'OK', msID, apigwID)
Пример #10
0
 def test_unmarshall_marshall(self):
     datasets = load_json_file('data/testDatasets.json')
     d = Dataset()
     d.unmarshall(datasets[0])
     d.json_marshall()