blob: 48d5955bc13f1c3afb1427b8ac4e3f26a134dda0 (
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
|
# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file
from custodia.message.common import InvalidMessage
from custodia.message.common import UnknownMessageType
from custodia.message.common import UnallowedMessage
from custodia.message.simple import SimpleKey
from custodia.message.kem import KEMHandler
default_types = ['simple', 'kem']
key_types = {'simple': SimpleKey,
'kem': KEMHandler}
class Validator(object):
"""Validates incoming messages."""
def __init__(self, allowed=None):
"""Creates a Validator object.
:param allowed: list of allowed message types (optional)
"""
self.allowed = allowed or default_types
self.types = dict()
for t in self.allowed:
self.types[t] = key_types[t]
def add_types(self, types):
self.types.update(types)
def parse(self, request, msg):
if not isinstance(msg, dict):
raise InvalidMessage('The message must be a dict')
if 'type' not in msg:
raise InvalidMessage('The type is missing')
if 'value' not in msg:
raise InvalidMessage('The value is missing')
if msg['type'] not in list(self.types.keys()):
raise UnknownMessageType("Type '%s' is unknown" % msg['type'])
if msg['type'] not in self.allowed:
raise UnallowedMessage("Message type '%s' not allowed" % (
msg['type'],))
handler = self.types[msg['type']](request)
handler.parse(msg['value'])
return handler
|