create_shared.py 16.6 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
8
9
10
11
12
13
14
import argparse
import boxsdk
import kadmin
import logging
import logging.handlers
import mcommunity
import os
import re
import yaml

from boxsdk.object.collaboration import CollaborationRole
from subprocess import check_output as cmd
from subprocess import CalledProcessError
15
16

devnull = open(os.devnull, 'w')
17
18
19
20
21
22
23
24


class SharedAccount:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
        self.create_extra_attr()
Rob Carleski's avatar
Rob Carleski committed
25
        self.logger = logging.getLogger(__name__)
26
27
28

    def create_box(self):
        try:
29
30
31
32
            self.logger.info(
                'Creating Box account',
                extra={'entity': self.account}
            )
33
34
35
36
37
            auth = boxsdk.JWTAuth.from_settings_file(
                self.config['box']['auth_file']
            )
            boxClient = boxsdk.Client(auth)
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
38
            self.logger.error(e, extra={'entity': self.account})
39
40
            exit(2)
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
41
            self.logger.error(e, extra={'entity': self.account})
42
43
44
45
            exit(2)

        try:
            if len(self.full_name) > 50:
Rob Carleski's avatar
Rob Carleski committed
46
                self.logger.warning(
47
48
49
50
51
52
53
                    'Full name attribute for user exceeds limit. Truncating.',
                    extra={'entity': self.account}
                )
            boxAccount = boxClient.create_user(
                name=self.full_name[:50],
                login=self.email,
                space_amount=-1,
54
                tracking_codes=[{
55
56
                    'name': 'account_type',
                    'value': 'shared'
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
            )

            boxAccount.update_info({'is_sync_enabled': False})

            self.shared_box_folder = boxClient.as_user(
                boxAccount
            ).folder(
                0
            ).create_subfolder(
                self.full_name
            )

            self.box_text = '''
Box-Specific Information:
 - The ability to use Box Sync with shared accounts is disabled by default,
but allowed in certain circumstances; if you need this, please reply to this
message to discuss. Syncing the shared folder in your individual account is
always allowed.

 - Files placed in shared account folders are owned by the shared account.

 - To learn more about using your shared account, visit the Shared U-M Box
Accounts section of the M+Box support site.

(http://www.itcs.umich.edu/storage/box/shared-accounts.php)

'''
            if self.secure:
                self.shared_box_folder.update_info({
                    'can_non_owners_invite': False,
                    'allowed_shared_link_access_levels': ['collaborators']
                })
                self.box_text += '''
 - Settings appropriate for sensitive data have been applied to this folder.
'''

            self.upload_box_info_file()

            for owner in self.owners:
                search = boxClient.users(filter_term=owner)
                for _ in search:
                    login = _['login'].split('@')[0].lower()
                    if owner.lower() == login:
                        try:
                            self.shared_box_folder.collaborate(
                                _,
                                CollaborationRole.CO_OWNER
                            )
                        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
107
                            self.logger.warning(
108
109
110
111
112
113
114
                                'Unable to add {} as Box collaborator'.format(
                                    _
                                 ),
                                extra={'entity': self.account}
                            )
                        break
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
115
            self.logger.error(e, extra={'entity': self.account})
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

    def upload_box_info_file(self):
        try:
            readme = '{}/{}-{}'.format(
                self.config['general']['data_dir'],
                self.account,
                'README.txt'
            )
            with open(readme, 'w+') as stream:
                content = '''
The folder "{}" is owned by the shared account "{}".

The initial co-owners on this folder are based on the owners listed on the
request form at the time this folder was created.

The co-owners and members will NOT be kept in sync with MCommunity.

f you have any questions please contact the ITS Service Center:

http://its.umich.edu/help/'''.format(self.full_name, self.email)
                stream.write(content)
            self.shared_box_folder.upload(readme)
            os.remove(readme)
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
140
            self.logger.error(e, extra={'entity': self.account})
141
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
142
            self.logger.error(e, extra={'entity': self.account})
143
144
145

    def create_google(self):
        try:
146
147
148
149
            self.logger.info(
                'Creating Google account',
                extra={'entity': self.account}
            )
150
151
152
153
154
155
156
157
158
159
160
161
162
            cmd([
                self.config['google']['gam_command'],
                'create',
                'user',
                self.account,
                'firstname',
                self.first_name,
                'lastname',
                self.last_name,
                'password',
                self.password,
                'org',
                'Department accounts'
163
            ], stderr=devnull)
164
        except CalledProcessError as e:
165
166
167
168
169
170
171
172
173
174
175
176
            if e.returncode == 144:
                self.logger.info(
                    'Invalid data provided to Google account creation call',
                    extra={'entity': self.account}
                )
            elif e.returncode == 153:
                self.logger.info(
                    'Account already exists in Google',
                    extra={'entity': self.account}
                )
            else:
                self.logger.error(e, extra={'entity': self.account})
177
178
179
180
181

        self.google_text = '''
Google-Specific Information:
- For information on using this account, please check the following URL:

182
https://documentation.its.umich.edu/node/339/
183
184
185
'''

    def set_up_mcommunity_group(self):
186
187
188
189
190
191
        client = mcommunity.Client(self.config['mcommunity'])
        controllerCn = client._create_entity_ldap(
            self.config['mcommunity']['api_control_group']
        )
        ext_addr = self.account.lower() + '@go.itd.umich.edu'
        needs_update = False
192
        try:
193
194
195
196
197
            self.logger.info(
                'Checking Mcommunity for associated group',
                extra={'entity': self.account}
            )
            client.fetch_group(self.account)
198
199
200
        except Exception as e:
            self.logger.info(e, extra={'entity': self.account})

201
202
203
204
        if hasattr(client, 'group_data'):
            self.logger.info(
                'Found associated MCommunity group',
                extra={'entity': self.account}
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
            for owner in self.owners:
                ownerDn = client._create_entity_ldap(owner).lower()
                if ownerDn not in client.group_data['ownerDn']:
                    needs_update = True
                    break

            if self.service in ['google', 'both']:
                if type(client.group_data['memberExternalRaw']) is list:
                    if ext_addr not in client.group_data['memberExternalRaw']:
                        needs_update = True

            if needs_update:
                self.logger.info(
                    'Mcommunity group needs updating',
                    extra={'entity': self.account}
                )
                if controllerCn not in client.group_data['ownerDn']:
                    if not self.take_group_ownership(self.account):
                        self.logger.error(
                            'Failed to obtain group ownership',
                            extra={'entity': self.account}
                        )
                        exit(2)
                    client.fetch_group(self.account)
            else:
                self.logger.info(
                    'Mcommunity group does not need an update',
                    extra={'entity': self.account}
                )
                return
236
237
        else:
            try:
238
239
240
241
242
243
                self.logger.info(
                    'Reserving new Mcommunity group',
                    extra={'entity': self.account}
                )
                client.reserve_group(self.account)
                client.fetch_group(self.account)
244
245
246
            except Exception as e:
                self.logger.info(e, extra={'entity': self.account})
                exit(2)
247
248

        try:
249
250
251
252
            self.logger.info(
                'Updating Mcommunity group membership',
                extra={'entity': self.account}
            )
253
            if self.service in ['google', 'both']:
254
255
256
257
258
259
260
261
262
263
264
                client.add_group_members(ext_addr)
            client.remove_group_members(
                self.config['mcommunity']['api_control_group']
            )
            client.update_group_members()
            self.logger.info(
                'Updating Mcommunity group ownership',
                extra={'entity': self.account}
            )
            client.add_group_owners(self.owners)
            client.remove_group_owners(
265
266
                self.config['mcommunity']['api_control_group']
            )
267
            client.update_group_owners()
268
        except Exception as e:
Rob Carleski's avatar
Rob Carleski committed
269
            self.logger.warning(e, extra={'entity': self.account})
270
271
272
273
274
275
276

    def take_group_ownership(self, group):
        input('Add api controller as group owner, then press enter.')
        return True

    def set_kerberos_password(self):
        try:
277
278
279
280
            self.logger.info(
                'Creating kerberos principal',
                extra={'entity': self.account}
            )
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
            admin = '{}@{}'.format(
                self.config['kerberos']['admin'],
                self.config['kerberos']['realm'].upper()
            )
            kadm = kadmin.init_with_keytab(
                admin,
                self.config['kerberos']['keytab']
            )
            kadm.ank(
                '{}@{}'.format(
                    self.account,
                    self.config['kerberos']['realm'].upper()
                ),
                self.password
            )
        except kadmin.KAdminError as e:
297
            self.logger.warning(e, extra={'entity': self.account})
298
299

    def upload_and_share_password(self):
300
        passFilePath = '{}/{}-passwd.txt'.format(
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
            self.config['general']['data_dir'],
            self.account
        )

        with open(passFilePath, 'w') as passwordFile:
            passwordFile.write(self.password)

        upload_output = cmd([
            self.config['google']['gam_command'],
            'user',
            self.config['google']['admin_account'],
            'add',
            'drivefile',
            'localfile',
            passFilePath,
            'parentname',
            'Shared Account Passwords'
318
        ], stderr=devnull)
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        file_id = re.search(
            r'.*\((.*)\)',
            upload_output.decode('UTF-8')
        ).groups()[0]

        for owner in self.owners:
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.config['google']['admin_account'],
                    'add',
                    'drivefileacl',
                    file_id,
                    'user',
                    owner,
                    'role',
                    'reader'
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
339
                self.logger.warning(e.output, extra={'entity': self.account})
340
341
342
343
344
345
346
347
                continue

        os.remove(passFilePath)
        return file_id

    def create_extra_attr(self):
        try:
            self.full_name = self.first_name + self.last_name
348
        except TypeError:
349
350
351
352
353
354
355
356
            split = re.split(r'[\-\_\.\s]+', self.account)
            self.first_name = ' '.join(split[:len(split)//2]).title()
            self.last_name = ' '.join(split[len(split)//2:]).title()
            self.full_name = '{} {}'.format(
                self.first_name,
                self.last_name
            )

357
358
        self.account = re.sub(r'[^\w_-]', '.', self.account).lower().strip()

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
        self.email = '{}@{}'.format(
            self.account,
            self.config['google']['domain']
        )


def main():
    helptext = '''examples:
        collab-create-shared -a collab-testing -p pass12word -o mlkjr moliere
        collab-create-shared -a collab-testing -f collab -l testing -t google
            -p pass12word -o mlkjr moliere -s
        collab-create-shared --account collab-testing --password pass12word
            --owners mlkjr moliere
        collab-create-shared --acount collab-testing --password pass12word
            --owners mlkdir moliere --first_name collab --last_name testing
            --type box --secure

        Note: If first and last names are not provided, they will be set
            automatically using common delimiters
        '''

    parser = argparse.ArgumentParser(
        description='Creates shared accounts in collab services',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--account',
        '-a',
        help='The account name to use.',
        required=True
    )
    parser.add_argument(
        '--password',
        '-p',
        help='The password to use for the account',
        required=True
    )
    parser.add_argument(
        '--owners',
        '-o',
        help='Owners for the shared account',
        nargs='+'
    )
    parser.add_argument(
404
        '--service',
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
        '-s',
        help='The type of account(s) to create',
        choices=[
            'google',
            'box',
            'both'
        ],
        default='both'
    )
    parser.add_argument(
        '--first_name',
        '-f',
        help='The first name to use for the account',
    )
    parser.add_argument(
        '--last_name',
        '-l',
        help='The last name to use for the account',
    )
    parser.add_argument(
        '--secure',
        help='Secure the account for sensitive data',
        action='store_true'
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use for Google operations',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
442
    logger = logging.getLogger(__name__)
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    logger.setLevel(logging.DEBUG)

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
    formatter = logging.Formatter(config['general']['console_format'])
    ch.setFormatter(formatter)
    logger.addHandler(ch)

460
    sa = SharedAccount(vars(args), config)
461
    sa.set_up_mcommunity_group()
462
    exit(2)
463
464
465
466
467
    sa.set_kerberos_password()
    if sa.service in ['box', 'both']:
        sa.create_box()
    if sa.service in ['google', 'both']:
        sa.create_google()
468
    pass_file_id = sa.upload_and_share_password()
469
470
471
472
473
474
475

    header_text = '''
Hello,

Your request has been completed. The password for your shared account
can be found at the following link:

476
https://docs.google.com/a/{}/file/d/{}
477
478
479
480
481
482

We recommend using a Chrome incognito window or separate browser to log
into your shared account. Please see below for more information about the
shared account created per your request:

General Account Information:
483
484
485
- Display Name: {}
- Username: {}
- Email Address: {}
486
'''.format(
487
488
        config['google']['domain'],
        pass_file_id,
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
        sa.full_name,
        sa.account,
        sa.email,
    )

    footer_text = '''
Single-Sign On is used for both Box and Google, and the method of changing
the password is the same for both. For information on changing the password,
please check the documentation found here:

https://documentation.its.umich.edu/node/339/#password

I will be closing this ticket now, as your request has been completed, but
feel free to reply back to this email if you have any questions or concerns
about your new account and the ticket will be re-opened.
'''

    print(
        '========== CANNED TEXT ==========',
        header_text,
509
510
        sa.box_text if hasattr(sa, 'box_text') else '',
        sa.google_text if hasattr(sa, 'google_text') else '',
511
512
513
514
515
516
        footer_text
    )


if __name__ == '__main__':
    main()