-
Notifications
You must be signed in to change notification settings - Fork 25
/
hybrid_json_assignment.py
210 lines (185 loc) · 7.98 KB
/
hybrid_json_assignment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# Copyright 2014-2015 SUSE Linux Products GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystone import config
from keystone import exception
from keystone.assignment.backends import sql as sql_assign
from keystone.assignment.role_backends import sql as sql_role
from keystone.common import manager
from keystone.common import sql
from keystone.i18n import _
from keystone.identity.backends import ldap as ldap_backend
from oslo_config import cfg
from oslo_log import log
import yaml
LOG = log.getLogger(__name__)
hybrid_opts = [
cfg.ListOpt('default_roles',
default=['_member_', ],
help='List of roles assigned by default to an LDAP user'),
cfg.StrOpt('default_project',
default='demo',
help='Default project'),
cfg.StrOpt('default_domain',
default='default',
deprecated_name='default_domain',
deprecated_for_removal=True,
help='(Deprecated) Default domain. Use "default_domain_id" '
'instead.'),
]
CONF = config.CONF
CONF.register_opts(hybrid_opts, 'ldap_hybrid')
class Assignment(sql_assign.Assignment):
_default_roles = list()
_default_project = None
def __init__(self, *args, **kwargs):
super(Assignment, self).__init__(*args, **kwargs)
self.ldap_user = ldap_backend.UserApi(CONF)
self.resource_driver = manager.load_driver(
'keystone.resource', self.default_resource_driver())
with open('/etc/keystone/user-project-map.json', 'r') as f:
self.userprojectmap = yaml.load(f)
projectidcache = {}
for user in self.userprojectmap:
projectids = {}
for projectname in self.userprojectmap[user]:
try:
projectid = projectidcache[projectname]
except:
# cache miss - need to fetch from DB
try:
project = self.resource_driver.get_project_by_name(
projectname, CONF.identity.default_domain_id)
projectid = project['id']
projectidcache[projectname] = project['id']
except:
pass
projectids[projectid] = 1
self.userprojectmap[user] = projectids
def _get_metadata(self, user_id=None, tenant_id=None,
domain_id=None, group_id=None, session=None):
# We only want to apply 'default_roles' to users from LDAP, so
# check if this is an LDAP User first
is_ldap = False
try:
user = self.ldap_user.get(user_id)
username = user['name']
except exception.UserNotFound:
# Not an LDAP User
username = ""
else:
is_ldap = True
LOG.warning('_get_metadata for user=%(user)s',
{'user': user_id})
try:
res = super(Assignment, self)._get_metadata(
user_id, tenant_id, domain_id, group_id, session)
except exception.MetadataNotFound:
LOG.debug('MetadataNotFound for user=%(user)s %(t)s'
' - falling back to JSON data',
{'user': user_id, 't': tenant_id})
if is_ldap and (self.default_project_id == tenant_id or
tenant_id in self.userprojectmap[username]):
return {
'roles': [
{'id': role_id} for role_id in self.default_roles
]
}
else:
raise
else:
LOG.debug('found user=%(user)s in DB', {'user': user_id})
if is_ldap:
roles = res.get('roles', [])
res['roles'] = roles + [
{'id': role_id} for role_id in self.default_roles
]
return res
@property
def default_project(self):
if self._default_project is None:
self._default_project = self.resource_driver.get_project_by_name(
CONF.ldap_hybrid.default_project,
CONF.identity.default_domain_id)
return dict(self._default_project)
@property
def default_project_id(self):
return self.default_project['id']
@property
def default_roles(self):
if not self._default_roles:
with sql.transaction() as session:
query = session.query(sql_role.RoleTable)
query = query.filter(sql_role.RoleTable.name.in_(
CONF.ldap_hybrid.default_roles))
role_refs = query.all()
if len(role_refs) != len(CONF.ldap_hybrid.default_roles):
raise exception.RoleNotFound(
message=_('Could not find one or more roles: %s') %
', '.join(CONF.ldap_hybrid.default_roles))
self._default_roles = [role_ref.id for role_ref in role_refs]
return self._default_roles
def list_role_assignments(self, role_id=None, user_id=None, group_ids=None,
domain_id=None, project_ids=None,
inherited_to_projects=None):
role_assignments = super(Assignment, self).list_role_assignments(
role_id=role_id, user_id=user_id, group_ids=group_ids,
domain_id=domain_id, project_ids=project_ids,
inherited_to_projects=inherited_to_projects)
if user_id:
ldap_users = [self.ldap_user.get_filtered(user_id)]
else:
ldap_users = self.ldap_user.get_all_filtered(None)
LOG.warning('xxhybrid list_role_assignments: user=%(user)s',
{'user': user_id})
# This will be really slow for setups with lots of users, but there
# is not other way to achieve it currently
for user in ldap_users:
# Skip LDAP User if it already as an assignemt,
# else add the default assignment
if any(a for a in role_assignments if
('user_id'in a and a['user_id'] == user['id'])):
continue
else:
for role in self.default_roles:
role_assignments.append({
'role_id': role,
'project_id': self.default_project_id,
'user_id': user['id']
})
return role_assignments
def list_project_ids_for_user(self, user_id, group_ids, hints):
LOG.warning('xxhybrid list_project_ids_for_user: user=%(user)s',
{'user': user_id})
project_ids = super(Assignment, self).list_project_ids_for_user(
user_id, group_ids, hints)
# Make sure the default project is in the project list for the user
# user_id
for project_id in project_ids:
if project_id == self.default_project_id:
return project_ids
# We only want to apply 'default_project' to users from LDAP, so
# check if this is an LDAP User first
try:
user = self.ldap_user.get(user_id)
username = user['name']
except exception.UserNotFound:
# Not an LDAP User
pass
else:
if username in self.userprojectmap:
project_ids.extend(self.userprojectmap[username].keys())
else:
project_ids.append(self.default_project_id)
return project_ids