def dynamic_validation(self, request: Request): self._validate_request_type(request) rev_reg_tags = request.operation[REVOC_REG_DEF_ID] author_did, req_id, operation = get_request_data(request) current_entry, revoc_def = self._get_current_revoc_entry_and_revoc_def( author_did=author_did, revoc_reg_def_id=operation[REVOC_REG_DEF_ID], req_id=req_id) rev_ref_def_author_did = rev_reg_tags.split(":", 1)[0] is_owner = rev_ref_def_author_did == author_did if current_entry: self.write_req_validator.validate(request, [ AuthActionEdit(txn_type=REVOC_REG_ENTRY, field='*', old_value='*', new_value='*', is_owner=is_owner) ]) else: self.write_req_validator.validate(request, [ AuthActionAdd(txn_type=REVOC_REG_ENTRY, field='*', value='*', is_owner=is_owner) ]) validator_cls = self.get_revocation_strategy( revoc_def[VALUE][ISSUANCE_TYPE]) validator = validator_cls(self.state) validator.validate(current_entry, request)
def get_result(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) if not validate_attrib_keys(operation): raise InvalidClientRequest(identifier, req_id, '{} should have one and only one of ' '{}, {}, {}' .format(ATTRIB, RAW, ENC, HASH)) nym = operation[TARGET_NYM] if RAW in operation: attr_type = RAW elif ENC in operation: # If attribute is encrypted, it will be queried by its hash attr_type = ENC else: attr_type = HASH attr_key = operation[attr_type] value, last_seq_no, last_update_time, proof = \ self.get_attr(did=nym, key=attr_key, attr_type=attr_type) attr = None if value is not None: if HASH in operation: attr = attr_key else: attr = value return self.make_result(request=request, data=attr, last_seq_no=last_seq_no, update_time=last_update_time, proof=proof)
def dynamic_validation(self, request: Request, req_pp_time: Optional[int]): # we can not add a Claim Def with existent ISSUER_DID # sine a Claim Def needs to be identified by seqNo self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) ref = operation[REF] try: txn = self.ledger.get_by_seq_no_uncommitted(ref) except KeyError: raise InvalidClientRequest(identifier, req_id, "Mentioned seqNo ({}) doesn't exist.".format(ref)) if txn['txn']['type'] != SCHEMA: raise InvalidClientRequest(identifier, req_id, "Mentioned seqNo ({}) isn't seqNo of the schema.".format(ref)) signature_type = get_write_claim_def_signature_type(request) schema_ref = get_write_claim_def_schema_ref(request) tag = get_write_claim_def_tag(request) path = self.make_state_path_for_claim_def(identifier, schema_ref, signature_type, tag) claim_def, _, _ = self.get_from_state(path, is_committed=False) if claim_def: self.write_req_validator.validate(request, [AuthActionEdit(txn_type=CLAIM_DEF, field='*', old_value='*', new_value='*')]) else: self.write_req_validator.validate(request, [AuthActionAdd(txn_type=CLAIM_DEF, field='*', value='*')])
def get_result(self, request: Request): identifier, req_id, operation = get_request_data(request) buy_key = BuyHandler.prepare_buy_key(identifier, req_id) result = self.state.get(buy_key) res = {f.IDENTIFIER.nm: identifier, f.REQ_ID.nm: req_id, "buy": result} return Reply(res)
def static_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) if not validate_attrib_keys(operation): raise InvalidClientRequest( identifier, req_id, '{} should have one and only one of ' '{}, {}, {}'.format(ATTRIB, RAW, ENC, HASH))
def make_schema_exist(schema_request, schema_handler): identifier, req_id, operation = get_request_data(schema_request) schema_name = get_write_schema_name(schema_request) schema_version = get_write_schema_version(schema_request) path = SchemaHandler.make_state_path_for_schema(identifier, schema_name, schema_version) schema_handler.state.set(path, encode_state_value("value", "seqNo", "txnTime"))
def make_context_exist(context_request, context_handler): identifier, req_id, operation = get_request_data(context_request) context_name = get_write_context_name(context_request) context_version = get_write_context_version(context_request) path = ContextHandler.make_state_path_for_context(identifier, context_name, context_version) context_handler.state.set(path, encode_state_value("value", "seqNo", "txnTime"))
def process_action(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) logger.debug("Transaction {} with type {} started".format( req_id, request.txn_type)) self.restarter.handleRestartRequest(request) result = generate_action_result(request) logger.debug("Transaction {} with type {} finished".format( req_id, request.txn_type)) return result
def dynamic_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) current_entry, revoc_def = self._get_current_revoc_entry_and_revoc_def( author_did=identifier, revoc_reg_def_id=operation[REVOC_REG_DEF_ID], req_id=req_id) validator_cls = self.get_revocation_strategy( revoc_def[VALUE][ISSUANCE_TYPE]) validator = validator_cls(self.state) validator.validate(current_entry, request)
def patched_dynamic_validation(self, request, req_pp_time): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) error = None if operation.get(ROLE) == STEWARD: if self._steward_threshold_exceeded(self.config): error = "New stewards cannot be added by other stewards " \ "as there are already {} stewards in the system". \ format(self.config.stewardThreshold) if error: raise UnauthorizedClientRequest(identifier, req_id, error)
def process_action(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) Txn = NamedTuple('txn', (('data', bytes), ('sender', bytes), ('to', bytes))) txn = Txn(decode_hex(operation['contract_code']), identifier, operation['contract_dest']) computation = self.virtual_machine.apply_transaction(txn) result = generate_action_result(request) # result[DATA] = self.info_tool.info return result
def dynamic_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) status = '*' pkt_to_upgrade = operation.get(PACKAGE, getConfig().UPGRADE_ENTRY) if pkt_to_upgrade: currentVersion, cur_deps = self.curr_pkt_info(pkt_to_upgrade) if not currentVersion: raise InvalidClientRequest( identifier, req_id, "Packet {} is not installed and cannot be upgraded".format( pkt_to_upgrade)) if all([APP_NAME not in d for d in cur_deps]): raise InvalidClientRequest( identifier, req_id, "Packet {} doesn't belong to pool".format(pkt_to_upgrade)) else: raise InvalidClientRequest(identifier, req_id, "Upgrade packet name is empty") targetVersion = operation[VERSION] reinstall = operation.get(REINSTALL, False) if not Upgrader.is_version_upgradable(currentVersion, targetVersion, reinstall): # currentVersion > targetVersion raise InvalidClientRequest(identifier, req_id, "Version is not upgradable") action = operation.get(ACTION) # TODO: Some validation needed for making sure name and version # present txn = self.upgrader.get_upgrade_txn( lambda txn: get_payload_data(txn).get(NAME, None) == operation.get( NAME, None) and get_payload_data(txn).get( VERSION) == operation.get(VERSION), reverse=True) if txn: status = get_payload_data(txn).get(ACTION, '*') if status == START and action == START: raise InvalidClientRequest( identifier, req_id, "Upgrade '{}' is already scheduled".format( operation.get(NAME))) if status == '*': auth_action = AuthActionAdd(txn_type=POOL_UPGRADE, field=ACTION, value=action) else: auth_action = AuthActionEdit(txn_type=POOL_UPGRADE, field=ACTION, old_value=status, new_value=action) self.write_request_validator.validate(request, [auth_action])
def static_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) required_fields = list(dict(ClientGetAuthRuleOperation.schema).keys()) required_fields.remove(OLD_VALUE) if len(operation) > 1: if not set(required_fields).issubset(set(operation.keys())): raise InvalidClientRequest( identifier, req_id, "Not enough fields to build an auth key.") self._check_auth_key(operation, identifier, req_id)
def dynamic_validation(self, request: Request, req_pp_time: Optional[int]): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) error = None if not is_steward(self.state, identifier, is_committed=False): error = "Only Steward is allowed to do these transactions" if operation.get(ROLE) == STEWARD: if self._steward_threshold_exceeded(self.config): error = "New stewards cannot be added by other stewards " \ "as there are already {} stewards in the system". \ format(self.config.stewardThreshold) if error: raise UnauthorizedClientRequest(identifier, req_id, error)
def static_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) role = operation.get(ROLE) nym = operation.get(TARGET_NYM) if isinstance(nym, str): nym = nym.strip() if not nym: raise InvalidClientRequest( identifier, req_id, "{} needs to be present".format(TARGET_NYM)) if not Authoriser.isValidRole(role): raise InvalidClientRequest(identifier, req_id, "{} not a valid role".format(role))
def process_action(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) logger.debug("Transaction {} with type {} started".format( req_id, request.txn_type)) result = generate_action_result(request) result[DATA] = self.info_tool.info result[DATA].update(self.info_tool.memory_profiler) result[DATA].update(self.info_tool._generate_software_info()) result[DATA].update(self.info_tool.extractions) result[DATA].update(self.info_tool.node_disk_size) logger.debug("Transaction {} with type {} finished".format( req_id, request.txn_type)) return result
def additional_dynamic_validation(self, request: Request, req_pp_time: Optional[int]): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) status = '*' pkg_to_upgrade = operation.get(PACKAGE, getConfig().UPGRADE_ENTRY) targetVersion = operation[VERSION] reinstall = operation.get(REINSTALL, False) if not pkg_to_upgrade: raise InvalidClientRequest(identifier, req_id, "Upgrade package name is empty") try: res = self.upgrader.check_upgrade_possible(pkg_to_upgrade, targetVersion, reinstall) except Exception as exc: res = str(exc) if res: raise InvalidClientRequest(identifier, req_id, res) action = operation.get(ACTION) # TODO: Some validation needed for making sure name and version # present txn = self.upgrader.get_upgrade_txn( lambda txn: get_payload_data(txn).get(NAME, None) == operation.get( NAME, None) and get_payload_data(txn).get( VERSION) == operation.get(VERSION), reverse=True) if txn: status = get_payload_data(txn).get(ACTION, '*') if status == START and action == START: raise InvalidClientRequest( identifier, req_id, "Upgrade '{}' is already scheduled".format( operation.get(NAME))) if status == '*': auth_action = AuthActionAdd(txn_type=POOL_UPGRADE, field=ACTION, value=action) else: auth_action = AuthActionEdit(txn_type=POOL_UPGRADE, field=ACTION, old_value=status, new_value=action) self.write_req_validator.validate(request, [auth_action])
def dynamic_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) if not (not operation.get(TARGET_NYM) or self.__has_nym(operation[TARGET_NYM], is_committed=False)): raise InvalidClientRequest( identifier, req_id, '{} should be added before adding ' 'attribute for it'.format(TARGET_NYM)) if operation.get(TARGET_NYM) and operation[TARGET_NYM] != identifier and \ not self.database_manager.idr_cache.getOwnerFor(operation[TARGET_NYM], isCommitted=False) == identifier: raise UnauthorizedClientRequest( identifier, req_id, "Only identity owner/guardian can add attribute " "for that identity")
def additional_dynamic_validation(self, request: Request, req_pp_time: Optional[int]): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) if not (not operation.get(TARGET_NYM) or self.__has_nym(operation[TARGET_NYM], is_committed=False)): raise InvalidClientRequest( identifier, request.reqId, '{} should be added before adding ' 'attribute for it'.format(TARGET_NYM)) is_owner = self.database_manager.idr_cache.getOwnerFor( operation[TARGET_NYM], isCommitted=False) == identifier field = None value = None for key in (RAW, ENC, HASH): if key in operation: field = key value = operation[key] break if field == RAW: get_key = attrib_raw_data_serializer.deserialize(value) get_key = list(get_key.keys())[0] else: get_key = value old_value, seq_no, _ = self._get_attr(operation[TARGET_NYM], get_key, field) if seq_no is not None: self.write_req_validator.validate(request, [ AuthActionEdit(txn_type=ATTRIB, field=field, old_value=old_value, new_value=value, is_owner=is_owner) ]) else: self.write_req_validator.validate(request, [ AuthActionAdd(txn_type=ATTRIB, field=field, value=value, is_owner=is_owner) ])
def static_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) action = operation.get(ACTION) if action not in (START, CANCEL): raise InvalidClientRequest(identifier, req_id, "{} not a valid action".format(action)) if action == START: schedule = operation.get(SCHEDULE, {}) force = operation.get(FORCE) force = str(force) == 'True' isValid, msg = self.upgrader.isScheduleValid( schedule, self.pool_manager.getNodesServices(), force) if not isValid: raise InvalidClientRequest( identifier, req_id, "{} not a valid schedule since {}".format(schedule, msg))
def dynamic_validation(self, request: Request): # we can not add a Schema with already existent NAME and VERSION # sine a Schema needs to be identified by seqNo self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) schema_name = get_write_schema_name(request) schema_version = get_write_schema_version(request) path = SchemaHandler.make_state_path_for_schema( identifier, schema_name, schema_version) schema, _, _ = self.get_from_state(path) if schema: self.write_req_validator.validate(request, [ AuthActionEdit( txn_type=SCHEMA, field='*', old_value='*', new_value='*') ]) else: self.write_req_validator.validate( request, [AuthActionAdd(txn_type=SCHEMA, field='*', value='*')])
def process_action(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) logger.debug("Transaction {} with type {} started".format( req_id, request.txn_type)) result = generate_action_result(request) result[DATA] = self.info_tool.info # Memory profiler needs only for debug purposes, # because collecting memory info it's a very long time operation # result[DATA].update(self.info_tool.memory_profiler) """For keeping output format""" result[DATA].update({'Memory_profiler': []}) result[DATA].update(self.info_tool._generate_software_info()) result[DATA].update(self.info_tool.extractions) # ToDo: also can be a long time operation, because we use external tools result[DATA].update(self.info_tool.node_disk_size) logger.debug("Transaction {} with type {} finished".format( req_id, request.txn_type)) return result
def dynamic_validation(self, request: Request): # we can not add a Schema with already existent NAME and VERSION # sine a Schema needs to be identified by seqNo self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) schema_name = get_write_schema_name(request) schema_version = get_write_schema_version(request) schema, _, _, _ = self.get_schema_handler.get_schema( author=identifier, schema_name=schema_name, schema_version=schema_version, with_proof=False) if schema: raise InvalidClientRequest( identifier, req_id, '{} can have one and only one SCHEMA with ' 'name {} and version {}'.format(identifier, schema_name, schema_version)) self.write_request_validator.validate( request, [AuthActionAdd(txn_type=SCHEMA, field='*', value='*')])
def dynamic_validation(self, request: Request): # we can not add a Claim Def with existent ISSUER_DID # sine a Claim Def needs to be identified by seqNo self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) ref = operation[REF] try: txn = self.ledger.get_by_seq_no_uncommitted(ref) except KeyError: raise InvalidClientRequest( identifier, req_id, "Mentioned seqNo ({}) doesn't exist.".format(ref)) if txn['txn']['type'] != SCHEMA: raise InvalidClientRequest( identifier, req_id, "Mentioned seqNo ({}) isn't seqNo of the schema.".format(ref)) # only owner can update claim_def, # because his identifier is the primary key of claim_def self.write_req_validator.validate( request, [AuthActionAdd(txn_type=CLAIM_DEF, field='*', value='*')])
def dynamic_validation(self, request: Request): # we can not add a Context with already existent NAME and VERSION # since a Context needs to be identified by seqNo self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) context_name = get_write_context_name(request) context_version = get_write_context_version(request) path = ContextHandler.make_state_path_for_context(identifier, context_name, context_version) context, _, _ = self.get_from_state(path) if context: self.write_req_validator.validate(request, [AuthActionEdit(txn_type=SET_CONTEXT, field='*', old_value='*', new_value='*')]) else: self.write_req_validator.validate(request, [AuthActionAdd(txn_type=SET_CONTEXT, field='*', value='*')])
def static_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) if not validate_attrib_keys(operation): raise InvalidClientRequest(identifier, req_id, '{} should have one and only one of ' '{}, {}, {}' .format(ATTRIB, RAW, ENC, HASH)) if RAW in operation: try: get_key = attrib_raw_data_serializer.deserialize(operation[RAW]) if len(get_key) == 0: raise InvalidClientRequest(identifier, request.reqId, '"row" attribute field must contain non-empty dict'. format(TARGET_NYM)) except JSONDecodeError: raise InvalidClientRequest(identifier, request.reqId, 'Attribute field must be dict while adding it as a row field'. format(TARGET_NYM))
def _validate_new_nym(self, request, operation): identifier, req_id, _ = get_request_data(request) role = operation.get(ROLE) nym_data = self.database_manager.idr_cache.getNym(request.identifier, isCommitted=False) if not nym_data: # Non-ledger nym case. These two checks duplicated and mainly executed in client_authn, # but it has point to repeat them here, for clear understanding of validation non-ledger request cases. if request.identifier != request.operation.get(TARGET_NYM): raise InvalidClientRequest( identifier, req_id, "DID which is not stored on ledger can " "send nym txn only if appropriate auth_rules set " "and sender did equal to destination nym") if not request.operation.get(VERKEY): raise InvalidClientRequest( identifier, req_id, "Non-ledger nym txn must contain verkey for new did") self.write_req_validator.validate( request, [AuthActionAdd(txn_type=NYM, field=ROLE, value=role)])
def dynamic_validation(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) cred_def_id = operation.get(CRED_DEF_ID) revoc_def_type = operation.get(REVOC_TYPE) revoc_def_tag = operation.get(TAG) assert cred_def_id assert revoc_def_tag assert revoc_def_type tags = cred_def_id.split(":") if len(tags) != 4 and len(tags) != 5: raise InvalidClientRequest( identifier, req_id, "Format of {} field is not acceptable. " "Expected: 'did:marker:signature_type:schema_ref' or " "'did:marker:signature_type:schema_ref:tag'".format( CRED_DEF_ID)) cred_def, _, _, _ = self.get_revoc_reg_def.lookup(cred_def_id, is_committed=False, with_proof=False) if cred_def is None: raise InvalidClientRequest( identifier, req_id, "There is no any CRED_DEF by path: {}".format(cred_def_id))