d836964a221af53710437ee1b4fe73c9dfec239c
[tests.git] / qaapi / qa / tests / sync_person_key.py
1 #!/usr/bin/python
2 import os, sys
3 from Test import Test
4 from qa import utils
5
6 class sync_person_key(Test):
7     """
8     Make sure specified users public key on file matches whats 
9     recorded at plc. Create a public/private keypair for the 
10     specified user if one doesnt exist already.  
11     """
12
13     def make_keys(self, path, name):
14         
15         if not os.path.isdir(path):
16             os.mkdir(path)
17         key_path = path + os.sep + name
18         command = "ssh-keygen -f %(key_path)s -t rsa -N ''"  % locals()
19         (stdout, stderr) = utils.popen(command)
20
21     def call(self, email):
22         api = self.config.api
23         auth = self.config.auth
24         email_parts = email.split("@")
25         keys_filename = email_parts[0]
26         keys_path = self.config.KEYS_PATH 
27         private_key_path = keys_path + os.sep + keys_filename
28         public_key_path = private_key_path + ".pub"
29         
30         # Validate person
31         persons = api.GetPersons(auth, [email], ['person_id', 'key_ids'])
32         if not persons:
33             raise Exception, "No such person %(email)s"
34         person = persons[0]
35
36         # make keys if they dont already exist  
37         if not os.path.isfile(private_key_path) or \
38            not os.path.isfile(public_key_path):
39             # Make new keys
40             self.make_keys(keys_path, keys_filename)
41             if self.config.verbose:
42                 utils.header("Made new key pair %(private_key_path)s %(public_key_path)s " %\
43                 locals())
44             
45         # sync public key  
46         public_key_file = open(public_key_path, 'r')
47         public_key = public_key_file.readline()
48                 
49         keys = api.GetKeys(auth, person['key_ids'])
50         if not keys:
51             # Add current key to db
52             key_fields = {'key_type': 'ssh',
53                           'key': public_key}
54             api.AddPersonKey(auth, person['person_id'], key_fields)
55             if self.config.verbose:
56                 utils.header("Added public key in %(public_key_path)s to db" % locals() )
57         else:
58             # keys need to be checked and possibly updated
59             key = keys[0]
60             if key['key'] != public_key:
61                 api.UpdateKey(auth, key['key_id'], public_key)
62                 if self.config.verbose:
63                     utils.header("Updated plc with new public key in %(public_key_path)s " % locals())
64             else:
65                 if self.config.verbose:
66                     utils.header("Key in %(public_key_path)s matchs public key in plc" % locals())                      
67
68 if __name__ == '__main__':
69     args = tuple(sys.argv[1:])
70     sync_person_key()(*args)            
71