Beispiel #1
0
class MetaDataView(Model):
    table = PolyModelType(MetaDataViewTable, serialize_when_none=False)
    sub_data = PolyModelType(MetaDataViewSubData, serialize_when_none=False)
    search = ListType(PolyModelType(BaseDynamicSearch),
                      serialize_when_none=False)
    widget = ListType(PolyModelType(BaseDynamicWidget),
                      serialize_when_none=False)
class BaseField(Model):
    type = StringType(choices=[
        "text", "state", "badge", "list", "dict", "datetime", "image", "enum"
    ],
                      serialize_when_none=False)
    options = PolyModelType([Model, DictType(PolyModelType(Model))],
                            serialize_when_none=False)
Beispiel #3
0
class CloudServiceResource(Model):
    provider = StringType(default="azure")
    cloud_service_type = StringType()
    cloud_service_group = StringType()
    tags = ListType(ModelType(Tags), serialize_when_none=False)
    data = PolyModelType(Model, default=lambda: {})
    reference = ModelType(ReferenceModel)
    region_code = StringType()
    _metadata = PolyModelType(CloudServiceMeta, serialize_when_none=False, serialized_name='metadata')
class BaseDynamicWidgetOptions(Model):
    value_options = PolyModelType([
        TextDyField, StateDyField, BadgeDyField, ListDyField, DictDyField,
        DateTimeDyField, ImageDyField, EnumDyField, SizeField, ProgressField
    ],
                                  serialize_when_none=False)
    name_options = PolyModelType([
        TextDyField, StateDyField, BadgeDyField, ListDyField, DictDyField,
        DateTimeDyField, ImageDyField, EnumDyField, SizeField, ProgressField
    ],
                                 serialize_when_none=False)
    chart_type = StringType(choices=('COLUMN', 'DONUT', 'TREEMAP'),
                            serialize_when_none=False)
Beispiel #5
0
class CloudServiceResource(Model):
    name = StringType(default="")
    provider = StringType(default="aws")
    account = StringType()
    instance_type = StringType(serialize_when_none=False)
    instance_size = FloatType(serialize_when_none=False)
    launched_at = StringType(serialize_when_none=False)
    cloud_service_type = StringType()
    cloud_service_group = StringType()
    data = PolyModelType(Model, default=lambda: {})
    tags = ListType(ModelType(CloudServiceResourceTags), default=[])
    reference = ModelType(ReferenceModel)
    region_code = StringType(serialize_when_none=False)
    _metadata = PolyModelType(CloudServiceMeta, serialize_when_none=False, serialized_name='metadata')
class Permission(Model):
    action = ListType(StringType(), default=[])
    resource = ListType(StringType(), default=[])
    effect = StringType(deserialize_from="Effect")
    condition = ListType(PolyModelType([Condition, _Condition]),
                         serialize_when_none=False)
    sid = StringType(deserialize_from="Sid", serialize_when_none=False)
Beispiel #7
0
class Scope(schematics.Model):

    company_id: str = StringType(required=True)
    """
    Historically, company_id=None meant global. Now, we should use support company id, same as with taxons.
    """
    project_id: Optional[str] = StringType()

    model_visibility: ModelVisibility = EnumType(
        ModelVisibility, default=ModelVisibility.available)
    """
    Every production consumer should not set this field. Set to experimental if you want to test new changes / models.
    """

    preaggregation_filters = PolyModelType(get_all_filter_clauses())
    """Optional pre-aggregation filters which determine scope of this Husky request"""
    @property
    def all_filters(self):
        """
        Get current preaggregation scope filters
        """
        return self.preaggregation_filters

    def __hash__(self) -> int:
        return hash('_'.join(
            str(part) for part in [
                self.project_id,
                self.company_id,
                self.model_visibility,
            ]))
Beispiel #8
0
class Relationship(Model):
    associated_role = AssociatedRole(required=True)
    relationship_type = RelationshipType(required=True)
    tenure = PolyModelType(Tenure, required=True)

    class Options:
        export_level = NOT_NONE
class ListDyFieldOptions(FieldViewOption):
    item = PolyModelType(
        [BadgeItemDyField, StateDyField, DateTimeDyField, DictDyField],
        serialize_when_none=False)
    sub_key = StringType(serialize_when_none=False)
    delimiter = StringType(serialize_when_none=False)
    link = StringType(serialize_when_none=False)
Beispiel #10
0
class EnumOptionDyField(FieldViewOption):
    items = DictType(PolyModelType([
        StateItemDyField, BadgeItemDyField, ImageItemDyField,
        DatetimeItemDyField
    ]),
                     serialize_when_none=False,
                     default={})
class ImageItemDyField(BaseField):
    type = StringType(default="image")
    options = PolyModelType(ImageDyFieldOptions, serialize_when_none=False)

    @classmethod
    def set(cls, options):
        return cls({'options': ImageDyFieldOptions(options)})
Beispiel #12
0
class InternalDataRequest(schematics.Model):
    """Internal representation of data request"""

    taxons: List[TaxonExpressionStr] = ListType(NonEmptyStringType,
                                                required=False,
                                                default=[])

    preaggregation_filters = PolyModelType(get_all_filter_clauses())

    order_by: List[TaxonDataOrder] = ListType(ModelType(TaxonDataOrder),
                                              default=list())

    limit: Optional[int] = IntType()

    offset: Optional[int] = IntType()

    properties: DataRequestProperties = ModelType(DataRequestProperties,
                                                  required=True)

    scope: Scope = ModelType(Scope, required=True)

    origin: Optional[DataRequestOrigin] = ModelType(DataRequestOrigin)

    physical_data_sources: Optional[List[str]] = ListType(NonEmptyStringType,
                                                          required=False)
    """
Beispiel #13
0
class ApiDataRequest(schematics.Model, ApiModelSchematics):
    """API representation of data request"""

    taxons: List[TaxonExpressionStr] = ListType(NonEmptyStringType,
                                                required=False,
                                                default=[])

    preaggregation_filters = PolyModelType(get_all_filter_clauses())

    order_by: List[TaxonDataOrder] = ListType(ModelType(TaxonDataOrder),
                                              default=list())

    limit: Optional[int] = IntType()

    offset: Optional[int] = IntType()

    properties: DataRequestProperties = ModelType(DataRequestProperties,
                                                  required=True)

    scope: ApiScope = ModelType(ApiScope, required=True)

    origin: Optional[DataRequestOrigin] = ModelType(DataRequestOrigin)

    def to_internal_model(self) -> 'InternalDataRequest':
        return InternalDataRequest(self.to_primitive())
class DatetimeItemDyField(BaseField):
    type = StringType(default="datetime")
    options = PolyModelType(DateTimeDyFieldOptions, serialize_when_none=False)

    @classmethod
    def set(cls, options):
        return cls({'options': DateTimeDyFieldOptions(options)})
Beispiel #15
0
def protocol_cfg(mapping, **kwargs):
    """
    Return an alternative protocol configuration type.

    Alternative protocol configurations allow only one from a selection of
    alternatives to be used. The model looks like this::

        protocol: <protocol name>
        conf: <configuration for the chosen protocol>

    schematics has PolyModelType which allows "conf" to be different models,
    but it must select the model to use based solely on the contents of "conf",
    which cannot be done with this construction. So create a new wrapper model
    for each protocol configuration model which also includes the "protocol"
    field and let PolyModelType choose from those.
    """

    models = []
    for protocol, model in mapping.items():
        wrapper = type(
            model.__name__ + "Wrapper", (Model, ), {
                "protocol": StringType(required=True, choices=[protocol]),
                "conf": ModelType(model, required=True),
            })
        mapping[protocol] = wrapper
        models.append(wrapper)

    def _claim(_, data):
        return mapping.get(data.get("protocol"))

    return PolyModelType(models, claim_function=_claim, **kwargs)
class BadgeDyField(BaseDynamicField):
    type = StringType(default="badge")
    options = PolyModelType(BadgeDyFieldOptions, serialize_when_none=False)

    @classmethod
    def data_source(cls, name, key, **kwargs):
        _data_source = {
            "key":
            key,
            "name":
            name,
            "options":
            BadgeDyFieldOptions({
                "background_color": "gray.200",
                "text_color": "gray.900"
            }),
        }

        if "options" in kwargs:
            _data_source.update(
                {"options": BadgeDyFieldOptions(kwargs.get("options"))})

        if "reference" in kwargs:
            _data_source.update({"reference": kwargs.get("reference")})

        return cls(_data_source)
class SimpleTableDynamicLayout(BaseLayoutField):
    type = StringType(default='simple-table')
    options = PolyModelType(SimpleTableLayoutOption)

    @classmethod
    def set(cls, name='', root_path=''):
        return cls({
            'name': name,
            'options': SimpleTableLayoutOption({'root_path': root_path})
        })

    @classmethod
    def set_fields(cls, name='', root_path=None, fields=[]):
        _options = cls._set_fields(fields, root_path=root_path)
        return cls({
            'name': name,
            'options': SimpleTableLayoutOption(_options)
        })

    @classmethod
    def set_tags(cls, name='Tags', root_path='data.tags', fields=None):
        if fields is None:
            fields = [
                TextDyField.data_source('Key', 'key'),
                TextDyField.data_source('Value', 'value'),
            ]
        return cls.set_fields(name, root_path, fields)
class BadgeDyField(BaseDynamicField):
    type = StringType(default="badge")
    options = PolyModelType(BadgeDyFieldOptions, serialize_when_none=False)

    @classmethod
    def data_source(cls, name, key, **kwargs):
        _data_source = {
            'key':
            key,
            'name':
            name,
            'options':
            BadgeDyFieldOptions({
                'background_color': 'gray.200',
                'text_color': 'gray.900'
            })
        }

        if 'options' in kwargs:
            _data_source.update(
                {'options': BadgeDyFieldOptions(kwargs.get('options'))})

        if 'reference' in kwargs:
            _data_source.update({'reference': kwargs.get('reference')})

        return cls(_data_source)
Beispiel #19
0
class MessageWrapper(Model):
    """Message wrapper allowing simple en/de-coding."""

    message = PolyModelType(tuple(
        map(lambda item: item[1], get_message_classes())),
                            claim_function=claim)
    """Wrapped message (inheriting from :py:class:`Message`)."""
class StateItemDyField(BaseField):
    type = StringType(default="state")
    options = PolyModelType(StateDyFieldOptions, serialize_when_none=False)

    @classmethod
    def set(cls, options):
        return cls({"options": StateDyFieldOptions(options)})
Beispiel #21
0
class ListDyField(BaseDynamicField):
    type = StringType(default="list")
    options = PolyModelType(ListDyFieldOptions, serialize_when_none=False)

    @classmethod
    def data_source(cls, name, key, **kwargs):
        _data_source = {'key': key, 'name': name}
        if 'default_badge' in kwargs:
            _default_badge = kwargs.get('default_badge')
            _list_options = {'delimiter': '  '}

            if 'type' in _default_badge and _default_badge.get('type') == 'outline':
                _list_options.update({'item': BadgeItemDyField.set({'outline_color': 'violet.500'})})
            elif 'type' in _default_badge and _default_badge.get('type') == 'inline':
                _list_options.update({'item': BadgeItemDyField.set({'background_color': 'violet.500'})})

            if 'sub_key' in _default_badge:
                _list_options.update({'sub_key': _default_badge.get('sub_key')})

            if 'delimiter' in _default_badge:
                _list_options.update({'delimiter': _default_badge.get('delimiter')})

            _data_source.update({'options': ListDyFieldOptions(_list_options)})

        if 'options' in kwargs:
            _data_source.update({'options': ListDyFieldOptions(kwargs.get('options'))})

        return cls(_data_source)
class RolePolicyDocument(Model):
    action = ListType(StringType(), deserialize_from="Action")
    condition = ListType(PolyModelType([Condition, _Condition]),
                         serialize_when_none=False)
    effect = ListType(StringType(), deserialize_from="Effect")
    principal = ListType(ModelType(PrincipalMeta),
                         deserialize_from="Principal")
    sid = ListType(StringType(), serialize_when_none=False)
class EnumDyField(BaseDynamicField):
    type = StringType(default="enum")
    options = DictType(PolyModelType([StateItemDyField, BadgeItemDyField, ImageItemDyField, DatetimeItemDyField]),
                       serialize_when_none=False,
                       default={})

    @classmethod
    def data_source(cls, name, key, **kwargs):
        _data_source = {'key': key, 'name': name}
        _default_badge = kwargs.get('default_badge', {})
        _default_state = kwargs.get('default_state', {})
        _default_outline_badge = kwargs.get('default_outline_badge', [])

        _options_dic = {}

        for _key in _default_outline_badge:
            _round_index = len(TYPE_BADGE)
            _index = _default_outline_badge.index(_key)
            _num = math.floor(_index/len(TYPE_BADGE))

            if _num > 0:
                _round_index = len(TYPE_BADGE)*_num

            if _round_index - 1 < _index:
                _index = _index - _round_index

            _options_dic[_key] = BadgeItemDyField.set({'outline_color': TYPE_BADGE[_index]})

        for _key in _default_badge:
            for _badge in _default_badge[_key]:
                _options_dic[_badge] = BadgeItemDyField.set({'background_color': _key})

        for _key in _default_state:
            for _state in _default_state[_key]:
                _state_options = {'icon': {'color': 'gray.400'}}

                if _key == 'safe':
                    _state_options = {'icon': {'color': 'green.500'}}
                elif _key == 'disable':
                    _state_options.update({'text_color': 'gray.400'})
                elif _key == 'warning':
                    _state_options = {'icon': {'color': 'yellow.500'}}
                elif _key == 'available':
                    _state_options = {'icon': {'color': 'blue.400'}}
                elif _key == 'alert':
                    _state_options = {'text_color': 'red.500', 'icon': {'color': 'red.500'}}

                _options_dic[_state] = StateItemDyField.set(_state_options)

        _data_source.update({'options': _options_dic})

        if 'options' in kwargs:
            _data_source.update({'options': kwargs.get('options')})

        if 'reference' in kwargs:
            _data_source.update({'reference': kwargs.get('reference')})

        return cls(_data_source)
class CloudServiceTypeResource(Model):
    name = StringType()
    provider = StringType()
    group = StringType()
    _metadata = PolyModelType(CloudServiceTypeMeta,
                              serialize_when_none=False,
                              serialized_name='metadata')
    labels = ListType(StringType(), serialize_when_none=False)
    tags = DictType(StringType, serialize_when_none=False)
Beispiel #25
0
class CloudServiceResponse(BaseResponse):
    match_rules = DictType(ListType(StringType), default={
        '1': ['reference.resource_id', 'provider', 'cloud_service_type', 'cloud_service_group']
    })
    options = DictType(StringType(), default={
        'update_mode': 'MERGE'
    })
    resource_type = StringType(default='inventory.CloudService')
    resource = PolyModelType(CloudServiceResource)
class BaseField(Model):
    type = StringType(
        choices=[
            "text",
            "state",
            "badge",
            "list",
            "dict",
            "datetime",
            "image",
            "enum",
            "progress",
            "size",
        ],
        serialize_when_none=False,
    )
    options = PolyModelType([Model, DictType(PolyModelType(Model))],
                            serialize_when_none=False)
    reference = ModelType(Reference, serialize_when_none=False)
class CloudServiceTypeResource(Model):
    name = StringType()
    provider = StringType(default='oracle_cloud')
    group = StringType()
    _metadata = PolyModelType(CloudServiceTypeMeta, serialize_when_none=False, serialized_name='metadata')
    labels = ListType(StringType(), serialize_when_none=False)
    tags = DictType(StringType, serialize_when_none=False)
    is_primary = BooleanType(default=False)
    is_major = BooleanType(default=False)
    resource_type = StringType(default='inventory.CloudService')
    service_code = StringType(serialize_when_none=False)
Beispiel #28
0
class TextDyField(BaseDynamicField):
    type = StringType(default="text")
    options = PolyModelType(TextDyFieldOptions, serialize_when_none=False)

    @classmethod
    def data_source(cls, name, key, **kwargs):
        _data_source = {'key': key, 'name': name}
        if 'options' in kwargs:
            _data_source.update({'options': TextDyFieldOptions(kwargs.get('options'))})

        return cls(_data_source)
Beispiel #29
0
 class Schema:
     id = String(default=randuuid)
     asset_id = String(required=False)
     timestamp_utc = String(default=datetime.now(timezone.utc).isoformat())
     description = String()
     event_source_name = String()
     likelihood_indicator = String()
     details = PolyModelType(
         [ObservatoryScore, VulnerabilitySummary, DastVulnerabilities],
         claim_function=claim_func,
     )
class ListDynamicLayout(BaseLayoutField):
    type = StringType(default='list')
    options = PolyModelType(ListLayoutOption)

    @classmethod
    def set(cls, name='', layouts=[]):
        return cls(name=name, options=ListLayoutOption({'layouts': layouts}))

    @classmethod
    def set_layouts(cls, name='', layouts=[]):
        return cls({'name': name, 'options': ListLayoutOption({'layouts': layouts})})