cosmetic
[plcapi.git] / PLC / Keys.py
1 import re
2
3 from PLC.Faults import *
4 from PLC.Parameter import Parameter
5 from PLC.Filter import Filter
6 from PLC.Debug import profile
7 from PLC.Table import Row, Table
8 from PLC.KeyTypes import KeyType, KeyTypes
9
10 class Key(Row):
11     """
12     Representation of a row in the keys table. To use, instantiate with a 
13     dict of values. Update as you would a dict. Commit to the database 
14     with sync().
15     """
16
17     table_name = 'keys'
18     primary_key = 'key_id'
19     join_tables = ['person_key']
20     fields = {
21         'key_id': Parameter(int, "Key identifier"),
22         'key_type': Parameter(str, "Key type"),
23         'key': Parameter(str, "Key value", max = 4096),
24         'peer_id': Parameter(int, "Peer at which this node is managed", nullok = True),
25         }
26
27     # for Cache
28     class_key= 'key'
29     foreign_fields = ['key_type']
30     foreign_xrefs = []
31
32     def validate_key_type(self, key_type):
33         key_types = [row['key_type'] for row in KeyTypes(self.api)]
34         if key_type not in key_types:
35             raise PLCInvalidArgument, "Invalid key type"
36         return key_type
37
38     def validate_key(self, key):
39         # Key must not be blacklisted
40         rows = self.api.db.selectall("SELECT 1 from keys" \
41                                      " WHERE key = %(key)s" \
42                                      " AND is_blacklisted IS True",
43                                      locals())
44         if rows:
45             raise PLCInvalidArgument, "Key is blacklisted and cannot be used"
46
47         return key
48
49     def validate(self):
50         # Basic validation
51         Row.validate(self)
52
53         assert 'key' in self
54         key = self['key']
55
56         if self['key_type'] == 'ssh':
57             # Accept only SSH version 2 keys without options. From
58             # sshd(8):
59             #
60             # Each protocol version 2 public key consists of: options,
61             # keytype, base64 encoded key, comment.  The options field
62             # is optional...The comment field is not used for anything
63             # (but may be convenient for the user to identify the
64             # key). For protocol version 2 the keytype is ``ssh-dss''
65             # or ``ssh-rsa''.
66
67             good_ssh_key = r'^.*(?:ssh-dss|ssh-rsa)[ ]+[A-Za-z0-9+/=]+(?: .*)?$'
68             if not re.match(good_ssh_key, key, re.IGNORECASE):
69                 raise PLCInvalidArgument, "Invalid SSH version 2 public key"
70
71     def blacklist(self, commit = True):
72         """
73         Permanently blacklist key (and all other identical keys),
74         preventing it from ever being added again. Because this could
75         affect multiple keys associated with multiple accounts, it
76         should be admin only.        
77         """
78
79         assert 'key_id' in self
80         assert 'key' in self
81
82         # Get all matching keys
83         rows = self.api.db.selectall("SELECT key_id FROM keys WHERE key = %(key)s",
84                                      self)
85         key_ids = [row['key_id'] for row in rows]
86         assert key_ids
87         assert self['key_id'] in key_ids
88
89         # Keep the keys in the table
90         self.api.db.do("UPDATE keys SET is_blacklisted = True" \
91                        " WHERE key_id IN (%s)" % ", ".join(map(str, key_ids)))
92
93         # But disassociate them from all join tables
94         for table in ['person_key']:
95             self.api.db.do("DELETE FROM %s WHERE key_id IN (%s)" % \
96                            (table, ", ".join(map(str, key_ids))))
97
98         if commit:
99             self.api.db.commit()
100
101 class Keys(Table):
102     """
103     Representation of row(s) from the keys table in the
104     database.
105     """
106
107     def __init__(self, api, key_filter = None, columns = None):
108         Table.__init__(self, api, Key, columns)
109         
110         sql = "SELECT %s FROM keys WHERE is_blacklisted IS False" % \
111               ", ".join(self.columns)
112
113         if key_filter is not None:
114             if isinstance(key_filter, (list, tuple, set)):
115                 key_filter = Filter(Key.fields, {'key_id': key_filter})
116             elif isinstance(key_filter, dict):
117                 key_filter = Filter(Key.fields, key_filter)
118             sql += " AND (%s)" % key_filter.sql(api)
119
120         self.selectall(sql)