aboutsummaryrefslogtreecommitdiff
path: root/app/handlers/common.py
blob: ed734be0f0dda8db8596d013249153332cb73946 (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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Set of common functions for all handlers."""

import pymongo
import types

from bson import (
    objectid,
    tz_util,
)
from datetime import (
    date,
    datetime,
    time,
    timedelta,
)

import models
import models.token as mtoken
import utils

# Default value to calculate a date range in case the provided value is
# out of range.
DEFAULT_DATE_RANGE = 5

# All the available collections as key-value. The key is the same used for the
# URL configuration.
COLLECTIONS = {
    'boot': models.BOOT_COLLECTION,
    'defconfig': models.DEFCONFIG_COLLECTION,
    'job': models.JOB_COLLECTION,
}

# Handlers valid keys.
BOOT_VALID_KEYS = {
    'POST': {
        models.MANDATORY_KEYS: [
            models.ARCHITECTURE_KEY,
            models.BOARD_KEY,
            models.DEFCONFIG_KEY,
            models.JOB_KEY,
            models.KERNEL_KEY,
            models.LAB_NAME_KEY,
            models.VERSION_KEY,
        ],
        models.ACCEPTED_KEYS: [
            models.ARCHITECTURE_KEY,
            models.BOARD_KEY,
            models.BOOT_LOAD_ADDR_KEY,
            models.BOOT_LOG_HTML_KEY,
            models.BOOT_LOG_KEY,
            models.BOOT_RESULT_DESC_KEY,
            models.BOOT_RESULT_KEY,
            models.BOOT_RETRIES_KEY,
            models.BOOT_TIME_KEY,
            models.BOOT_WARNINGS_KEY,
            models.DEFCONFIG_FULL_KEY,
            models.DEFCONFIG_KEY,
            models.DTB_ADDR_KEY,
            models.DTB_APPEND_KEY,
            models.DTB_KEY,
            models.EMAIL_KEY,
            models.ENDIANNESS_KEY,
            models.FASTBOOT_CMD_KEY,
            models.FASTBOOT_KEY,
            models.GIT_BRANCH_KEY,
            models.GIT_COMMIT_KEY,
            models.GIT_DESCRIBE_KEY,
            models.GIT_URL_KEY,
            models.ID_KEY,
            models.INITRD_ADDR_KEY,
            models.JOB_KEY,
            models.KERNEL_IMAGE_KEY,
            models.KERNEL_KEY,
            models.LAB_NAME_KEY,
            models.NAME_KEY,
            models.STATUS_KEY,
            models.VERSION_KEY,
        ]
    },
    'GET': [
        models.ARCHITECTURE_KEY,
        models.BOARD_KEY,
        models.CREATED_KEY,
        models.DEFCONFIG_FULL_KEY,
        models.DEFCONFIG_ID_KEY,
        models.DEFCONFIG_KEY,
        models.ENDIANNESS_KEY,
        models.GIT_BRANCH_KEY,
        models.GIT_COMMIT_KEY,
        models.ID_KEY,
        models.JOB_ID_KEY,
        models.JOB_KEY,
        models.KERNEL_KEY,
        models.LAB_NAME_KEY,
        models.NAME_KEY,
        models.STATUS_KEY,
        models.WARNINGS_KEY,
    ],
    'DELETE': [
        models.BOARD_KEY,
        models.DEFCONFIG_FULL_KEY,
        models.DEFCONFIG_ID_KEY,
        models.DEFCONFIG_KEY,
        models.ID_KEY,
        models.JOB_ID_KEY,
        models.JOB_KEY,
        models.KERNEL_KEY,
        models.NAME_KEY,
    ]
}

COUNT_VALID_KEYS = {
    'GET': [
        models.ARCHITECTURE_KEY,
        models.BOARD_KEY,
        models.CREATED_KEY,
        models.DEFCONFIG_FULL_KEY,
        models.DEFCONFIG_ID_KEY,
        models.DEFCONFIG_KEY,
        models.ERRORS_KEY,
        models.GIT_BRANCH_KEY,
        models.GIT_COMMIT_KEY,
        models.GIT_DESCRIBE_KEY,
        models.ID_KEY,
        models.JOB_ID_KEY,
        models.JOB_KEY,
        models.KERNEL_CONFIG_KEY,
        models.KERNEL_IMAGE_KEY,
        models.KERNEL_KEY,
        models.MODULES_DIR_KEY,
        models.MODULES_KEY,
        models.NAME_KEY,
        models.PRIVATE_KEY,
        models.STATUS_KEY,
        models.SYSTEM_MAP_KEY,
        models.TEXT_OFFSET_KEY,
        models.TIME_KEY,
        models.WARNINGS_KEY,
    ],
}

DEFCONFIG_VALID_KEYS = {
    'GET': [
        models.ARCHITECTURE_KEY,
        models.BUILD_LOG_KEY,
        models.CREATED_KEY,
        models.DEFCONFIG_FULL_KEY,
        models.DEFCONFIG_KEY,
        models.DIRNAME_KEY,
        models.ERRORS_KEY,
        models.GIT_BRANCH_KEY,
        models.GIT_COMMIT_KEY,
        models.GIT_DESCRIBE_KEY,
        models.ID_KEY,
        models.JOB_ID_KEY,
        models.JOB_KEY,
        models.KCONFIG_FRAGMENTS_KEY,
        models.KERNEL_CONFIG_KEY,
        models.KERNEL_IMAGE_KEY,
        models.KERNEL_KEY,
        models.MODULES_DIR_KEY,
        models.MODULES_KEY,
        models.NAME_KEY,
        models.STATUS_KEY,
        models.SYSTEM_MAP_KEY,
        models.TEXT_OFFSET_KEY,
        models.WARNINGS_KEY,
    ],
}

TOKEN_VALID_KEYS = {
    'POST': [
        models.ADMIN_KEY,
        models.DELETE_KEY,
        models.EMAIL_KEY,
        models.EXPIRES_KEY,
        models.GET_KEY,
        models.IP_ADDRESS_KEY,
        models.IP_RESTRICTED,
        models.NAME_KEY,
        models.POST_KEY,
        models.SUPERUSER_KEY,
        models.USERNAME_KEY,
    ],
    'GET': [
        models.CREATED_KEY,
        models.EMAIL_KEY,
        models.EXPIRED_KEY,
        models.EXPIRES_KEY,
        models.ID_KEY,
        models.IP_ADDRESS_KEY,
        models.NAME_KEY,
        models.PROPERTIES_KEY,
        models.TOKEN_KEY,
        models.USERNAME_KEY,
    ],
}

SUBSCRIPTION_VALID_KEYS = {
    'GET': [
        models.JOB_KEY
    ],
    'POST': [
        models.EMAIL_KEY,
        models.JOB_KEY,
    ],
    'DELETE': [
        models.EMAIL_KEY
    ],
}

JOB_VALID_KEYS = {
    'POST': [
        models.JOB_KEY,
        models.KERNEL_KEY
    ],
    'GET': [
        models.CREATED_KEY,
        models.ID_KEY,
        models.JOB_KEY,
        models.KERNEL_KEY,
        models.NAME_KEY,
        models.PRIVATE_KEY,
        models.STATUS_KEY,
    ],
}

BATCH_VALID_KEYS = {
    "POST": [
        models.COLLECTION_KEY,
        models.DOCUMENT_ID_KEY,
        models.METHOD_KEY,
        models.OP_ID_KEY,
        models.QUERY_KEY,
    ]
}

LAB_VALID_KEYS = {
    "POST": {
        models.MANDATORY_KEYS: [
            models.CONTACT_KEY,
            models.NAME_KEY,
        ],
        models.ACCEPTED_KEYS: [
            models.ADDRESS_KEY,
            models.CONTACT_KEY,
            models.NAME_KEY,
            models.PRIVATE_KEY,
            models.TOKEN_KEY,
            models.VERSION_KEY,
        ]
    },
    "GET": [
        models.ADDRESS_KEY,
        models.CONTACT_KEY,
        models.CREATED_KEY,
        models.ID_KEY,
        models.NAME_KEY,
        models.PRIVATE_KEY,
        models.TOKEN_KEY,
        models.UPDATED_KEY,
    ],
    "DELETE": [
        models.ADDRESS_KEY,
        models.CONTACT_KEY,
        models.ID_KEY,
        models.NAME_KEY,
        models.TOKEN_KEY,
    ]
}

ID_KEYS = [
    models.BOOT_ID_KEY,
    models.DEFCONFIG_ID_KEY,
    models.ID_KEY,
    models.JOB_ID_KEY,
    models.LAB_ID_KEY,
]

MASTER_KEY = 'master_key'
API_TOKEN_HEADER = 'Authorization'
ACCEPTED_CONTENT_TYPE = 'application/json'
DEFAULT_RESPONSE_TYPE = 'application/json; charset=UTF-8'
NOT_VALID_TOKEN = "Operation not permitted: check the token permissions"


def get_all_query_values(query_args_func, valid_keys):
    """Handy function to get all query args in a batch.

    :param query_args_func: A function used to return a list of the query
    arguments.
    :type query_args_func: function
    :param valid_keys: A list containing the valid keys that should be
    retrieved.
    :type valid_keys: list
    """
    spec = get_query_spec(query_args_func, valid_keys)

    get_and_add_date_range(spec, query_args_func)
    update_id_fields(spec)

    sort = get_query_sort(query_args_func)
    fields = get_query_fields(query_args_func)
    skip, limit = get_skip_and_limit(query_args_func)
    unique = get_aggregate_value(query_args_func)

    return (spec, sort, fields, skip, limit, unique)


def update_id_fields(spec):
    """Make sure ID fields are treated correctly.

    If we search for an ID field, either _id or like job_id, that references
    a real _id in mongodb, we need to make sure they are treated as such.
    mongodb stores them as ObjectId elements.

    :param spec: The spec data structure with the parameters to check.
    """
    if spec:
        common_keys = list(set(ID_KEYS) & set(spec.viewkeys()))
        for key in common_keys:
            spec[key] = objectid.ObjectId(spec[key])


def get_aggregate_value(query_args_func):
    """Get teh value of the aggregate key.

    :param query_args_func: A function used to return a list of the query
    arguments.
    :type query_args_func: function
    :return The aggregate value as string.
    """
    aggregate = query_args_func(models.AGGREGATE_KEY)
    if all([aggregate and isinstance(aggregate, types.ListType)]):
        aggregate = aggregate[-1]
    else:
        aggregate = None
    return aggregate


def get_query_spec(query_args_func, valid_keys):
    """Get values from the query string to build a `spec` data structure.

    A `spec` data structure is a dictionary whose keys are the keys
    accepted by this handler method.

    :param query_args_func: A function used to return a list of the query
    arguments.
    :type query_args_func: function
    :param valid_keys: A list containing the valid keys that should be
    retrieved.
    :type valid_keys: list
    :return A `spec` data structure (dictionary).
    """
    def _get_spec_values():
        """Get the values for the spec data structure.

        Internally used only, with some logic to differentiate between single
        and multiple values. Makes sure also that the list of values if valid,
        meaning that we do not have None or empty values.

        :return A tuple with the key and its value.
        """
        for key in valid_keys:
            val = query_args_func(key) or []
            if val:
                # Go through the values and make sure we have valid ones.
                val = [v for v in val if v]
                len_val = len(val)

                if len_val == 1:
                    val = val[0]
                elif len_val > 1:
                    # More than one value, make sure we look for all of them.
                    val = {'$in': val}

            yield key, val

    spec = {}
    if all([valid_keys and isinstance(valid_keys, types.ListType)]):
        spec = {
            k: v for k, v in [
                (key, val)
                for key, val in _get_spec_values()
                if val
            ]
        }

    return spec


def get_and_add_date_range(spec, query_args_func):
    """Retrieve the `date_range` query from the request.

    Add the retrieved `date_range` value into the provided `spec` data
    structure.

    :param spec: The dictionary where to store the key-value.
    :type spec: dictionary
    :param query_args_func: A function used to return a list of query
    arguments.
    :type query_args_func: function
    :return The passed `spec` updated.
    """
    date_range = query_args_func(models.DATE_RANGE_KEY)
    if date_range:
        # Today needs to be set at the end of the day!
        today = datetime.combine(
            date.today(), time(23, 59, 59, tzinfo=tz_util.utc)
        )
        previous = calculate_date_range(date_range)

        spec[models.CREATED_KEY] = {'$gte': previous, '$lt': today}
    return spec


def calculate_date_range(date_range):
    """Calculate the new date subtracting the passed number of days.

    It removes the passed days from today date, calculated at midnight
    UTC.

    :param date_range: The number of days to remove from today.
    :type date_range int, long, str
    :return A new `datetime.date` object that is the result of the
    subtraction of `datetime.date.today()` and
    `datetime.timedelta(days=date_range)`.
    """
    if isinstance(date_range, types.ListType):
        date_range = date_range[-1]

    if isinstance(date_range, types.StringTypes):
        try:
            date_range = int(date_range)
        except ValueError:
            utils.LOG.error(
                "Wrong value passed to date_range: %s", date_range
            )
            date_range = DEFAULT_DATE_RANGE

    date_range = abs(date_range)
    if date_range > timedelta.max.days:
        date_range = DEFAULT_DATE_RANGE

    # Calcuate with midnight in mind though, so we get the starting of
    # the day for the previous date.
    today = datetime.combine(
        date.today(), time(tzinfo=tz_util.utc)
    )
    delta = timedelta(days=date_range)

    return today - delta


def get_query_fields(query_args_func):
    """Get values from the query string to build a `fields` data structure.

    A `fields` data structure can be either a list or a dictionary.

    :param query_args_func: A function used to return a list of query
    arguments.
    :type query_args_func: function
    :return A `fields` data structure (list or dictionary).
    """
    fields = None
    y_fields, n_fields = map(
        query_args_func, [models.FIELD_KEY, models.NOT_FIELD_KEY]
    )

    if y_fields and not n_fields:
        fields = list(set(y_fields))
    elif n_fields:
        fields = dict.fromkeys(list(set(y_fields)), True)
        fields.update(dict.fromkeys(list(set(n_fields)), False))

    return fields


def get_query_sort(query_args_func):
    """Get values from the query string to build a `sort` data structure.

    A `sort` data structure is a list of tuples in a `key-value` fashion.
    The keys are the values passed as the `sort` argument on the query,
    they values are based on the `sort_order` argument and defaults to the
    descending order.

    :param query_args_func: A function used to return a list of query
    arguments.
    :type query_args_func: function
    :return A `sort` data structure, or None.
    """
    sort = None
    sort_fields, sort_order = map(
        query_args_func, [models.SORT_KEY, models.SORT_ORDER_KEY]
    )

    if sort_fields:
        if all([sort_order, isinstance(sort_order, types.ListType)]):
            sort_order = int(sort_order[-1])
        else:
            sort_order = pymongo.DESCENDING

        # Wrong number for sort order? Force descending.
        if all([sort_order != pymongo.ASCENDING,
                sort_order != pymongo.DESCENDING]):
            utils.LOG.warn(
                "Wrong sort order used (%d), default to %d",
                sort_order, pymongo.DESCENDING
            )
            sort_order = pymongo.DESCENDING

        sort = [
            (field, sort_order)
            for field in sort_fields
        ]

    return sort


def get_skip_and_limit(query_args_func):
    """Retrieve the `skip` and `limit` query arguments.

    :param query_args_func: A function used to return a list of query
    arguments.
    :type query_args_func: function
    :return A tuple with the `skip` and `limit` arguments.
    """
    skip, limit = map(query_args_func, [models.SKIP_KEY, models.LIMIT_KEY])

    if all([skip, isinstance(skip, types.ListType)]):
        skip = int(skip[-1])
    else:
        skip = 0

    if all([limit, isinstance(limit, types.ListType)]):
        limit = int(limit[-1])
    else:
        limit = 0

    return skip, limit


def valid_token_general(token, method):
    """Make sure the token can be used for an HTTP method.

    :param token: The Token object to validate.
    :param method: The HTTP verb this token is being validated for.
    :return True or False.
    """
    valid_token = False

    if method == "GET" and token.is_get_token:
        valid_token = True
    elif method == "POST" and token.is_post_token:
        valid_token = True
    elif method == "DELETE" and token.is_delete_token:
        valid_token = True

    return valid_token


def valid_token_th(token, method):
    """Make sure a token is a valid token for the `TokenHandler`.

    A valid `TokenHandler` token is an admin token, or a superuser token
    for GET operations.

    :param token: The Token object to validate.
    :param method: The HTTP verb this token is being validated for.
    :return True or False.
    """
    valid_token = False

    if token.is_admin:
        valid_token = True
    elif token.is_superuser and method == "GET":
        valid_token = True

    return valid_token


def validate_token(token_obj, method, remote_ip, validate_func):
    """Make sure the passed token is valid.

    :param token_obj: The JSON object from the db that contains the token.
    :param method: The HTTP verb this token is being validated for.
    :param remote_ip: The remote IP address sending the token.
    :param validate_func: Function called to validate the token, must accept
        a Token object and the method string.
    :return True or False.
    """
    valid_token = True

    if token_obj:
        token = mtoken.Token.from_json(token_obj)

        if not isinstance(token, mtoken.Token):
            utils.LOG.error("Retrieved token is not a Token object")
            valid_token = False
        else:
            valid_token &= validate_func(token, method)

            if token.is_ip_restricted and \
                    not _valid_token_ip(token, remote_ip):
                valid_token = False
    else:
        valid_token = False

    return valid_token


def _valid_token_ip(token, remote_ip):
    """Make sure the token comes from the designated IP addresses.

    :param token: The Token object to validate.
    :param remote_ip: The remote IP address sending the token.
    :return True or False.
    """
    valid_token = False

    if remote_ip:
        remote_ip = mtoken.convert_ip_address(remote_ip)

        if remote_ip in token.ip_address:
            valid_token = True
        else:
            utils.LOG.warn(
                "IP restricted token from wrong IP address: %s",
                remote_ip
            )
    else:
        utils.LOG.info("No remote IP address provided, cannot validate token")

    return valid_token