Exemple #1
0
def allow_root_access(request, context):
    """
    Adds ALL_PERMISSIONS to every resource if user has 'root_permission'
    """
    if getattr(request, 'user'):
        for perm in permission_to_pyramid_acls(request.user.permissions):
            if perm[2] == 'root_administration':
                context.__acl__.append((perm[0], perm[1], ALL_PERMISSIONS))
Exemple #2
0
def allow_root_access(request, context):
    """
    Adds ALL_PERMISSIONS to every resource if user has 'root_permission'
    """
    if getattr(request, "user"):
        permissions = UserService.permissions(request.user)
        for perm in permission_to_pyramid_acls(permissions):
            if perm[2] == "root_administration":
                context.__acl__.append((perm[0], perm[1], ALL_PERMISSIONS))
 def __init__(self, request):
     self.__acl__ = [(Allow, Authenticated, u'view'), ]
     # general page factory - append custom non resource permissions
     # request.user object from cookbook recipie
     if request.user:
         #for perm in request.user.permissions:
         #    self.__acl__.append((Allow, perm.user.id, perm.perm_name,))
         # or you could do
         for outcome, perm_user, perm_name in permission_to_pyramid_acls(
                 request.user.permissions):
             self.__acl__.append((outcome, perm_user, perm_name))
    def __init__(self, request):
        self.__acl__ = []
        rid = request.matchdict.get("resource_id")

        if not rid:
            raise HTTPNotFound()
        self.resource = Resource.by_resource_id(rid)
        if not self.resource:
            raise HTTPNotFound()
        if self.resource and request.user:
            # append basic resource acl that gives all permissions to owner
            self.__acl__ = self.resource.__acl__
            # append permissions that current user may have for this context resource
            permissions = self.resource.perms_for_user(request.user)
            for outcome, perm_user, perm_name in permission_to_pyramid_acls(
                    permissions):
                self.__acl__.append((outcome, perm_user, perm_name,))
Exemple #5
0
    def __init__(self, request):
        self.__acl__ = []
        # general page factory - append custom non resource permissions
        if getattr(request, 'user'):
            permissions = UserService.permissions(request.user,
                                                  db_session=request.dbsession)
            has_admin_panel_access = False
            panel_perms = ['admin_panel', ALL_PERMISSIONS]
            for outcome, perm_user, perm_name in permission_to_pyramid_acls(
                    permissions):
                perm_tuple = rewrite_root_perm(outcome, perm_user, perm_name)
                if perm_tuple[0] is Allow and perm_tuple[2] in panel_perms:
                    has_admin_panel_access = True
                self.__acl__.append(perm_tuple)

            # users have special permission called `admin_panel`
            # it should be prerequisite for other `admin*` permissions
            # if it is not present let's deny other admin permissions
            if not has_admin_panel_access:
                self.__acl__ = list(
                    filter(filter_admin_panel_perms, self.__acl__))
Exemple #6
0
    def __init__(self, request):
        self.__acl__ = []
        # general page factory - append custom non resource permissions
        if getattr(request, "user"):
            permissions = UserService.permissions(
                request.user, db_session=request.dbsession
            )
            has_admin_panel_access = False
            panel_perms = ["admin_panel", ALL_PERMISSIONS]
            for outcome, perm_user, perm_name in permission_to_pyramid_acls(
                    permissions
            ):
                perm_tuple = rewrite_root_perm(outcome, perm_user, perm_name)
                if perm_tuple[0] is Allow and perm_tuple[2] in panel_perms:
                    has_admin_panel_access = True
                self.__acl__.append(perm_tuple)

            # users have special permission called `admin_panel`
            # it should be prerequisite for other `admin*` permissions
            # if it is not present let's deny other admin permissions
            if not has_admin_panel_access:
                self.__acl__ = list(filter(filter_admin_panel_perms, self.__acl__))
Exemple #7
0
    def __init__(self, request):
        self.__acl__ = []
        resource_id = safe_integer(request.matchdict.get("object_id"))
        self.resource = ResourceService.by_resource_id(
            resource_id, db_session=request.dbsession)
        if not self.resource:
            raise HTTPNotFound()

        if self.resource:
            self.__acl__ = self.resource.__acl__

        if self.resource and request.user:
            # add perms that this user has for this resource
            # this is a big performance optimization - we fetch only data
            # needed to check one specific user
            permissions = ResourceService.perms_for_user(
                self.resource, request.user)
            for outcome, perm_user, perm_name in permission_to_pyramid_acls(
                    permissions):
                self.__acl__.append(
                    rewrite_root_perm(outcome, perm_user, perm_name))

        allow_root_access(request, context=self)
Exemple #8
0
    def __init__(self, request):
        self.__acl__ = []
        resource_id = safe_integer(request.matchdict.get("object_id"))
        self.resource = ResourceService.by_resource_id(
            resource_id, db_session=request.dbsession
        )
        if not self.resource:
            raise HTTPNotFound()

        if self.resource:
            self.__acl__ = self.resource.__acl__

        if self.resource and request.user:
            # add perms that this user has for this resource
            # this is a big performance optimization - we fetch only data
            # needed to check one specific user
            permissions = ResourceService.perms_for_user(self.resource, request.user)
            for outcome, perm_user, perm_name in permission_to_pyramid_acls(
                    permissions
            ):
                self.__acl__.append(rewrite_root_perm(outcome, perm_user, perm_name))

        allow_root_access(request, context=self)
Exemple #9
0
 def __acl__(self):
     # type: () -> AccessControlListType
     """
     Administrators have all permissions, user/group-specific permissions added if user is logged in.
     """
     user = self.request.user
     # allow if role MAGPIE_ADMIN_PERMISSION is somehow directly set instead of inferred via members of admin-group
     acl = [(Allow, get_constant("MAGPIE_ADMIN_PERMISSION"),
             ALL_PERMISSIONS)]
     admins = GroupService.by_group_name(get_constant("MAGPIE_ADMIN_GROUP"),
                                         db_session=self.request.db)
     if admins:
         # need to add explicit admin-group ALL_PERMISSIONS otherwise views with other permissions than the
         # default MAGPIE_ADMIN_PERMISSION will be refused access (e.g.: views with MAGPIE_LOGGED_PERMISSION)
         acl += [(Allow, "group:{}".format(admins.id), ALL_PERMISSIONS)]
     if user:
         # user-specific permissions (including group memberships)
         permissions = UserService.permissions(user, self.request.db)
         user_acl = permission_to_pyramid_acls(permissions)
         # allow views that require minimally to be logged in (regardless of who is the user)
         auth_acl = [(Allow, user.id, Authenticated)]
         acl += user_acl + auth_acl
     return acl
Exemple #10
0
    def effective_permissions(self,
                              user,
                              resource,
                              permissions=None,
                              allow_match=True):
        # type: (models.User, ServiceOrResourceType, Optional[Collection[Permission]], bool) -> List[PermissionSet]
        """
        Obtains the effective permissions the user has over the specified resource.

        Recursively rewinds the resource tree from the specified resource up to the top-most parent service the resource
        resides under (or directly if the resource is the service) and retrieve permissions along the way that should be
        applied to children when using scoped-resource inheritance. Rewinding of the tree can terminate earlier when
        permissions can be immediately resolved such as when more restrictive conditions enforce denied access.

        Both user and group permission inheritance is resolved simultaneously to tree hierarchy with corresponding
        allow and deny conditions. User :term:`Direct Permissions` have priority over all its groups
        :term:`Inherited Permissions`, and denied permissions have priority over allowed access ones.

        All applicable permissions on the resource (as defined by :meth:`allowed_permissions`) will have their
        resolution (Allow/Deny) provided as output, unless a specific subset of permissions is requested using
        :paramref:`permissions`. Other permissions are ignored in this case to only resolve requested ones.
        For example, this parameter can be used to request only ACL resolution from specific permissions applicable
        for a given request, as obtained by :meth:`permission_requested`.

        Permissions scoped as `match` can be ignored using :paramref:`allow_match`, such as when the targeted resource
        does not exist.

        .. seealso::
            - :meth:`ServiceInterface.resource_requested`
        """
        if not permissions:
            permissions = self.allowed_permissions(resource)
        requested_perms = set(permissions)  # type: Set[Permission]
        effective_perms = dict()  # type: Dict[Permission, PermissionSet]

        # immediately return all permissions if user is an admin
        db_session = self.request.db
        admin_group = get_constant("MAGPIE_ADMIN_GROUP", self.request)
        admin_group = GroupService.by_group_name(admin_group,
                                                 db_session=db_session)
        if admin_group in user.groups:  # noqa
            return [
                PermissionSet(perm,
                              access=Access.ALLOW,
                              scope=Scope.MATCH,
                              typ=PermissionType.EFFECTIVE,
                              reason=PERMISSION_REASON_ADMIN)
                for perm in permissions
            ]

        # level at which last permission was found, -1 if not found
        # employed to resolve with *closest* scope and for applicable 'reason' combination on same level
        effective_level = dict()  # type: Dict[Permission, Optional[int]]
        current_level = 1  # one-based to avoid ``if level:`` check failing with zero
        full_break = False
        # current and parent resource(s) recursive-scope
        while resource is not None and not full_break:  # bottom-up until service is reached

            # include both permissions set in database as well as defined directly on resource
            cur_res_perms = ResourceService.perms_for_user(
                resource, user, db_session=db_session)
            cur_res_perms.extend(permission_to_pyramid_acls(resource.__acl__))

            for perm_name in requested_perms:
                if full_break:
                    break
                for perm_tup in cur_res_perms:
                    perm_set = PermissionSet(perm_tup)

                    # if user is owner (directly or via groups), all permissions are set,
                    # but continue processing this resource until end in case user explicit deny reverts it
                    if perm_tup.perm_name == ALL_PERMISSIONS:
                        # FIXME:
                        #   This block needs to be validated if support of ownership rules are added.
                        #   Conditions must be revised according to wanted behaviour...
                        #   General idea for now is that explict user/group deny should be prioritized over resource
                        #   ownership permissions since these can be attributed to *any user* while explicit deny are
                        #   definitely set by an admin-level user.
                        for perm in requested_perms:
                            if perm_set.access == Access.DENY:
                                all_perm = PermissionSet(
                                    perm, perm_set.access, perm.scope,
                                    PermissionType.OWNED)
                                effective_perms[perm] = all_perm
                            else:
                                all_perm = PermissionSet(
                                    perm, perm_set.access, perm.scope,
                                    PermissionType.OWNED)
                                effective_perms.setdefault(perm, all_perm)
                        full_break = True
                        break
                    # skip if the current permission must not be processed (at all or for the moment until next 'name')
                    if perm_set.name not in requested_perms or perm_set.name != perm_name:
                        continue
                    # only first resource can use match (if even enabled with found one), parents are recursive-only
                    if not allow_match and perm_set.scope == Scope.MATCH:
                        continue
                    # pick the first permission if none was found up to this point
                    prev_perm = effective_perms.get(perm_name)
                    scope_level = effective_level.get(perm_name)
                    if not prev_perm:
                        effective_perms[perm_name] = perm_set
                        effective_level[perm_name] = current_level
                        continue

                    # user direct permissions have priority over inherited ones from groups
                    # if inherited permission was found during previous iteration, override it with direct permission
                    if perm_set.type == PermissionType.DIRECT:
                        # - reset resolution scope of previous permission attributed to group as it takes precedence
                        # - since there can't be more than one user permission-name per resource on a given level,
                        #   scope resolution is done after applying this *closest* permission, ignore higher level ones
                        if prev_perm.type == PermissionType.INHERITED or not scope_level:
                            effective_perms[perm_name] = perm_set
                            effective_level[perm_name] = current_level
                        continue  # final decision for this user, skip any group permissions

                    # resolve prioritized permission according to ALLOW/DENY, scope and group priority
                    # (see 'PermissionSet.resolve' method for extensive details)
                    # skip if last permission is not on group to avoid redundant USER > GROUP check processed before
                    if prev_perm.type == PermissionType.INHERITED:
                        # - If new permission to process is done against the previous permission from *same* tree-level,
                        #   there is a possibility to combine equal priority groups. In such case, reason is 'MULTIPLE'.
                        # - If not of equal priority, the appropriate permission is selected and reason is overridden
                        #   accordingly by the new higher priority permission.
                        # - If no permission was defined at all (first occurrence), also set it using current permission
                        if scope_level in [None, current_level]:
                            resolved_perm = PermissionSet.resolve(
                                perm_set,
                                prev_perm,
                                context=PermissionType.EFFECTIVE)
                            effective_perms[perm_name] = resolved_perm
                            effective_level[perm_name] = current_level
                        # - If new permission is at *different* tree-level, it applies only if the group has higher
                        #   priority than the previous one, to respect the *closest* scope to the target resource.
                        #   Same priorities are ignored as they were already resolved by *closest* scope above.
                        # - Reset scope level with new permission such that another permission of same group priority as
                        #   that could be processed in next iteration can be compared against it, to resolve 'access'
                        #   priority between them.
                        elif perm_set.group_priority > prev_perm.group_priority:
                            effective_perms[perm_name] = perm_set
                            effective_level[perm_name] = current_level

            # don't bother moving to parent if everything is resolved already
            #   can only assume nothing left to resolve if all permissions are direct on user (highest priority)
            #   if any found permission is group inherited, higher level user permission could still override it
            if (len(effective_perms) == len(requested_perms)
                    and all(perm.type == PermissionType.DIRECT
                            for perm in effective_perms.values())):
                break
            # otherwise, move to parent if any available, since we are not done rewinding the resource tree
            allow_match = False  # reset match not applicable anymore for following parent resources
            current_level += 1
            if resource.parent_id:
                resource = ResourceService.by_resource_id(
                    resource.parent_id, db_session=db_session)
            else:
                resource = None

        # set deny for all still unresolved permissions from requested ones
        resolved_perms = set(effective_perms)
        missing_perms = set(permissions) - resolved_perms
        final_perms = set(effective_perms.values())  # type: Set[PermissionSet]
        for perm_name in missing_perms:
            perm = PermissionSet(perm_name,
                                 access=Access.DENY,
                                 scope=Scope.MATCH,
                                 typ=PermissionType.EFFECTIVE,
                                 reason=PERMISSION_REASON_DEFAULT)
            final_perms.add(perm)
        # enforce type and scope (use MATCH to make it explicit that it applies specifically for this resource)
        for perm in final_perms:
            perm.type = PermissionType.EFFECTIVE
            perm.scope = Scope.MATCH
        return list(final_perms)