models.py 16.3 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
from django.conf import settings
Lukas Burgey's avatar
Lukas Burgey committed
2
3
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
4
from django.db.models.signals import post_save, pre_delete
Lukas Burgey's avatar
Lukas Burgey committed
5
from django.dispatch import receiver
Lukas Burgey's avatar
Lukas Burgey committed
6
from requests.auth import HTTPBasicAuth
Lukas Burgey's avatar
Lukas Burgey committed
7
from rest_framework.authtoken.models import Token
Lukas Burgey's avatar
Lukas Burgey committed
8
import json
Lukas Burgey's avatar
Lukas Burgey committed
9
10
import pika
import requests
Lukas Burgey's avatar
Lukas Burgey committed
11
from .logging import logger
12

Lukas Burgey's avatar
Lukas Burgey committed
13

Lukas Burgey's avatar
Lukas Burgey committed
14
15
16
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
class RabbitMQInstance(models.Model):
17

Lukas Burgey's avatar
Lukas Burgey committed
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
    host = models.CharField(
            max_length=150,
            default='localhost',
            )
    exchange = models.CharField(
            max_length=150,
            default='deployments',
            )
    port = models.IntegerField(
            default=15672
            )
    path = models.CharField(
            max_length=150,
            default='api',
            )
    username = models.CharField(
            max_length=150,
            default='guest',
            )
    password = models.CharField(
            max_length=150,
            default='guest',
            )
    enabled = models.BooleanField(
            default=False,
            )

    def __str__(self):
        return self.host

Lukas Burgey's avatar
Lukas Burgey committed
48
49
    def msg(self, msg):
        return '[RabbitMQ:{}] {}'.format(self.host, msg)
Lukas Burgey's avatar
Lukas Burgey committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

    @property
    def api(self):
        return 'http://{}:{}/{}'.format(
                self.host,
                self.port,
                self.path,
                )

    @property
    def auth(self):
        return HTTPBasicAuth(
                self.username,
                self.password
                )

    @property
    def vhost(self):
        return '%2f'

70
71
72
73
74
75
76
77
78
79
80
81
82
    # singletons
    rabbitmq_connection = None
    rabbitmq_channel = None

    @property
    def connection(self):
        if self.rabbitmq_connection is None:
            rabbitmqconnection_properties = pika.ConnectionParameters(
                    host=self.host,
                    ssl=True,
                    )
            self.rabbitmq_connection = pika.BlockingConnection(
                    rabbitmqconnection_properties)
Lukas Burgey's avatar
Lukas Burgey committed
83
            logger.debug(self.msg('opened connection'))
84
85
86
87
88
89
90
91
92
93
94
95

        return self.rabbitmq_connection

    @property
    def channel(self):
        if self.rabbitmq_channel is None:
            self.rabbitmq_channel = self.connection.channel()
            self.rabbitmq_channel.exchange_declare(
                    exchange=self.exchange,
                    durable=True,
                    exchange_type='topic')
            self.rabbitmq_channel.confirm_delivery()
Lukas Burgey's avatar
Lukas Burgey committed
96
97
            logger.debug(self.msg('opened channel'))

98
99
        return self.rabbitmq_channel

Lukas Burgey's avatar
Lukas Burgey committed
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
    def get_uri(self, path):
        return '{}/{}'.format(self.api, path)

    def rest_get(self, api_path):
        r = requests.get(
                self.get_uri(api_path),
                auth=self.auth)
        r.raise_for_status()
        return r.json()

    # send a rest call with path and data to the rest interface of
    # the rabbitmq instance
    def rest_put(self, api_path, data):
        r = requests.put(
                self.get_uri(api_path),
                json=data,
                auth=self.auth)
        r.raise_for_status()
        return r

    def rest_del(self, api_path):
        r = requests.delete(
                self.get_uri(api_path),
                auth=self.auth)
        r.raise_for_status()
        return r

    def set_topic_permissions(self, site):
        username = site.client.username
        path = 'topic-permissions/{}/{}/'.format(
                self.vhost,
                username,
                )

        # set permissions for the correct topics
        # we construct a regex to match the services of the site
        services = ''
        omitBar = True
        for service in site.services.all():
            prefix = '|'
            if omitBar:
                prefix = ''
                omitBar = False

            services = services + prefix + service.name

        set_topic_permission_data = {
                'exchange': self.exchange,
                'write': '^$',
                'read': '^service\.({})$'.format(services),
                }

        return self.rest_put(path, set_topic_permission_data)

    # set permissions for the user
    def set_permissions(self, site):
        username = site.client.username
        path = 'permissions/{}/{}/'.format(
                self.vhost,
                username,
                )
        permission = '^(amq\.gen.*|{})'.format(self.exchange)
        set_permission_data = {
                'configure': permission,
                'write': permission,
                'read': permission,
                }

        return self.rest_put(path, set_permission_data)

    # create user at the rabbitmq instance
    def create_user(self, site):
        username = site.client.username
        path = 'users/{}/'.format(username)

        user_creation_data = {
                'password': str(site.client.auth_token.key),
                'tags': '',
                }

        return self.rest_put(path, user_creation_data)

    # delete user at the rabbitmq instance
    def delete_user(self, site):
        username = site.client.username
        path = 'users/{}/'.format(username)

        return self.rest_del(path)

    # PUBLIC API

    def register_site(self, site):
Lukas Burgey's avatar
Lukas Burgey committed
192
193
        logger.info(self.msg('register: {}'.format(
            print_client(site.client))))
Lukas Burgey's avatar
Lukas Burgey committed
194
195
196
197
198
199
        self.create_user(site)
        self.set_permissions(site)
        self.set_topic_permissions(site)

    def update_site(self, site):
        self.set_topic_permissions(site)
Lukas Burgey's avatar
Lukas Burgey committed
200
        logger.info(self.msg('updated permissions for {}'.format(
Lukas Burgey's avatar
Lukas Burgey committed
201
            print_client(site.client))))
Lukas Burgey's avatar
Lukas Burgey committed
202
203

    def deregister_site(self, site):
Lukas Burgey's avatar
Lukas Burgey committed
204
205
        logger.info(self.msg('deregistered {}'.format(
            print_client(site.client))))
Lukas Burgey's avatar
Lukas Burgey committed
206
207
208
209
210
211
212
213
214

    def is_client_connected(self, site):
        connections = self.rest_get("connections/")
        clients_for_site = [c
                            for c in connections
                            if c['user'] == site.client.username]
        return len(clients_for_site) > 0

    def disconnect(self):
Lukas Burgey's avatar
Lukas Burgey committed
215
        logger.debug(self.msg('closing connection'))
Lukas Burgey's avatar
Lukas Burgey committed
216
217
218
219
220
221
222
223
224
225
        self.connection.close()

    def service_routing_key(self, service):
        return 'service.' + service.name

    def online_clients(self, service):
        return [site
                for site in service.site.all()
                if self.is_client_connected(site)]

226
227
228
229
230
231
232
233
234
    def publish_by_service(self, service, msg):
        return self.channel.basic_publish(
                exchange=self.exchange,
                routing_key=self.service_routing_key(service),
                body=msg,
                properties=pika.BasicProperties(
                    delivery_mode=1,
                    ),
                )
Lukas Burgey's avatar
Lukas Burgey committed
235
236


237
# TODO dirty
Lukas Burgey's avatar
Lukas Burgey committed
238
239
240
241
def rabbitmq_instance():
    return RabbitMQInstance.objects.get(enabled=True)


Lukas Burgey's avatar
Lukas Burgey committed
242
class User(AbstractUser):
243
244
245
246
247
248
249
250
251
252
    TYPE_CHOICES = (
            ('apiclient', 'API-Client'),
            ('oidcuser', 'OIDC User'),
            ('admin', 'Admin'),
            )
    user_type = models.CharField(
            max_length=20,
            choices=TYPE_CHOICES,
            default='oidcuser',
            )
Lukas Burgey's avatar
Lukas Burgey committed
253
254
255
    sub = models.CharField(max_length=150, blank=True, null=True)
    password = models.CharField(max_length=150, blank=True, null=True)

Lukas Burgey's avatar
Lukas Burgey committed
256
257
258
259
260
261
    # we hide deleted keys here
    # the full list of ssh keys is at self._ssh_keys
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

Lukas Burgey's avatar
Lukas Burgey committed
262

263
264
265
266
267
268
269
def print_client(user):
    return '{}@{}'.format(
            user.username,
            user.site,
            )


Lukas Burgey's avatar
Lukas Burgey committed
270
271
272
273
274
275
276
277
278
279
280
281
def construct_user(user_info):
    return User(
            sub=user_info['sub'],
            name=user_info['name'],
            first_name=user_info['given_name'],
            last_name=user_info['family_name'],
            email=user_info['email'],
            username=user_info['email'],
            )


class Site(models.Model):
282
283
284
    client = models.OneToOneField(
            User,
            related_name='site',
285
            )
Lukas Burgey's avatar
Lukas Burgey committed
286
287
288
289
290
291
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)

    def __str__(self):
        return self.name

292
293
294
295
296
297
    # tasks which are still to be executed on this site
    @property
    def tasks(self):
        return [item.task
                for item
                in self.task_items.all()]
Lukas Burgey's avatar
Lukas Burgey committed
298

Lukas Burgey's avatar
Lukas Burgey committed
299
300
301
302

class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
303
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
304
305
            Site,
            related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
306
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
307
308
309
            Group,
            related_name='services',
            blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
310
311

    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
312
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
313
314
315
316
317


class SSHPublicKey(models.Model):
    name = models.CharField(max_length=150, unique=True)
    key = models.TextField(max_length=1000)
Lukas Burgey's avatar
Lukas Burgey committed
318
    # hidden field at the user
Lukas Burgey's avatar
Lukas Burgey committed
319
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
320
            User,
Lukas Burgey's avatar
Lukas Burgey committed
321
            related_name='_ssh_keys')
Lukas Burgey's avatar
Lukas Burgey committed
322

Lukas Burgey's avatar
Lukas Burgey committed
323
324
325
326
327
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
            default=False,
            editable=False,
            )
328

Lukas Burgey's avatar
Lukas Burgey committed
329
330
    def msg(self, msg):
        return '[SSHPublicKey:{}] {}'.format(self, msg)
331

332
333
334
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
335
    def delete_key(self):
Lukas Burgey's avatar
Lukas Burgey committed
336
337
        if (not self.tasks.exists() and not self.deployments.exists()):
            logger.info(self.msg('Direct deletion of key'))
338
339
340
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
341
        logger.info(self.msg('Deletion of key started'))
342
343
344
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
345
        # delete implies withdrawing the key from all clients
346
347
348
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
349
350
    # when a key is withdrawn by a client we try to finally delete it
    def try_final_deletion(self):
Lukas Burgey's avatar
Lukas Burgey committed
351
352
353
        if (self.deleted and not self.tasks.exists()):
            logger.info(self.msg(
                'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
354
355
356
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
357
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
358
359
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
360
361
362
        return self.name


363
364
365
# Deployment describes the credential state per user as it is supposed to be
# DeploymentTask is what is sent to the clients via rabbitmq
# The DeploymentTaskItem track the acknowledgements from the clients
Lukas Burgey's avatar
Lukas Burgey committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
class Deployment(models.Model):
    user = models.ForeignKey(
            User,
            related_name='deployments',
            on_delete=models.CASCADE,
            )
    service = models.ForeignKey(
            Service,
            related_name='deployments',
            on_delete=models.CASCADE,
            )
    # SET_NULL: we allow credentials to be deleted after deployment
    ssh_keys = models.ManyToManyField(
            SSHPublicKey,
            related_name='deployments',
            blank=True,
            )
383
384
385
386
387
388
389
390

    # these ssh keys are to be withdrawn by the clients
    ssh_keys_to_withdraw = models.ManyToManyField(
            SSHPublicKey,
            related_name='withdrawn_deployments',
            blank=True,
            )

391
392
393
    @property
    def withdrawals(self):
        return self.tasks.filter(action='withdraw')
Lukas Burgey's avatar
Lukas Burgey committed
394

395
396
397
    @property
    def deploys(self):
        return self.tasks.filter(action='deploy')
Lukas Burgey's avatar
Lukas Burgey committed
398

399
400
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
401

402
403
404
405
406
407
    def deploy_key(self, key):
        self.ssh_keys.add(key)

        if key in self.ssh_keys_to_withdraw.all():
            self.ssh_keys_to_withdraw.remove(key)
        self.save()
408
409
410

        # and delete outstanding tasks which are made obsolete by this task
        for withdrawal in self.withdrawals.filter(key=key):
Lukas Burgey's avatar
Lukas Burgey committed
411
412
            logger.debug(withdrawal.msg('now obsolete'))
            withdrawal.delete()
413
414
415
416
417
418
419
420

        # generate task
        task = DeploymentTask(
                action='deploy',
                deployment=self,
                key=key,
                )
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
421
        logger.debug(task.msg('generated'))
422
423
424
425
426
427
428
429

        # generate task items
        for site in self.service.site.all():
            deploy = DeploymentTaskItem(
                    task=task,
                    site=site,
                    )
            deploy.save()
Lukas Burgey's avatar
Lukas Burgey committed
430
            logger.debug(deploy.msg('generated'))
431
432
433

        # publish the task
        task.publish()
434
435
436
437
438
439
440
441

    def withdraw_key(self, key):
        self.ssh_keys.remove(key)

        # keys which are to be withdrawn by the clients
        self.ssh_keys_to_withdraw.add(key)
        self.save()

442
443
        # and delete outstanding tasks which are made obsolete by this task
        for deploy in self.deploys.filter(key=key):
Lukas Burgey's avatar
Lukas Burgey committed
444
445
            logger.debug(deploy.msg("now obsolete"))
            deploy.delete()
Lukas Burgey's avatar
Lukas Burgey committed
446

447
448
449
450
451
452
453
        # generate task
        task = DeploymentTask(
                action='withdraw',
                deployment=self,
                key=key,
                )
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
454
        logger.debug(task.msg('generated'))
Lukas Burgey's avatar
Lukas Burgey committed
455

456
457
458
459
460
461
462
        # generate task items
        for site in self.service.site.all():
            withdrawal = DeploymentTaskItem(
                    task=task,
                    site=site,
                    )
            withdrawal.save()
Lukas Burgey's avatar
Lukas Burgey committed
463
            logger.debug(withdrawal.msg('generated'))
464

465
466
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
467
468


469
470
471
472
473
474
475
476
477
478
479
480
481
482
class DeploymentTask(models.Model):
    ACTION_CHOICES = (
            ('deploy', 'deploy'),
            ('withdraw', 'withdraw'),
            )
    action = models.CharField(
            max_length=10,
            choices=ACTION_CHOICES,
            )
    key = models.ForeignKey(
            SSHPublicKey,
            related_name='tasks',
            on_delete=models.CASCADE,
            )
Lukas Burgey's avatar
Lukas Burgey committed
483
484
    deployment = models.ForeignKey(
            Deployment,
485
486
            related_name='tasks',
            on_delete=models.CASCADE,
Lukas Burgey's avatar
Lukas Burgey committed
487
488
489
490
491
492
493
494
495
496
            )

    @property
    def user(self):
        return self.deployment.user

    @property
    def service(self):
        return self.deployment.service

497
498
499
500
501
502
503
504
505
    def __str__(self):
        return "{}:{}:{}:{} - {}".format(
                self.id,
                self.deployment.service,
                self.deployment.user,
                self.key,
                self.action,
                )

Lukas Burgey's avatar
Lukas Burgey committed
506
507
    def msg(self, msg):
        return '[DeploymentTask:{}] {}'.format(self, msg)
508
509
510
511
512
513
514
515
516
517
518

    def publish(self):
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

        rabbitmq_instance().publish_by_service(
                self.service,
                msg)

    # the client acked the receipt and execution of the task for his site
    def item_finished(self, site):
Lukas Burgey's avatar
Lukas Burgey committed
519
520
521
        item = self.task_items.get(site=site)
        logger.debug(item.msg('done'))
        item.delete()
522
523
524
525
526
527

        if not self.task_items.exists():
            self.finished()

    # maintenance after all task items are done
    def finished(self):
Lukas Burgey's avatar
Lukas Burgey committed
528
        logger.info(self.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
529
        self.delete()
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547

        # check if this was the final withdraw in a key deletion
        if self.action == 'withdraw':
            self.key.try_final_deletion()


class DeploymentTaskItem(models.Model):
    task = models.ForeignKey(
            DeploymentTask,
            related_name='task_items',
            on_delete=models.CASCADE,
            )
    site = models.ForeignKey(
            Site,
            related_name='task_items',
            on_delete=models.CASCADE,
            )

Lukas Burgey's avatar
Lukas Burgey committed
548
    def __str__(self):
549
550
551
552
553
        return "{}@{}".format(
                self.task,
                self.site,
                )

Lukas Burgey's avatar
Lukas Burgey committed
554
555
    def msg(self, msg):
        return '[DeploymentTaskItem:{}] {}'.format(self, msg)
556

Lukas Burgey's avatar
Lukas Burgey committed
557

558
559
560
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if instance.user_type == 'apiclient' and created:
        Token.objects.create(user=instance)


@receiver(post_save, sender=Site)
def register_at_rabbitmq(
        sender, instance=None, created=False, **kwargs):
    if not created:
        return

    RabbitMQInstance().register_site(instance)


@receiver(pre_delete, sender=Site)
def deregister_at_rabbitmq(
        sender, instance=None, **kwargs):

    RabbitMQInstance().deregister_site(instance)