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