\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7 \8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh \00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€ \00 $\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95 59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9 C/// File Manager

File Manager

Path: /opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/rpc_tools/

Viewing File: lookup.py

import functools
import inspect
from typing import Any

from defence360agent.contracts.config import UserType
from defence360agent.utils import Scope

from .exceptions import RpcError

_RPC_MARK = "__rpc_command"


class DuplicateHandlerError(Exception):
    pass


class NotCoroutineError(Exception):
    pass


class Endpoints:
    """Endpoints class implements registration and lookup for functions
    implementing RPC calls."""

    SCOPE = Scope.AV_IM360
    APPLICABLE_USER_TYPES = set()  # type: Set[str]
    __COMMAND_MAP = {
        UserType.ROOT: {},
        UserType.NON_ROOT: {},
    }  # type: Dict[str, Dict]
    _subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls._subclasses.append(cls)

    @classmethod
    def get_active_endpoints(cls):
        # consider endpoint as active if it has at least one RPC call handler
        active_endpoints = []
        for subcls in cls._subclasses:
            rpc_handlers = inspect.getmembers(
                subcls, lambda item: getattr(item, _RPC_MARK, None)
            )
            if rpc_handlers:
                active_endpoints.append(subcls)
        return active_endpoints

    def __init__(self, sink):
        self._sink = sink

    @classmethod
    async def route_to_endpoint(cls, request, sink, user=UserType.ROOT) -> Any:
        """Find appropriate class and function within that class that
        implements processing for request based on supplied 'command' within.

        Call that (async) function and return its result.

        If target class/function for given request['command'] is not found then
        RpcError exception is raised."""
        command = request["command"]
        key = tuple(command)
        if key not in cls.__COMMAND_MAP[user]:
            raise RpcError(
                'Endpoint not found for RPC method "%s"'
                % " ".join(request["command"])
            )
        cls_handler, handler_name = cls.__COMMAND_MAP[user][key]
        handler = getattr(cls_handler(sink), handler_name)
        return await handler(**request["params"])

    @classmethod
    def register_rpc_handlers(cls) -> None:
        """Registers RPC handlers for all functions within a class.

        Functions should be decorated with @bind('command', ...)."""
        for name in dir(cls):
            if name.startswith("_"):
                continue
            attr = getattr(cls, name)
            command = getattr(attr, _RPC_MARK, None)
            if command is None:
                continue
            if not inspect.iscoroutinefunction(attr):
                raise NotCoroutineError("Must be a coroutine")
            for user_type in cls.APPLICABLE_USER_TYPES:
                if command in cls.__COMMAND_MAP[user_type]:
                    msg = (
                        "Duplicate handlers for command {} ({}): {} and {}"
                        .format(
                            command,
                            user_type,
                            cls.__COMMAND_MAP[user_type][command],
                            attr,
                        )
                    )
                    raise DuplicateHandlerError(msg)
                cls.__COMMAND_MAP[user_type][command] = (cls, name)

    @classmethod
    def reset_rpc_handlers(cls):
        """Clears all previously made registrations."""
        for user_type in {UserType.NON_ROOT, UserType.ROOT}:
            cls.__COMMAND_MAP[user_type] = {}


class CommonEndpoints(Endpoints):
    """Endpoints available both for root and non root users."""

    APPLICABLE_USER_TYPES = {UserType.NON_ROOT, UserType.ROOT}


class RootEndpoints(Endpoints):
    """Endpoints available only for root user."""

    APPLICABLE_USER_TYPES = {UserType.ROOT}


class UserOnlyEndpoints(Endpoints):
    """Endpoints available only for non root users."""

    APPLICABLE_USER_TYPES = {UserType.NON_ROOT}


LOOKUP_ASSIGNMENTS = functools.WRAPPER_ASSIGNMENTS + (_RPC_MARK,)


def wraps(
    wrapped, assigned=LOOKUP_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES
):
    """Decorator replacing functools.wraps for rpc handlers"""
    return functools.partial(
        functools.update_wrapper,
        wrapped=wrapped,
        assigned=assigned,
        updated=updated,
    )


def bind(*command):
    """Mark a function as processing RPC calls for command."""

    def decorator(func):
        setattr(func, _RPC_MARK, command)
        return func

    return decorator