def __init__(self, rule_json=None): super(PolicyMappingRule, self).__init__(rule_json) if rule_json.get('policy_id') and rule_json.get('policy_ids'): raise ValidationError('Cannot specify both policy_id and policy_ids properties in mapping rule, must use one or the other') if rule_json.get('policy_id'): self.policy_ids = [rule_json.get('policy_id')] elif rule_json.get('policy_ids'): self.policy_ids = rule_json.get('policy_ids') else: raise ValidationError('No policy_id or policy_ids property found for mapping rule: {}'.format(rule_json)) self.whitelist_ids = rule_json.get('whitelist_ids')
def __init__(self, raw_json=None, strict_validation=True): self.raw = raw_json if not raw_json: raise ValueError('Empty whitelist json') self.verify_version(raw_json) self.version = raw_json.get('version') self.id = raw_json.get('id') self.name = raw_json.get('name') self.comment = raw_json.get('comment') self.rules = [] errors = [] for x in raw_json.get('rules'): try: self.rules.append(policy_rule_factory(self, x, strict_validation=strict_validation)) except PolicyRuleValidationErrorCollection as e: for err in e.validation_errors: errors.append(err) except PolicyError as e: errors.append(e) except Exception as e: errors.append(ValidationError.caused_by(e)) if errors: raise InitializationError(message='Policy initialization failed due to validation errors', init_errors=errors) self.gates = OrderedDict() # Map the rule set into a minimal set of gates to execute linked to the list of rules for each gate for r in self.rules: if r.gate_cls not in self.gates: self.gates[r.gate_cls] = [r] else: self.gates[r.gate_cls].append(r)
def __init__(self, policy_json=None): self.gate_name = policy_json.get('gate') self.trigger_name = policy_json.get('trigger') self.trigger_params = { p.get('name'): p.get('value') for p in policy_json.get('params')} action = policy_json.get('action', '').lower() try: self.action = GateAction.__members__[action] except KeyError: raise InvalidGateAction(action=action, gate_name=self.gate_name, trigger_name=self.trigger_name, valid_actions=filter(lambda x: not x.startswith('_'), GateAction.__dict__.keys())) self.error_exc = None self.errors = [] # Configure the trigger instance try: self.gate_cls = Gate.registry[self.gate_name.lower()] try: selected_trigger_cls = self.gate_cls.get_trigger_named(self.trigger_name) self.configured_trigger = selected_trigger_cls(parent_gate_cls=self.gate_cls, **self.trigger_params) except [TriggerNotFoundError, InvalidParameterError, InputParameterValidationError] as e: # Error finding or initializing the trigger log.exception('Policy rule execution exception: {}'.format(e)) self.error_exc = TriggerNotFoundError(self.gate_name, self.trigger_name) self.configured_trigger = None raise except PolicyError: raise except KeyError: # Gate not found raise GateNotFoundError(self.gate_name) except Exception as e: raise ValidationError(e)
def validate(self, value): try: jsonschema.validate(instance=value, schema=self.validation_schema) return True except jsonschema.ValidationError as e: raise ValidationError( 'JSON Schema validation failed. Schema={}, Detail={}'.format( e.schema, e.message))
def __init__(self, parent, policy_json=None): super(ExecutablePolicyRule, self).__init__(parent, policy_json) # Configure the trigger instance try: self.gate_cls = Gate.get_gate_by_name(self.gate_name) except KeyError: # Gate not found self.error_exc = GateNotFoundError(gate=self.gate_name, valid_gates=Gate.registered_gate_names(), rule_id=self.rule_id) self.configured_trigger = None raise self.error_exc try: selected_trigger_cls = self.gate_cls.get_trigger_named(self.trigger_name.lower()) except KeyError: self.error_exc = TriggerNotFoundError(valid_triggers=self.gate_cls.trigger_names(), trigger=self.trigger_name, gate=self.gate_name, rule_id=self.rule_id) self.configured_trigger = None raise self.error_exc try: try: self.configured_trigger = selected_trigger_cls(parent_gate_cls=self.gate_cls, rule_id=self.rule_id, **self.trigger_params) except (TriggerNotFoundError, InvalidParameterError, ParameterValueInvalidError) as e: # Error finding or initializing the trigger self.error_exc = e self.configured_trigger = None if hasattr(e, 'gate') and e.gate is None: e.gate = self.gate_name if hasattr(e, 'trigger') and e.trigger is None: e.trigger = self.trigger_name if hasattr(e, 'rule_id') and e.rule_id is None: e.rule_id = self.rule_id raise e except PolicyError: raise # To filter out already-handled errors except Exception as e: raise ValidationError.caused_by(e)
def __init__(self, policy_json=None): self.gate_name = policy_json.get('gate') self.trigger_name = policy_json.get('trigger') self.rule_id = policy_json.get('id') # Convert to lower-case for case-insensitive matches self.trigger_params = { p.get('name').lower(): p.get('value') for p in policy_json.get('params') } action = policy_json.get('action', '').lower() try: self.action = GateAction.__members__[action] except KeyError: raise InvalidGateAction(gate=self.gate_name, trigger=self.trigger_name, rule_id=self.rule_id, action=action, valid_actions=filter( lambda x: not x.startswith('_'), GateAction.__dict__.keys())) self.error_exc = None self.errors = [] # Configure the trigger instance try: self.gate_cls = Gate.get_gate_by_name(self.gate_name) except KeyError: # Gate not found self.error_exc = GateNotFoundError( gate=self.gate_name, valid_gates=Gate.registered_gate_names(), rule_id=self.rule_id) self.configured_trigger = None raise self.error_exc try: selected_trigger_cls = self.gate_cls.get_trigger_named( self.trigger_name.lower()) except KeyError: self.error_exc = TriggerNotFoundError( valid_triggers=self.gate_cls.trigger_names(), trigger=self.trigger_name, gate=self.gate_name, rule_id=self.rule_id) self.configured_trigger = None raise self.error_exc try: try: self.configured_trigger = selected_trigger_cls( parent_gate_cls=self.gate_cls, rule_id=self.rule_id, **self.trigger_params) except [ TriggerNotFoundError, InvalidParameterError, ParameterValueInvalidError ] as e: # Error finding or initializing the trigger log.exception('Policy rule execution exception: {}'.format(e)) self.error_exc = e self.configured_trigger = None if hasattr(e, 'gate') and e.gate is None: e.gate = self.gate_name if hasattr(e, 'trigger') and e.trigger is None: e.trigger = self.trigger_name if hasattr(e, 'rule_id') and e.rule_id is None: e.rule_id = self.rule_id raise e except PolicyError: raise # To filter out already-handled errors except Exception as e: raise ValidationError.caused_by(e)
def __init__(self, bundle_json, tag=None): """ Build and initialize the bundle. If errors are encountered they are buffered until the end and all returned at once in an aggregated InitializationError to ensure that all errors can be presented back to the user, not just the first one. The exception to that rule is the version check on the bundle itself, which is returned directly if the UnsupportedVersionError is raised since parsing cannot proceed reliably. :param bundle_json: """ if not bundle_json: raise ValidationError('No bundle json received') self.verify_version(bundle_json) self.raw = bundle_json self.id = self.raw.get('id') self.name = self.raw.get('name') self.version = self.raw.get('version') self.comment = self.raw.get('comment') self.policies = {} self.whitelists = {} self.mapping = None self.init_errors = [] if tag: self.target_tag = tag else: self.target_tag = None try: # Build the mapping first, then build reachable policies and whitelists self.mapping = ExecutableMapping(self.raw.get('mappings', [])) # If building for a specific tag target, only build the mapped rules, else build all rules if self.target_tag: rule = self.mapping.execute(image_obj=None, tag=self.target_tag) if rule is not None: rules = [rule] self.mapping.mapping_rules = filter( lambda x: x == rule, self.mapping.mapping_rules) else: rules = [] else: rules = self.mapping.mapping_rules for rule in rules: try: # Build the specified policy for the rule policy = filter(lambda x: x['id'] == rule.policy_id, self.raw.get('policies', [])) if not policy: raise ReferencedObjectNotFoundError( reference_id=rule.policy_id, reference_type='policy') elif len(policy) > 1: raise DuplicateIdentifierFoundError( identifier=rule.policy_id, identifier_type='policy') self.policies[rule.policy_id] = ExecutablePolicy(policy[0]) except Exception as e: if isinstance(e, InitializationError): self.init_errors += e.causes else: self.init_errors.append(e) # Build the whitelists for the rule for wl in rule.whitelist_ids: try: whitelist = filter(lambda x: x['id'] == wl, self.raw.get('whitelists', [])) if not whitelist: raise ReferencedObjectNotFoundError( reference_id=wl, reference_type='whitelist') elif len(whitelist) > 1: raise DuplicateIdentifierFoundError( identifier=wl, identifier_type='whitelist') self.whitelists[wl] = ExecutableWhitelist(whitelist[0]) except Exception as e: if isinstance(e, InitializationError): self.init_errors += e.causes else: self.init_errors.append(e) except Exception as e: if isinstance(e, InitializationError): self.init_errors += e.causes else: self.init_errors.append(e)