Ejemplo n.º 1
0
    def cached_principal_roles(self, parent, principal, groups, level):
        # Redefine it to get global roles
        cache = self.cache(parent, level)
        try:
            cache_principal_roles = cache.principal_roles
        except AttributeError:
            cache_principal_roles = cache.principal_roles = {}
        try:
            return cache_principal_roles[principal]
        except KeyError:
            pass

        # We reached the end so we go to see the global ones
        if parent is None:
            # Then the code roles
            roles = self.global_principal_roles(principal, groups)

            cache_principal_roles[principal] = roles
            return roles

        roles = self.cached_principal_roles(getattr(parent, "__parent__", None), principal, groups, "p")

        # We check the local map of roles
        prinrole = IPrincipalRoleMap(parent, None)

        if prinrole:
            roles = roles.copy()
            for role, setting in prinrole.get_roles_for_principal(principal):
                roles[role] = level_setting_as_boolean(level, setting)
            for group in groups:
                for role, setting in prinrole.get_roles_for_principal(group):
                    roles[role] = level_setting_as_boolean(level, setting)

        cache_principal_roles[principal] = roles
        return roles
Ejemplo n.º 2
0
async def sharing_get(context, request):
    roleperm = IRolePermissionMap(context)
    prinperm = IPrincipalPermissionMap(context)
    prinrole = IPrincipalRoleMap(context)
    result = {
        'local': {},
        'inherit': []
    }
    result['local']['roleperm'] = roleperm._bycol
    result['local']['prinperm'] = prinperm._bycol
    result['local']['prinrole'] = prinrole._bycol
    for obj in iter_parents(context):
        roleperm = IRolePermissionMap(obj, None)
        url_factory = query_multi_adapter((obj, request), IAbsoluteURL)
        if roleperm is not None and url_factory is not None:
            prinperm = IPrincipalPermissionMap(obj)
            prinrole = IPrincipalRoleMap(obj)
            result['inherit'].append({
                '@id': url_factory(),
                'roleperm': roleperm._bycol,
                'prinperm': prinperm._bycol,
                'prinrole': prinrole._bycol,
            })
    await notify(ObjectPermissionsViewEvent(context))
    return result
Ejemplo n.º 3
0
    def cached_principals(self, parent, roles, permission, level):
        """Get the roles for a specific permission.

        Global + Local + Code
        """
        cache = self.cache(parent)
        try:
            cache_principals = cache.principals
        except AttributeError:
            cache_principals = cache.principals = {}
        try:
            return cache_principals[permission]
        except KeyError:
            pass

        if parent is None:
            principals = dict([
                (role, 1)
                for (role,
                     setting) in code_principals_for_permission(permission)
                if setting is Allow
            ])
            cache_principals[permission] = principals
            return principals

        principals = self.cached_principals(
            getattr(parent, '__parent__', None), roles, permission, 'p')
        prinperm = IPrincipalPermissionMap(parent, None)
        if prinperm:
            principals = principals.copy()
            for principal, setting in prinperm.get_principals_for_permission(
                    permission):
                if setting is Allow:
                    principals[principal] = 1
                elif setting is AllowSingle and level == 'o':
                    principals[principal] = 1
                elif setting is Deny and principal in principals:
                    del principals[principal]

        prinrole = IPrincipalRoleMap(parent, None)
        if prinrole:
            for role in roles:
                for principal, setting in prinrole.get_principals_for_role(
                        role):
                    if setting is Allow:
                        principals[principal] = 1
                    elif setting is AllowSingle and level == 'o':
                        principals[principal] = 1
                    elif setting is Deny and principal in principals:
                        del principals[principal]

        if level != 'o':
            # Only cache on non 1rst level queries needs new way
            cache_principals[permission] = principals
        return principals
Ejemplo n.º 4
0
def cached_principals(parent: IBaseObject, roles: typing.List[str],
                      permission: str, level: str) -> typing.Dict[str, int]:
    """Get the roles for a specific permission.

    Global + Local + Code
    """
    try:
        cache = parent.__volatile__.setdefault('security_cache', {})
    except AttributeError:
        cache = {}
    try:
        cache_principals = cache['principals']
    except KeyError:
        cache_principals = cache['principals'] = {}
    try:
        return cache_principals[permission + level]
    except KeyError:
        pass

    if parent is None:
        principals = dict([
            (role, 1)
            for (role, setting) in code_principals_for_permission(permission)
            if setting is Allow
        ])
        cache_principals[permission + level] = principals
        return principals

    principals = cached_principals(getattr(parent, '__parent__', None), roles,
                                   permission, 'p')
    prinperm = IPrincipalPermissionMap(parent, None)
    if prinperm:
        principals = principals.copy()
        for principal, setting in prinperm.get_principals_for_permission(
                permission):
            if setting is Allow:
                principals[principal] = 1
            elif setting is AllowSingle and level == 'o':
                principals[principal] = 1
            elif setting is Deny and principal in principals:
                del principals[principal]

    prinrole = IPrincipalRoleMap(parent, None)
    if prinrole:
        for role in roles:
            for principal, setting in prinrole.get_principals_for_role(role):
                if setting is Allow:
                    principals[principal] = 1
                elif setting is AllowSingle and level == 'o':
                    principals[principal] = 1
                elif setting is Deny and principal in principals:
                    del principals[principal]

    cache_principals[permission + level] = principals
    return principals
Ejemplo n.º 5
0
    def cached_principals(self, parent, roles, permission, level):
        """Get the roles for a specific permission.

        Global + Local + Code
        """
        cache = self.cache(parent)
        try:
            cache_principals = cache.principals
        except AttributeError:
            cache_principals = cache.principals = {}
        try:
            return cache_principals[permission]
        except KeyError:
            pass

        if parent is None:
            principals = dict(
                [(role, 1)
                 for (role, setting) in code_principals_for_permission(permission)
                 if setting is Allow])
            cache_principals[permission] = principals
            return principals

        principals = self.cached_principals(
            getattr(parent, '__parent__', None),
            roles,
            permission, 'p')
        prinperm = IPrincipalPermissionMap(parent, None)
        if prinperm:
            principals = principals.copy()
            for principal, setting in prinperm.get_principals_for_permission(permission):
                if setting is Allow:
                    principals[principal] = 1
                elif setting is AllowSingle and level == 'o':
                    principals[principal] = 1
                elif setting is Deny and principal in principals:
                    del principals[principal]

        prinrole = IPrincipalRoleMap(parent, None)
        if prinrole:
            for role in roles:
                for principal, setting in prinrole.get_principals_for_role(role):
                    if setting is Allow:
                        principals[principal] = 1
                    elif setting is AllowSingle and level == 'o':
                        principals[principal] = 1
                    elif setting is Deny and principal in principals:
                        del principals[principal]

        if level != 'o':
            # Only cache on non 1rst level queries needs new way
            cache_principals[permission] = principals
        return principals
Ejemplo n.º 6
0
def settings_for_object(ob):
    """Analysis tool to show all of the grants to a process
    """
    result = []
    while ob is not None:
        data = {}
        result.append({getattr(ob, '__name__', None) or '(no name)': data})

        principal_permissions = IPrincipalPermissionMap(ob, None)
        if principal_permissions is not None:
            settings = principal_permissions.get_principals_and_permissions()
            settings.sort()
            data['prinperm'] = [
                {'principal': pr, 'permission': p, 'setting': s}
                for (p, pr, s) in settings]

        principal_roles = IPrincipalRoleMap(ob, None)
        if principal_roles is not None:
            settings = principal_roles.get_principals_and_roles()
            data['prinrole'] = [
                {'principal': p, 'role': r, 'setting': s}
                for (r, p, s) in settings]

        role_permissions = IRolePermissionMap(ob, None)
        if role_permissions is not None:
            settings = role_permissions.get_roles_and_permissions()
            data['roleperm'] = [
                {'permission': p, 'role': r, 'setting': s}
                for (p, r, s) in settings]

        ob = getattr(ob, '__parent__', None)

    data = {}
    result.append({'system': data})

    settings = principal_permission_manager.get_principals_and_permissions()
    settings.sort()
    data['prinperm'] = [
        {'principal': pr, 'permission': p, 'setting': s}
        for (p, pr, s) in settings]

    settings = principal_role_manager.get_principals_and_roles()
    data['prinrole'] = [
        {'principal': p, 'role': r, 'setting': s}
        for (r, p, s) in settings]

    settings = role_permission_manager.get_roles_and_permissions()
    data['roleperm'] = [
        {'permission': p, 'role': r, 'setting': s}
        for (p, r, s) in settings]

    return result
Ejemplo n.º 7
0
def get_owners(obj):
    try:
        prinrole = IPrincipalRoleMap(obj)
    except TypeError:
        return []
    owners = []
    for user, roles in prinrole._bycol.items():
        for role in roles:
            if role == 'guillotina.Owner':
                owners.append(user)
    return owners
Ejemplo n.º 8
0
    def cached_principal_roles(self, parent, principal, groups, level):
        # Redefine it to get global roles
        cache = self.cache(parent)
        try:
            cache_principal_roles = cache.principal_roles
        except AttributeError:
            cache_principal_roles = cache.principal_roles = {}
        try:
            return cache_principal_roles[principal]
        except KeyError:
            pass

        # We reached the end so we go to see the global ones
        if parent is None:
            # Then the code roles
            roles = self.global_principal_roles(principal, groups)

            cache_principal_roles[principal] = roles
            return roles

        roles = self.cached_principal_roles(
            getattr(parent, '__parent__', None),
            principal,
            groups,
            'p')

        # We check the local map of roles
        prinrole = IPrincipalRoleMap(parent, None)

        if prinrole:
            roles = roles.copy()
            for role, setting in prinrole.get_roles_for_principal(
                    principal):
                roles[role] = level_setting_as_boolean(level, setting)
            for group in groups:
                for role, setting in prinrole.get_roles_for_principal(
                        group):
                    roles[role] = level_setting_as_boolean(level, setting)

        cache_principal_roles[principal] = roles
        return roles
Ejemplo n.º 9
0
async def sharing_get(context, request):
    roleperm = IRolePermissionMap(context)
    prinperm = IPrincipalPermissionMap(context)
    prinrole = IPrincipalRoleMap(context)
    result = {"local": {}, "inherit": []}
    result["local"]["roleperm"] = roleperm._bycol
    result["local"]["prinperm"] = prinperm._bycol
    result["local"]["prinrole"] = prinrole._bycol
    for obj in iter_parents(context):
        roleperm = IRolePermissionMap(obj, None)
        url = get_object_url(obj, request)
        if roleperm is not None and url is not None:
            prinperm = IPrincipalPermissionMap(obj)
            prinrole = IPrincipalRoleMap(obj)
            result["inherit"].append({
                "@id": url,
                "roleperm": roleperm._bycol,
                "prinperm": prinperm._bycol,
                "prinrole": prinrole._bycol,
            })
    await notify(ObjectPermissionsViewEvent(context))
    return result
Ejemplo n.º 10
0
def get_owners(obj) -> list:
    try:
        prinrole = IPrincipalRoleMap(obj)
    except TypeError:
        return []
    owners = []
    for user, roles in prinrole._bycol.items():
        for role in roles:
            if role == 'guillotina.Owner':
                owners.append(user)
    if len(owners) == 0 and getattr(obj, '__parent__', None) is not None:
        # owner can be parent if none found on current object
        return get_owners(obj.__parent__)
    return owners
Ejemplo n.º 11
0
def get_owners(obj: IResource) -> list:
    """
    Return owners of an object

    :param obj: object to get path from
    """
    try:
        prinrole = IPrincipalRoleMap(obj)
    except TypeError:
        return []
    owners = []
    for user, roles in prinrole._bycol.items():
        for role in roles:
            if role == "guillotina.Owner":
                owners.append(user)
    if len(owners) == 0 and getattr(obj, "__parent__", None) is not None:
        # owner can be parent if none found on current object
        return get_owners(obj.__parent__)
    return owners
Ejemplo n.º 12
0
async def grantinfo(context, request):
    """ principals -> roles """
    search = request.query.get("search")
    if search is not None:
        search = search.lower()

    result = {"available_roles": [], "entries": []}

    # Inherit
    inheritMap = IInheritPermissionMap(context)
    permissions = inheritMap.get_locked_permissions()
    if len(permissions) > 0:
        blocked_permissions = permissions
        result["inherit"] = False
    else:
        result["inherit"] = True

    # Roles
    roles = local_roles()
    valid_roles = [
        role for role in roles
        if role in app_settings.get("available_roles", [])
    ]
    for role in valid_roles:
        role_obj = get_utility(IRole, name=role)
        result["available_roles"].append({
            "id": role,
            "title": role_obj.title,
            "description": role_obj.description
        })

    prinrole = IPrincipalRoleMap(context)
    settings = [
        setting for setting in prinrole.get_principals_and_roles()
        if setting[0] in valid_roles
    ]
    valid_settings = {}
    default_roles = {role: None for role in valid_roles}

    try:
        container = get_current_container()
        users = await container.async_get("users")
        groups = await container.async_get("groups")
    except (AttributeError, KeyError, ContainerNotFound):
        return None

    for data in settings:
        if data[1] not in valid_settings:
            user = await users.async_get(data[1])
            if user:
                valid_settings[data[1]] = {
                    "id": data[1],
                    "disabled": user.disabled,
                    "login": None,
                    "roles": deepcopy(default_roles),
                    "title": user.name,
                    "type": "user",
                    "origin": "dbusers",
                }
            else:
                group = await groups.async_get(data[1])
                if group:
                    valid_settings[data[1]] = {
                        "id": data[1],
                        "disabled": group.disabled,
                        "login": None,
                        "roles": deepcopy(default_roles),
                        "title": group.name,
                        "type": "group",
                        "origin": "dbusers",
                    }
                else:
                    valid_settings[data[1]] = {
                        "id": data[1],
                        "disabled": False,
                        "login": None,
                        "roles": deepcopy(default_roles),
                        "title": data[1],
                        "type": "user",
                        "origin": "system",
                    }
        valid_settings[data[1]]["roles"].update({data[0]: data[2]})

    result["entries"] = list(valid_settings.values())

    if search is not None:
        catalog = query_utility(ICatalogUtility)
        query_result = await catalog.search(container,
                                            {"type_name": ["User", "Group"]})
        for obj in query_result["items"]:
            ident = obj.get("id", "")
            if search in ident.lower() and ident not in valid_settings:
                result["entries"].append({
                    "id": ident,
                    "disabled": False,
                    "login": None,
                    "roles": deepcopy(default_roles),
                    "title": obj.get("title", ""),
                    "type": obj.get("type_name").lower(),
                })

    return result
Ejemplo n.º 13
0
def settings_for_object(ob):
    """Analysis tool to show all of the grants to a process
    """
    result = []

    locked_permissions = []
    while ob is not None:
        data = {}
        result.append({getattr(ob, "__name__", None) or "(no name)": data})

        principal_permissions = IPrincipalPermissionMap(ob, None)
        if principal_permissions is not None:
            settings = principal_permissions.get_principals_and_permissions()
            settings.sort()
            data["prinperm"] = [{
                "principal": pr,
                "permission": p,
                "setting": s
            } for (p, pr, s) in settings]

        principal_roles = IPrincipalRoleMap(ob, None)
        if principal_roles is not None:
            settings = principal_roles.get_principals_and_roles()
            data["prinrole"] = [{
                "principal": p,
                "role": r,
                "setting": s
            } for (r, p, s) in settings]

        role_permissions = IRolePermissionMap(ob, None)
        if role_permissions is not None:
            settings = role_permissions.get_roles_and_permissions()
            data["roleperm"] = [{
                "permission": p,
                "role": r,
                "setting": s
            } for (p, r, s) in settings if p not in locked_permissions]

        inherit_permissions = IInheritPermissionMap(ob)
        if inherit_permissions is not None:
            settings = inherit_permissions.get_locked_permissions()
            data["perminhe"] = []
            for (p, s) in settings:
                if s is Deny:
                    locked_permissions.append(p)
                data["perminhe"].append({"permission": p, "setting": s})

        ob = getattr(ob, "__parent__", None)

    data = {}
    result.append({"system": data})

    settings = principal_permission_manager.get_principals_and_permissions()
    settings.sort()
    data["prinperm"] = [{
        "principal": pr,
        "permission": p,
        "setting": s
    } for (p, pr, s) in settings]

    settings = principal_role_manager.get_principals_and_roles()
    data["prinrole"] = [{
        "principal": p,
        "role": r,
        "setting": s
    } for (r, p, s) in settings]

    settings = role_permission_manager.get_roles_and_permissions()
    data["roleperm"] = [{
        "permission": p,
        "role": r,
        "setting": s
    } for (p, r, s) in settings if p not in locked_permissions]

    return result
Ejemplo n.º 14
0
def settings_for_object(ob):
    """Analysis tool to show all of the grants to a process
    """
    result = []

    locked_permissions = []
    while ob is not None:
        data = {}
        result.append({getattr(ob, '__name__', None) or '(no name)': data})

        principal_permissions = IPrincipalPermissionMap(ob, None)
        if principal_permissions is not None:
            settings = principal_permissions.get_principals_and_permissions()
            settings.sort()
            data['prinperm'] = [
                {'principal': pr, 'permission': p, 'setting': s}
                for (p, pr, s) in settings]

        principal_roles = IPrincipalRoleMap(ob, None)
        if principal_roles is not None:
            settings = principal_roles.get_principals_and_roles()
            data['prinrole'] = [
                {'principal': p, 'role': r, 'setting': s}
                for (r, p, s) in settings]

        role_permissions = IRolePermissionMap(ob, None)
        if role_permissions is not None:
            settings = role_permissions.get_roles_and_permissions()
            data['roleperm'] = [
                {'permission': p, 'role': r, 'setting': s}
                for (p, r, s) in settings if p not in locked_permissions]

        inherit_permissions = IInheritPermissionMap(ob)
        if inherit_permissions is not None:
            settings = inherit_permissions.get_locked_permissions()
            data['perminhe'] = []
            for (p, s) in settings:
                if s is Deny:
                    locked_permissions.append(p)
                data['perminhe'].append({'permission': p, 'setting': s})

        ob = getattr(ob, '__parent__', None)

    data = {}
    result.append({'system': data})

    settings = principal_permission_manager.get_principals_and_permissions()
    settings.sort()
    data['prinperm'] = [
        {'principal': pr, 'permission': p, 'setting': s}
        for (p, pr, s) in settings]

    settings = principal_role_manager.get_principals_and_roles()
    data['prinrole'] = [
        {'principal': p, 'role': r, 'setting': s}
        for (r, p, s) in settings]

    settings = role_permission_manager.get_roles_and_permissions()
    data['roleperm'] = [
        {'permission': p, 'role': r, 'setting': s}
        for (p, r, s) in settings if p not in locked_permissions]

    return result