sfaclientlib improved
[sfa.git] / sfa / client / sfaclientlib.py
1 # Thierry Parmentelat -- INRIA
2 #
3 # a minimal library for writing "lightweight" SFA clients
4 #
5
6 import os,os.path
7
8 import sfa.util.sfalogging
9 # importing sfa.utils.faults does pull a lot of stuff 
10 # OTOH it's imported from Certificate anyways, so..
11 from sfa.util.faults import RecordNotFound
12
13 from sfa.client.sfaserverproxy import SfaServerProxy
14
15 # see optimizing dependencies below
16 from sfa.trust.certificate import Keypair, Certificate
17
18 ########## 
19 # a helper class to implement the bootstrapping of crypto. material
20 # assuming we are starting from scratch on the client side 
21 # what's needed to complete a full slice creation cycle
22 # (**) prerequisites: 
23 #  (*) a local private key 
24 #  (*) the corresp. public key in the registry 
25 # (**) step1: a self-signed certificate
26 #      default filename is <hrn>.sscert
27 # (**) step2: a user credential
28 #      obtained at the registry with GetSelfCredential
29 #      using the self-signed certificate as the SSL cert
30 #      default filename is <hrn>.user.cred
31 # (**) step3: a registry-provided certificate (i.e. a GID)
32 #      obtained at the registry using Resolve
33 #      using the step2 credential as credential
34 #      default filename is <hrn>.user.gid
35 #
36 # From that point on, the GID is used as the SSL certificate
37 # and the following can be done
38 #
39 # (**) retrieve a slice (or authority) credential 
40 #      obtained at the registry with GetCredential
41 #      using the (step2) user-credential as credential
42 #      default filename is <hrn>.<type>.cred
43 # (**) retrieve a slice (or authority) GID 
44 #      obtained at the registry with Resolve
45 #      using the (step2) user-credential as credential
46 #      default filename is <hrn>.<type>.cred
47
48
49 ########## Implementation notes
50 #
51 # (*) decorators
52 #
53 # this implementation is designed as a guideline for 
54 # porting to other languages
55 #
56 # the decision to go for decorators aims at focusing 
57 # on the core of what needs to be done when everything
58 # works fine, and to take caching and error management 
59 # out of the way
60
61 # for non-pythonic developers, it should be enough to 
62 # implement the bulk of this code, namely the _produce methods
63 # and to add caching and error management by whichever means 
64 # is available, including inline 
65 #
66 # (*) self-signed certificates
67
68 # still with other languages in mind, we've tried to keep the
69 # dependencies to the rest of the code as low as possible
70
71 # however this still relies on the sfa.trust.certificate module
72 # for the initial generation of a self-signed-certificate that
73 # is associated to the user's ssh-key
74 # (for user-friendliness, and for smooth operations with planetlab, 
75 # the usage model is to reuse an existing keypair)
76
77 # there might be a more portable, i.e. less language-dependant way, to
78 # implement this step by exec'ing the openssl command a known
79 # successful attempt at this approach that worked for Java is
80 # documented below
81 # http://nam.ece.upatras.gr/fstoolkit/trac/wiki/JavaSFAClient
82 #
83 ####################
84
85 class SfaClientException (Exception): pass
86
87 class SfaClientBootstrap:
88
89     # dir is mandatory but defaults to '.'
90     def __init__ (self, user_hrn, registry_url, dir=None, 
91                   verbose=False, timeout=None, logger=None):
92         self.hrn=user_hrn
93         self.registry_url=registry_url
94         if dir is None: dir="."
95         self.dir=dir
96         self.verbose=verbose
97         self.timeout=timeout
98         # default for the logger is to use the global sfa logger
99         if logger is None: 
100             logger = sfa.util.sfalogging.logger
101         self.logger=logger
102
103     ######################################## *_produce methods
104     ### step1
105     # unconditionnally create a self-signed certificate
106     def self_signed_cert_produce (self,output):
107         self.assert_private_key()
108         private_key_filename = self.private_key_filename()
109         keypair=Keypair(filename=private_key_filename)
110         self_signed = Certificate (subject = self.hrn)
111         self_signed.set_pubkey (keypair)
112         self_signed.set_issuer (keypair, self.hrn)
113         self_signed.sign ()
114         self_signed.save_to_file (output)
115         self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
116                               (self.hrn,output))
117         return output
118
119     ### step2 
120     # unconditionnally retrieve my credential (GetSelfCredential)
121     # we always use the self-signed-cert as the SSL cert
122     def my_credential_produce (self, output):
123         self.assert_self_signed_cert()
124         certificate_filename = self.self_signed_cert_filename()
125         certificate_string = self.plain_read (certificate_filename)
126         self.assert_private_key()
127         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
128                                          certificate_filename)
129         credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
130         self.plain_write (output, credential_string)
131         self.logger.debug("SfaClientBootstrap: Wrote result of GetSelfCredential in %s"%output)
132         return output
133
134     ### step3
135     # unconditionnally retrieve my GID - use the general form 
136     def my_gid_produce (self,output):
137         return self.gid_produce (output, self.hrn, "user")
138
139     ### retrieve any credential (GetCredential) unconditionnal form
140     # we always use the GID as the SSL cert
141     def credential_produce (self, output, hrn, type):
142         self.assert_my_gid()
143         certificate_filename = self.my_gid_filename()
144         self.assert_private_key()
145         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
146                                          certificate_filename)
147         self.assert_my_credential()
148         my_credential_string = self.my_credential_string()
149         credential_string=registry_proxy.GetCredential (my_credential_string, hrn, type)
150         self.plain_write (output, credential_string)
151         self.logger.debug("SfaClientBootstrap: Wrote result of GetCredential in %s"%output)
152         return output
153
154     def slice_credential_produce (self, output, hrn):
155         return self.credential_produce (output, hrn, "slice")
156
157     def authority_credential_produce (self, output, hrn):
158         return self.credential_produce (output, hrn, "authority")
159
160     ### retrieve any gid (Resolve) - unconditionnal form
161     # use my GID when available as the SSL cert, otherwise the self-signed
162     def gid_produce (self, output, hrn, type ):
163         try:
164             self.assert_my_gid()
165             certificate_filename = self.my_gid_filename()
166         except:
167             self.assert_self_signed_cert()
168             certificate_filename = self.self_signed_cert_filename()
169             
170         self.assert_private_key()
171         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
172                                          certificate_filename)
173         credential_string=self.plain_read (self.my_credential())
174         records = registry_proxy.Resolve (hrn, credential_string)
175         records=[record for record in records if record['type']==type]
176         if not records:
177             raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
178         record=records[0]
179         self.plain_write (output, record['gid'])
180         self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
181         return output
182
183     #################### public interface
184     
185     # return my_gid, run all missing steps in the bootstrap sequence
186     def bootstrap_my_gid (self):
187         self.self_signed_cert()
188         self.my_credential()
189         return self.my_gid()
190
191     # once we've bootstrapped we can use this object to issue any other SFA call
192     # always use my gid
193     def server_proxy (self, url):
194         self.assert_my_gid()
195         return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
196                                verbose=self.verbose, timeout=self.timeout)
197
198     # now in some cases the self-signed is enough
199     def server_proxy_simple (self, url):
200         self.assert_self_signed_cert()
201         return SfaServerProxy (url, self.private_key_filename(), self.self_signed_cert_filename(),
202                                verbose=self.verbose, timeout=self.timeout)
203
204     # this method can optionnally be invoked to ensure proper
205     # installation of the private key that belongs to this user
206     # installs private_key in working dir with expected name -- preserve mode
207     # typically user_private_key would be ~/.ssh/id_rsa
208     # xxx should probably check the 2 files are identical
209     def init_private_key_if_missing (self, user_private_key):
210         private_key_filename=self.private_key_filename()
211         if not os.path.isfile (private_key_filename):
212             key=self.plain_read(user_private_key)
213             self.plain_write(private_key_filename, key)
214             os.chmod(private_key_filename,os.stat(user_private_key).st_mode)
215             self.logger.debug("SfaClientBootstrap: Copied private key from %s into %s"%\
216                                   (user_private_key,private_key_filename))
217         
218     #################### private details
219     # stupid stuff
220     def fullpath (self, file): return os.path.join (self.dir,file)
221
222     # the expected filenames for the various pieces
223     def private_key_filename (self): 
224         return self.fullpath ("%s.pkey"%self.hrn)
225     def self_signed_cert_filename (self): 
226         return self.fullpath ("%s.sscert"%self.hrn)
227     def my_credential_filename (self):
228         return self.credential_filename (self.hrn, "user")
229     def credential_filename (self, hrn, type): 
230         return self.fullpath ("%s.%s.cred"%(hrn,type))
231     def slice_credential_filename (self, hrn): 
232         return self.credential_filename(hrn,'slice')
233     def authority_credential_filename (self, hrn): 
234         return self.credential_filename(hrn,'authority')
235     def my_gid_filename (self):
236         return self.gid_filename ("user", self.hrn)
237     def gid_filename (self, hrn, type): 
238         return self.fullpath ("%s.%s.gid"%(hrn,type))
239     
240
241 # optimizing dependencies
242 # originally we used classes GID or Credential or Certificate 
243 # like e.g. 
244 #        return Credential(filename=self.my_credential()).save_to_string()
245 # but in order to make it simpler to other implementations/languages..
246     def plain_read (self, filename):
247         infile=file(filename,"r")
248         result=infile.read()
249         infile.close()
250         return result
251
252     def plain_write (self, filename, contents):
253         outfile=file(filename,"w")
254         result=outfile.write(contents)
255         outfile.close()
256
257     def assert_filename (self, filename, kind):
258         if not os.path.isfile (filename):
259             raise IOError,"Missing %s file %s"%(kind,filename)
260         return True
261         
262     def assert_private_key (self): return self.assert_filename (self.private_key_filename(),"private key")
263     def assert_self_signed_cert (self): return self.assert_filename (self.self_signed_cert_filename(),"self-signed certificate")
264     def assert_my_credential (self): return self.assert_filename (self.my_credential_filename(),"user's credential")
265     def assert_my_gid (self): return self.assert_filename (self.my_gid_filename(),"user's GID")
266
267
268     # decorator to make up the other methods
269     def get_or_produce (filename_method, produce_method):
270         def wrap (f):
271             def wrapped (self, *args, **kw):
272                 filename=filename_method (self, *args, **kw)
273                 if os.path.isfile ( filename ): return filename
274                 try:
275                     produce_method (self, filename, *args, **kw)
276                     return filename
277                 except IOError:
278                     raise 
279                 except:
280                     import traceback
281                     traceback.print_exc()
282                     raise Exception, "Could not produce/retrieve %s"%filename
283             wrapped.__name__=f.__name__
284             return wrapped
285         return wrap
286
287     @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
288     def self_signed_cert (self): pass
289
290     @get_or_produce (my_credential_filename, my_credential_produce)
291     def my_credential (self): pass
292
293     @get_or_produce (my_gid_filename, my_gid_produce)
294     def my_gid (self): pass
295
296     @get_or_produce (credential_filename, credential_produce)
297     def credential (self, hrn, type): pass
298
299     @get_or_produce (slice_credential_filename, slice_credential_produce)
300     def slice_credential (self, hrn): pass
301
302     @get_or_produce (authority_credential_filename, authority_credential_produce)
303     def authority_credential (self, hrn): pass
304
305     @get_or_produce (gid_filename, gid_produce)
306     def gid (self, hrn, type ): pass
307
308
309     # get the credentials as strings, for inserting as API arguments
310     def my_credential_string (self): 
311         self.my_credential()
312         return self.plain_read(self.my_credential_filename())
313     def slice_credential_string (self, hrn): 
314         self.slice_credential(hrn)
315         return self.plain_read(self.slice_credential_filename(hrn))
316     def authority_credential_string (self, hrn): 
317         self.authority_credential(hrn)
318         return self.plain_read(self.authority_credential_filename(hrn))