Beispiel #1
0
    def get_condition(self, expression: Expression, remainder: List[str]) -> Any:
        if len(remainder) > 1:
            raise FieldNotQueryableException(
                f"Attribute doesn't have subfields: {'.'.join(remainder[1:])}"
            )

        if remainder:
            attribute_key = remainder[0]
        else:
            raise UnsupportedGrammarException("Missing attribute key (meta.<key>:)")

        metakey_definition = MetakeyDefinition.query_for_read(
            key=attribute_key, include_hidden=True
        ).first()

        if metakey_definition is None:
            raise ObjectNotFoundException(f"No such attribute: {attribute_key}")

        if (
            metakey_definition.hidden
            and expression.has_wildcard()
            and not g.auth_user.has_rights(Capabilities.reading_all_attributes)
        ):
            raise FieldNotQueryableException(
                "Wildcards are not allowed for hidden attributes"
            )

        value = get_term_value(expression)
        if expression.has_wildcard():
            value_condition = Metakey.value.like(value)
        else:
            value_condition = Metakey.value == value

        return self.column.any(and_(Metakey.key == attribute_key, value_condition))
Beispiel #2
0
    def put(self, key):
        """
        ---
        summary: Create/update attribute key
        description: |
            Creates or updates attribute key definition.

            Requires `managing_attributes` capability.
        security:
            - bearerAuth: []
        tags:
            - attribute
        parameters:
            - in: path
              name: key
              schema:
                type: string
              description: Attribute key
        requestBody:
            description: Attribute key definition
            content:
              application/json:
                schema: MetakeyDefinitionItemRequestBodySchema
        responses:
            200:
                description: When metakey definition is successfully added
                content:
                  application/json:
                    schema: MetakeyDefinitionManageItemResponseSchema
            400:
                description: |
                    When one of attribute definition fields is missing or incorrect.
            403:
                description: When user doesn't have `managing_attributes` capability.
        """
        schema = MetakeyDefinitionItemRequestArgsSchema()
        args_obj = load_schema({"key": key}, schema)

        schema = MetakeyDefinitionItemRequestBodySchema()
        obj = loads_schema(request.get_data(as_text=True), schema)

        metakey_definition = MetakeyDefinition(
            key=args_obj["key"],
            url_template=obj["url_template"],
            label=obj["label"],
            description=obj["description"],
            hidden=obj["hidden"],
        )
        metakey_definition = db.session.merge(metakey_definition)
        db.session.commit()

        schema = MetakeyDefinitionManageItemResponseSchema()
        return schema.dump(metakey_definition)
def configure():
    """
    Configure 'drakvuf' attribute key in MWDB.

    This will be called by 'mwdb configure' command.
    """
    logger.info("Configuring 'drakvuf' attribute key.")
    attribute = MetakeyDefinition(
        key="drakvuf",
        url_template=f"{config.drakvuf.drakvuf_url}/progress/$value",
        label="Drakvuf analysis",
        description="Reference to the Drakvuf analysis for file")
    db.session.merge(attribute)
    db.session.commit()
Beispiel #4
0
    def get(self, access):
        """
        ---
        summary: Get list of attribute keys
        description: |
            Returns list of attribute keys which currently authenticated user
            can read or set.
        security:
            - bearerAuth: []
        tags:
            - attribute
        parameters:
            - in: path
              name: access
              schema:
                type: string
                enum: [read, set]
              description: Type of desired access
        responses:
            200:
                description: List of attribute keys and definitions
                content:
                  application/json:
                    schema: MetakeyDefinitionListResponseSchema
            400:
                description: When used unknown access type (other than read or set)
        """
        if access == "read":
            metakeys = MetakeyDefinition.query_for_read()
        elif access == "set":
            metakeys = MetakeyDefinition.query_for_set()
        else:
            raise BadRequest(f"Unknown desired access type '{access}'")

        metakeys = metakeys.order_by(MetakeyDefinition.key).all()
        schema = MetakeyDefinitionListResponseSchema()
        return schema.dump({"metakeys": metakeys})
def configure():
    logger.info("Configuring 'karton' attribute key.")
    attribute = MetakeyDefinition(
        key="karton",
        url_template="",
        label="Karton analysis",
        description="Reference to the Karton analysis for object")
    db.session.merge(attribute)
    db.session.commit()

    logger.info("Updating permissions for admin account.")
    admin_group = Group.get_by_name("admin")
    if KartonCapabilities.karton_manage not in admin_group.capabilities:
        admin_group.capabilities.append(KartonCapabilities.karton_manage)
    db.session.commit()
Beispiel #6
0
    def create_object(self, params):
        params = dict(params)

        # Validate parent object
        if params["parent"] is not None:
            if not g.auth_user.has_rights(Capabilities.adding_parents):
                raise Forbidden("You are not permitted to link with parent")

            parent_object = Object.access(params["parent"])

            if parent_object is None:
                raise NotFound("Parent object not found")
        else:
            parent_object = None

        # Validate metakeys
        metakeys = params["metakeys"]
        for metakey in params["metakeys"]:
            key = metakey["key"]
            if not MetakeyDefinition.query_for_set(key).first():
                raise NotFound(
                    f"Metakey '{key}' not defined or insufficient "
                    "permissions to set that one"
                )

        # Validate upload_as argument
        share_with = get_shares_for_upload(params["upload_as"])

        item, is_new = self._create_object(params, parent_object, share_with, metakeys)

        try:
            db.session.commit()

            if is_new:
                hooks.on_created_object(item)
                self.on_created(item)
            else:
                hooks.on_reuploaded_object(item)
                self.on_reuploaded(item)
        finally:
            item.release_after_upload()

        logger.info(
            f"{self.ObjectType.__name__} added",
            extra={"dhash": item.dhash, "is_new": is_new},
        )
        schema = self.ItemResponseSchema()
        return schema.dump(item)
Beispiel #7
0
    def create_object(self, params):
        params = dict(params)

        # Validate parent object
        if params["parent"] is not None:
            if not g.auth_user.has_rights(Capabilities.adding_parents):
                raise Forbidden("You are not permitted to link with parent")

            parent_object = Object.access(params["parent"])

            if parent_object is None:
                raise NotFound("Parent object not found")
        else:
            parent_object = None

        # Validate metakeys
        metakeys = params["metakeys"]
        for metakey in params["metakeys"]:
            key = metakey["key"]
            if not MetakeyDefinition.query_for_set(key).first():
                raise NotFound(f"Metakey '{key}' not defined or insufficient "
                               "permissions to set that one")

        # Validate upload_as argument
        upload_as = params["upload_as"]
        if upload_as == "*":
            # If '*' is provided: share with all user's groups except 'public'
            share_with = [
                group for group in g.auth_user.groups if group.name != "public"
            ]
        else:
            share_group = Group.get_by_name(upload_as)
            # Does group exist?
            if share_group is None:
                raise NotFound(f"Group {upload_as} doesn't exist")
            # Has user access to group?
            if share_group not in g.auth_user.groups and not g.auth_user.has_rights(
                    Capabilities.sharing_objects):
                raise NotFound(f"Group {upload_as} doesn't exist")
            # Is group pending?
            if share_group.pending_group is True:
                raise NotFound(f"Group {upload_as} is pending")
            share_with = [share_group, Group.get_by_name(g.auth_user.login)]

        item, is_new = self._create_object(params, parent_object, share_with,
                                           metakeys)

        db.session.commit()

        if is_new:
            hooks.on_created_object(item)
            self.on_created(item)
        else:
            hooks.on_reuploaded_object(item)
            self.on_reuploaded(item)

        logger.info(f'{self.ObjectType.__name__} added',
                    extra={
                        'dhash': item.dhash,
                        'is_new': is_new
                    })
        schema = self.ItemResponseSchema()
        return schema.dump(item)