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