aboutsummaryrefslogtreecommitdiff
path: root/scripts/ldap-sync
blob: 9dcf3c52fdc6ebf8eb3cc8d2702f98066e27c1ed (plain)
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
#!/usr/bin/env python
# Copyright (C) 2013 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import ldap
import logging
import logging.config
import os
import subprocess
import sys
import urllib2
import uuid
from hashlib import sha1
from random import random

from ConfigParser import ConfigParser

config = ConfigParser()
config.read(os.path.join(os.path.dirname(sys.argv[0]), "sync.conf"))

logging.config.fileConfig(os.path.join(os.path.dirname(sys.argv[0]),
                                       "sync.conf"))
logger = logging.getLogger()

# Global variables: first used to store all users coming out from LDAP, we need
# to add those two that are the default RhodeCode ones.
# Second used to map groups and their users, used at the end to remove users.
all_usernames = ['admin', 'default']
all_groups = {}


class InvalidResponseIDError(Exception):
    ''' Request and response don't have the same UUID. '''


class RhodecodeResponseError(Exception):
    ''' Response has an error, something went wrong with request execution. '''


class UserAlreadyInGroupError(Exception):
    ''' User is already a member of the target group. '''


class UserNotInGroupError(Exception):
    ''' User is not a member of the target group. '''


class SystemCommand():

    @classmethod
    def execute(cls, cmd_args, with_sudo=True):
        """Runs the command passed."""
        if not isinstance(cmd_args, list):
            cmd_args = list(cmd_args)
        if with_sudo:
            cmd_args.insert(0, "sudo")

        with open(os.devnull, 'w'):
            process = subprocess.Popen(cmd_args, stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            (stdout, stderr) = process.communicate()

        if process.returncode != 0:
            logger.warn("Error executing command: '%s'. Reason: %s." %
                        (" ".join(cmd_args), stderr))
        else:
            logger.debug("Sucess executing command %s. Output: %s" % (cmd_args,
                                                                      stdout))

        return stdout

    @classmethod
    def add_group(cls, groupname):
        cmd_args = ["groupadd", groupname]
        cls.execute(cmd_args)

    @classmethod
    def add_user(cls, username):
        cmd_args = ["adduser", "--disabled-password", "--force-badname",
                    "--quiet", "--gecos", "''", username]
        cls.execute(cmd_args)

    @classmethod
    def add_user_to_group(cls, groupname, username):
        cmd_args = ["gpasswd", "-a", username, groupname]
        cls.execute(cmd_args)

    @classmethod
    def remove_user_from_group(cls, groupname, username):
        cmd_args = ["gpasswd", "-d", username, groupname]
        cls.execute(cmd_args)

    @classmethod
    def get_group_members(cls, groupname):
        cmd_args = ["members", "--all", groupname]
        try:
            output = cls.execute(cmd_args)
            users = set(output.split())
            return users
        except:
            return {}


class RhodecodeAPI():

    def __init__(self, url, key):
        self.url = url
        self.key = key

    def get_api_data(self, id, method, args):
        """Prepare dict for API post."""
        return {
            "id": id,
            "api_key": self.key,
            "method": method,
            "args": args
        }

    def rhodecode_api_post(self, method, args):
        """Send a generic API post to Rhodecode.

        This will generate the UUID for validation check after the
        response is returned. Handle errors and get the result back.
        """
        id = str(uuid.uuid1())
        data = self.get_api_data(id, method, args)

        data = json.dumps(data)
        headers = {'content-type': 'text/plain'}
        req = urllib2.Request(self.url, data, headers)

        response = urllib2.urlopen(req)
        response = json.load(response)

        if id != response["id"]:
            raise InvalidResponseIDError("UUID does not match.")

        if response["error"] is not None:
            raise RhodecodeResponseError(response["error"])

        return response["result"]

    def create_user(self, username, email, firstname, lastname, password,
                    ldap_dn, active=True, admin=False):
        """Create the user in RhodeCode."""
        args = {
            'username': username,
            'email': email,
            'firstname': firstname,
            'lastname': lastname,
            'active': str(active),
            'admin': str(admin),
            'password': password,
            'ldap_dn': ldap_dn,
        }
        return self.rhodecode_api_post("create_user", args)

    def update_user(self, userid, username, active, ldap_dn):
        """Update an existing user."""
        args = {
            'userid': userid,
            'username': username,
            'active': active,
            'ldap_dn': ldap_dn,
        }
        return self.rhodecode_api_post("update_user", args)

    def delete_user(self, username):
        """Removes an user from RhodeCode."""
        args = {'userid': username}
        return self.rhodecode_api_post("delete_user", args)

    def create_group(self, name, active=True):
        """Create the Rhodecode user group."""
        args = {
            "group_name": name,
            "active": str(active)
        }
        self.rhodecode_api_post("create_users_group", args)

    def add_membership(self, group, username):
        """Add specific user to a group."""
        args = {
            "usersgroupid": group,
            "userid": username
        }
        result = self.rhodecode_api_post("add_user_to_users_group", args)
        if not result["success"]:
            raise UserAlreadyInGroupError("User %s already in group %s." %
                                          (username, group))

    def remove_membership(self, group, username):
        """Remove specific user from a group."""
        args = {
            "usersgroupid": group,
            "userid": username
        }
        result = self.rhodecode_api_post("remove_user_from_users_group", args)
        if not result["success"]:
            raise UserNotInGroupError("User %s not in group %s." %
                                      (username, group))

    def get_group_members(self, name):
        """Get the list of member usernames from a user group."""
        args = {"usersgroupid": name}
        members = self.rhodecode_api_post("get_users_group", args)['members']
        member_list = []
        for member in members:
            member_list.append(member["username"])
        return member_list

    def get_group(self, name):
        """Return group info."""
        args = {"usersgroupid": name}
        return self.rhodecode_api_post("get_users_group", args)

    def get_groups(self):
        """Returns all the groups in RhodeCode."""
        args = {}
        return self.rhodecode_api_post("get_users_groups", args)

    def get_user(self, username):
        """Return user info."""
        args = {"userid": username}
        return self.rhodecode_api_post("get_user", args)

    def get_users(self):
        """Returns all the users in RhodeCode."""
        args = {}
        return self.rhodecode_api_post("get_users", args)


class LdapClient():

    def __init__(self, uri, user, key, base_dn, group_dn):
        self.client = ldap.initialize(uri, trace_level=0)
        self.client.set_option(ldap.OPT_REFERRALS, 0)
        self.client.simple_bind(user, key)
        self.base_dn = base_dn
        self.group_dn = group_dn

    def __del__(self):
        self.client.unbind()

    def get_groups(self):
        """Get all the groups in form of dict {group_name: group_info,...}."""
        searchFilter = "objectClass=groupOfUniqueNames"
        result = self.client.search_s(self.group_dn, ldap.SCOPE_SUBTREE,
                                      searchFilter)

        groups = {}
        for group in result:
            groups[group[1]['cn'][0]] = group[1]

        return groups

    def get_git_group_users(self, group):
        """Search for members of the specified group."""
        searchFilter = "memberof=cn=%s,ou=mailing,ou=groups,dc=linaro,dc=org"
        searchFilter = searchFilter % group
        # We need the base_dn here to search for members of the group.
        return self.client.search_s(self.base_dn, ldap.SCOPE_SUBTREE,
                                    searchFilter)

    def get_git_groups(self):
        ldap_groups = self.get_groups()
        groups = []
        for key, value in ldap_groups.iteritems():
            for member in value['uniqueMember']:
                groups.append(self.parse_member_string(member)[1])
        return groups

    def get_users(self):
        """Get all the users as list. [username1, username2, ..]."""
        searchFilter = "(uid=*)"
        result = self.client.search_s(self.base_dn, ldap.SCOPE_SUBTREE,
                                      searchFilter)

        users = []
        for user in result:
            users.append(user[1]['uid'][0])

        return users

    def get_group_users(self, groups, group):
        """Returns all the users belonging to a single group.

        Based on the list of groups and memberships, returns all the
        users belonging to a single group, searching recursively.
        """
        users = []
        for member in groups[group]["uniqueMember"]:
            member = self.parse_member_string(member)
            if member[0] == "uid":
                users.append(member[1])
            elif member[0] == "cn":
                users += self.get_group_users(groups, member[1])

        return users

    def parse_member_string(self, member):
        """Parses the member string and returns a touple of type and name.

        Unique member can be either user or group. Users will have 'uid' as
        prefix while groups will have 'cn'.
        """
        member = member.split(",")[0]
        return member.split('=')


class LdapSync():

    def __init__(self):
        self.ldap_client = LdapClient(config.get("ldap_config", "ldap_uri"),
                                      config.get("ldap_config", "ldap_user"),
                                      config.get("ldap_config", "ldap_key"),
                                      config.get("ldap_config", "base_dn"),
                                      config.get("ldap_config", "group_dn"))
        self.rhodecode_api = RhodecodeAPI(config.get("ldap_config", "api_url"),
                                          config.get("ldap_config", "api_key"))

    def get_ldap_groups(self):
        """Fetch the LDAP groups if they are not already present."""
        try:
            return self.ldap_groups
        except:
            self.ldap_groups = self.ldap_client.get_groups()
            return self.ldap_groups

    def get_ldap_users(self):
        """Fetch the LDAP users if they are not already present."""
        try:
            return self.ldap_users
        except:
            self.ldap_users = self.ldap_client.get_users()
            return self.ldap_users

    def get_ldap_git_groups(self):
        try:
            return self.ldap_git_groups
        except:
            self.ldap_git_groups = self.ldap_client.get_git_groups()
            return self.ldap_git_groups

    def get_rhodecode_usernames(self):
        rhodecode_user_names = []
        json_users = self.rhodecode_api.get_users()
        for user in json_users:
            rhodecode_user_names.append(user.get('username'))
        return rhodecode_user_names

    def get_ldap_git_group_users(self, group):
        return self.ldap_client.get_git_group_users(group)

    def update_git_groups_from_ldap(self):
        """Creates groups based on the git groups available in LDAP."""
        logger.info("Start importing git groups to Rhodecode.")
        added = existing = 0
        groups = self.get_ldap_git_groups()
        for group in groups:
            try:
                self.rhodecode_api.create_group(group)
                logger.info("Added group: %s" % group)
                added += 1
            except Exception as e:
                logger.warn("Skip group %s. Reason: %s" % (group, e))
                existing += 1

        logger.info("End importing groups to Rhodecode. "
                    "Added: %s, Existing: %s." % (added, existing))

    def update_git_users_from_ldap(self, group, members):
        """Update group membership for the specified group and members."""
        for member in members:
            uid_or_cn = member[0].split(',')[0].split('=')
            details = member[1]
            # RhodeCode supports only users inside a group, we cannot have
            # groups inside another group. If we have a group member of another
            # group, we find its members on add them.
            if uid_or_cn[0] == 'uid':
                username = details.get('uid')[0]
                ldap_dn = member[0]
                # Store all usernames, needed to remove users at the end.
                self._add_users_groups(username, group)

                if uid_or_cn[1] not in self.get_rhodecode_usernames():
                    # We can have more than one here, but we take the first.
                    email = details.get('mail')[0]
                    try:
                        firstname = details.get('givenName')[0]
                        lastname = details.get('sn')[0]
                    except:
                        logger.warn("User %s has no 'givenName' or 'sn' LDAP "
                                    "attribute." % username)
                        firstname = lastname = username
                    # FIXME
                    # This is a bug in RhodeCode, spoke to the developer.
                    # RhodeCode does not permit to create users without a
                    # password field, even when using LDAP. We just throw
                    # garbage in there, the password is checked via LDAP.
                    fake_password = sha1(str(random)).hexdigest()
                    try:
                        logger.info("Creating new user %s" % username)
                        self.rhodecode_api.create_user(username, email,
                                                       firstname, lastname,
                                                       fake_password, ldap_dn)
                    except RhodecodeResponseError:
                        logger.warn("User %s already exists." % username)
                else:
                    # Make sure user is active and has LDAP info.
                    user = self.rhodecode_api.get_user(username)
                    if user.get('ldap_dn') is None or not bool(user.get('active')):
                        logger.debug('Updatind user %s' % username)
                        self.rhodecode_api.update_user(user['user_id'],
                                                       username,
                                                       True,
                                                       ldap_dn)
                # Finally, add the user to the group.
                if username not in self.rhodecode_api.get_group_members(group):
                    logger.debug("Adding %s in group %s" % (username, group))
                    self.rhodecode_api.add_membership(group, username)
            elif uid_or_cn[0] == 'cn':
                logger.debug("Found a group member: %s" % uid_or_cn[1])
                members = self.get_ldap_git_group_users(details.get('cn')[0])
                self.update_git_users_from_ldap(group, members)

    def _add_users_groups(self, username, group):
        """Internally used to store all user names and groups."""
        all_usernames.append(username)
        if all_groups.get(group) is not None:
            all_groups[group].append(username)
        else:
            all_groups[group] = [username]

    def update_groups_from_ldap(self):
        """Add all the groups from LDAP to Rhodecode."""
        logger.info("Start importing groups to Rhodecode.")
        added = existing = 0
        groups = self.get_ldap_groups()
        for group in groups:
            try:
                self.rhodecode_api.create_group(group)
                logger.debug("Added group: %s" % group)
                added += 1
            except Exception as e:
                logger.warn("Skip group %s. Reason: %s" % (group, e))
                existing += 1

        logger.info("End importing groups to Rhodecode. "
                    "Added: %s, Existing: %s." % (added, existing))

    def update_memberships_from_ldap(self, group):
        """Update rhodecode memberships based on the LDAP groups."""
        group_users = self.ldap_client.get_group_users(self.get_ldap_groups(),
                                                       group)

        # Delete memberships first from each group which are not part
        # of the group any more.
        logger.debug("Remove memberships for users not in LDAP group.")
        try:
            rhodecode_members = self.rhodecode_api.get_group_members(group)
        except Exception as e:
            logger.warn("Could not get members for group %s. Reason: %s" %
                        (group, e))

        for rhodecode_member in rhodecode_members:
            if rhodecode_member not in group_users:
                try:
                    self.rhodocode_api.remove_membership(group,
                                                         rhodecode_member)
                except UserNotInGroupError:
                    # This should not actually happen but log it if it does.
                    logger.debug("User not in Rhodecode group.")
                except RhodecodeResponseError as e:
                    logger.warn("Membership for user %s could not be "
                                "removed from group %s. Reason" %
                                (rhodecode_member, group, e))

        # Add memberships.
        for member in group_users:
            try:
                self.rhodecode_api.add_membership(group, member)
            except UserAlreadyInGroupError:
                logger.debug("User already in Rhodecode group.")
            except RhodecodeResponseError as e:
                logger.warn("Membership for user %s could not be "
                            "added to the group %s. Reason: %s" %
                            (member, group, e))

    def remove_user_from_group(self, username, group):
        """Removes user from the specified group, if in the group."""
        group_users = all_groups.get(group)

        if username in group_users:
            self.rhodecode_api.remove_membership(group, username)

    def disable_user(self, username):
        """Disable a user in RhodeCode.

        :param username: The user to disable.
        """
        # FIXME
        # There are some instability in LDAP groups, so for now we disable
        # users instead of removing them.
        user = self.rhodecode_api.get_user(username)
        logger.info("Disabling user %s" % username)
        self.rhodecode_api.update_user(user['user_id'], username, False,
                                       user['ldap_dn'])


if __name__ == '__main__':

    sync = LdapSync()
    sync.update_git_groups_from_ldap()

    groups = sync.get_ldap_git_groups()
    for group in groups:
        members = sync.get_ldap_git_group_users(group)
        sync.update_git_users_from_ldap(group, members)

    # TODO
    # Commented out section, since right now there is not much stability on
    # LDAP side, and we receive different results. This would lead to false
    # users deactivation.
    # Users to remove.
    # diff = set(sync.get_rhodecode_usernames()).difference(set(all_usernames))
    # if diff:
    #     for username in diff:
    #         for group in groups:
    #             sync.remove_user_from_group(username, group)
    #     sync.disable_user(username)