Statistics
| Branch: | Tag: | Revision:

root / snf-pithos-backend / pithos / backends / lib / sqlalchemy / permissions.py @ 3759eddb

History | View | Annotate | Download (10.1 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from sqlalchemy.sql import select, literal, or_, and_
35
from sqlalchemy.sql.expression import join, union
36

    
37
from xfeatures import XFeatures
38
from groups import Groups
39
from public import Public
40
from node import Node
41
from collections import defaultdict
42

    
43
from dbworker import ESCAPE_CHAR
44

    
45

    
46
READ = 0
47
WRITE = 1
48

    
49

    
50
class Permissions(XFeatures, Groups, Public, Node):
51

    
52
    def __init__(self, **params):
53
        XFeatures.__init__(self, **params)
54
        Groups.__init__(self, **params)
55
        Public.__init__(self, **params)
56
        Node.__init__(self, **params)
57

    
58
    def access_grant(self, path, access, members=()):
59
        """Grant members with access to path.
60
           Members can also be '*' (all),
61
           or some group specified as 'owner:group'."""
62

    
63
        if not members:
64
            return
65
        feature = self.xfeature_create(path)
66
        self.feature_setmany(feature, access, members)
67

    
68
    def access_set(self, path, permissions):
69
        """Set permissions for path. The permissions dict
70
           maps 'read', 'write' keys to member lists."""
71

    
72
        r = permissions.get('read', [])
73
        w = permissions.get('write', [])
74
        if not r and not w:
75
            self.xfeature_destroy(path)
76
            return
77
        feature = self.xfeature_create(path)
78
        self.feature_clear(feature, READ)
79
        self.feature_clear(feature, WRITE)
80
        if r:
81
            self.feature_setmany(feature, READ, r)
82
        if w:
83
            self.feature_setmany(feature, WRITE, w)
84

    
85
    def access_get_for_bulk(self, perms):
86
        """Get permissions for path."""
87
        allowed = None
88
        d = defaultdict(list)
89
        for value, feature_id, key in perms:
90
            d[key].append(value)
91
        permissions = d
92
        if READ in permissions:
93
            allowed = 0
94
            permissions['read'] = permissions[READ]
95
            del(permissions[READ])
96
        if WRITE in permissions:
97
            allowed = 1
98
            permissions['write'] = permissions[WRITE]
99
            del(permissions[WRITE])
100
        return (permissions, allowed)
101

    
102
    def access_get(self, path):
103
        """Get permissions for path."""
104

    
105
        feature = self.xfeature_get(path)
106
        if not feature:
107
            return {}
108
        permissions = self.feature_dict(feature)
109
        if READ in permissions:
110
            permissions['read'] = permissions[READ]
111
            del(permissions[READ])
112
        if WRITE in permissions:
113
            permissions['write'] = permissions[WRITE]
114
            del(permissions[WRITE])
115
        return permissions
116

    
117
    def access_members(self, path):
118
        feature = self.xfeature_get(path)
119
        if not feature:
120
            return []
121
        permissions = self.feature_dict(feature)
122
        members = set()
123
        members.update(permissions.get(READ, []))
124
        members.update(permissions.get(WRITE, []))
125
        for m in set(members):
126
            parts = m.split(':', 1)
127
            if len(parts) != 2:
128
                continue
129
            user, group = parts
130
            members.remove(m)
131
            members.update(self.group_members(user, group))
132
        return list(members)
133

    
134
    def access_clear(self, path):
135
        """Revoke access to path (both permissions and public)."""
136

    
137
        self.xfeature_destroy(path)
138
        self.public_unset(path)
139

    
140
    def access_clear_bulk(self, paths):
141
        """Revoke access to path (both permissions and public)."""
142

    
143
        self.xfeature_destroy_bulk(paths)
144
        self.public_unset_bulk(paths)
145

    
146
    def access_check(self, path, access, member):
147
        """Return true if the member has this access to the path."""
148

    
149
        feature = self.xfeature_get(path)
150
        if not feature:
151
            return False
152
        members = self.feature_get(feature, access)
153
        if member in members or '*' in members:
154
            return True
155
        for owner, group in self.group_parents(member):
156
            if owner + ':' + group in members:
157
                return True
158
        return False
159

    
160
    def access_check_bulk(self, paths, member):
161
        rows = None
162
        xfeatures_xfeaturevals = \
163
            self.xfeaturevals.join(self.xfeatures,
164
                                   onclause=
165
                                   and_(self.xfeatures.c.feature_id ==
166
                                        self.xfeaturevals.c.feature_id,
167
                                        self.xfeatures.c.path.in_(paths)))
168
        s = select([self.xfeatures.c.path,
169
                   self.xfeaturevals.c.value,
170
                   self.xfeaturevals.c.feature_id,
171
                   self.xfeaturevals.c.key],
172
                   from_obj=[xfeatures_xfeaturevals])
173
        r = self.conn.execute(s)
174
        rows = r.fetchall()
175
        r.close()
176
        if rows:
177
            access_check_paths = {}
178
            for path, value, feature_id, key in rows:
179
                try:
180
                    access_check_paths[path].append((value, feature_id, key))
181
                except KeyError:
182
                    access_check_paths[path] = [(value, feature_id, key)]
183
            access_check_paths['group_parents'] = self.group_parents(member)
184
            return access_check_paths
185
        return None
186

    
187
    def access_inherit(self, path):
188
        """Return the paths influencing the access for path."""
189

    
190
#         r = self.xfeature_inherit(path)
191
#         if not r:
192
#             return []
193
#         # Compute valid.
194
#         return [x[0] for x in r if x[0] in valid]
195

    
196
        # Only keep path components.
197
        parts = path.rstrip('/').split('/')
198
        valid = []
199
        for i in range(1, len(parts)):
200
            subp = '/'.join(parts[:i + 1])
201
            valid.append(subp)
202
            if subp != path:
203
                valid.append(subp + '/')
204
        return [x for x in valid if self.xfeature_get(x)]
205

    
206
    def access_inherit_bulk(self, paths):
207
        """Return the paths influencing the access for path."""
208

    
209
        # Only keep path components.
210
        valid = []
211
        for path in paths:
212
            parts = path.rstrip('/').split('/')
213
            for i in range(1, len(parts)):
214
                subp = '/'.join(parts[:i + 1])
215
                valid.append(subp)
216
                if subp != path:
217
                    valid.append(subp + '/')
218
        valid = self.xfeature_get_bulk(valid)
219
        return [x[1] for x in valid]
220

    
221
    def access_list_paths(self, member, prefix=None, include_owned=False,
222
                          include_containers=True):
223
        """Return the list of paths granted to member.
224

225
        Keyword arguments:
226
        prefix -- return only paths starting with prefix (default None)
227
        include_owned -- return also paths owned by member (default False)
228
        include_containers -- return also container paths owned by member
229
                              (default True)
230

231
        """
232

    
233
        xfeatures_xfeaturevals = self.xfeatures.join(self.xfeaturevals)
234

    
235
        selectable = (self.groups.c.owner + ':' + self.groups.c.name)
236
        member_groups = select([selectable.label('value')],
237
                               self.groups.c.member == member)
238

    
239
        members = select([literal(member).label('value')])
240
        any = select([literal('*').label('value')])
241

    
242
        u = union(member_groups, members, any).alias()
243
        inner_join = join(xfeatures_xfeaturevals, u,
244
                          self.xfeaturevals.c.value == u.c.value)
245
        s = select([self.xfeatures.c.path], from_obj=[inner_join]).distinct()
246
        if prefix:
247
            like = lambda p: self.xfeatures.c.path.like(
248
                self.escape_like(p) + '%', escape=ESCAPE_CHAR)
249
            s = s.where(or_(*map(like,
250
                                 self.access_inherit(prefix) or [prefix])))
251
        r = self.conn.execute(s)
252
        l = [row[0] for row in r.fetchall()]
253
        r.close()
254

    
255
        if include_owned:
256
            container_nodes = select(
257
                [self.nodes.c.node],
258
                self.nodes.c.parent == self.node_lookup(member))
259
            condition = self.nodes.c.parent.in_(container_nodes)
260
            if include_containers:
261
                condition = or_(condition,
262
                                self.nodes.c.node.in_(container_nodes))
263
            s = select([self.nodes.c.path], condition)
264
            r = self.conn.execute(s)
265
            l += [row[0] for row in r.fetchall() if row[0] not in l]
266
            r.close()
267
        return l
268

    
269
    def access_list_shared(self, prefix=''):
270
        """Return the list of shared paths."""
271

    
272
        s = select([self.xfeatures.c.path])
273
        like = lambda p: self.xfeatures.c.path.like(
274
            self.escape_like(p) + '%', escape=ESCAPE_CHAR)
275
        s = s.where(or_(*map(like, self.access_inherit(prefix) or [prefix])))
276
        s = s.order_by(self.xfeatures.c.path.asc())
277
        r = self.conn.execute(s)
278
        l = [row[0] for row in r.fetchall()]
279
        r.close()
280
        return l