pass a record object (instead of dict) to determine_user_rights
[sfa.git] / sfa / managers / registry_manager.py
1 import types
2 # for get_key_from_incoming_ip
3 import tempfile
4 import os
5 import commands
6
7 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
8     UnknownSfaType, ExistingRecord, NonExistingRecord
9 from sfa.util.sfatime import utcparse, datetime_to_epoch
10 from sfa.util.prefixTree import prefixTree
11 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
12 from sfa.util.plxrn import hrn_to_pl_login_base
13 from sfa.util.version import version_core
14 from sfa.util.sfalogging import logger
15
16 from sfa.trust.gid import GID 
17 from sfa.trust.credential import Credential
18 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
19 from sfa.trust.gid import create_uuid
20
21 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey
22 from sfa.storage.alchemy import dbsession
23
24 class RegistryManager:
25
26     def __init__ (self, config): pass
27
28     # The GENI GetVersion call
29     def GetVersion(self, api, options):
30         peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems() 
31                        if hrn != api.hrn])
32         xrn=Xrn(api.hrn)
33         return version_core({'interface':'registry',
34                              'sfa': 2,
35                              'geni_api': 2,
36                              'hrn':xrn.get_hrn(),
37                              'urn':xrn.get_urn(),
38                              'peers':peers})
39     
40     def GetCredential(self, api, xrn, type, caller_xrn=None):
41         # convert xrn to hrn     
42         if type:
43             hrn = urn_to_hrn(xrn)[0]
44         else:
45             hrn, type = urn_to_hrn(xrn)
46             
47         # Is this a root or sub authority
48         auth_hrn = api.auth.get_authority(hrn)
49         if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
50             auth_hrn = hrn
51         auth_info = api.auth.get_auth_info(auth_hrn)
52         # get record info
53         record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
54         if not record:
55             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
56     
57         # verify_cancreate_credential requires that the member lists
58         # (researchers, pis, etc) be filled in
59         logger.debug("get credential before augment dict, keys=%s"%record.__dict__.keys())
60         self.driver.augment_records_with_testbed_info (record.__dict__)
61         logger.debug("get credential after augment dict, keys=%s"%record.__dict__.keys())
62         if not self.driver.is_enabled (record.__dict__):
63               raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record.email))
64     
65         # get the callers gid
66         # if caller_xrn is not specified assume the caller is the record
67         # object itself.
68         if not caller_xrn:
69             caller_hrn = hrn
70             caller_gid = record.get_gid_object()
71         else:
72             caller_hrn, caller_type = urn_to_hrn(caller_xrn)
73             if caller_type:
74                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
75             else:
76                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
77             if not caller_record:
78                 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
79             caller_gid = GID(string=caller_record.gid)
80  
81         object_hrn = record.get_gid_object().get_hrn()
82         # call the builtin authorization/credential generation engine
83         rights = api.auth.determine_user_rights(caller_hrn, record)
84         # make sure caller has rights to this object
85         if rights.is_empty():
86             raise PermissionError("%s has no rights to %s (%s)" % \
87                                   (caller_hrn, object_hrn, xrn))    
88         object_gid = GID(string=record.gid)
89         new_cred = Credential(subject = object_gid.get_subject())
90         new_cred.set_gid_caller(caller_gid)
91         new_cred.set_gid_object(object_gid)
92         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
93         #new_cred.set_pubkey(object_gid.get_pubkey())
94         new_cred.set_privileges(rights)
95         new_cred.get_privileges().delegate_all_privileges(True)
96         if hasattr(record,'expires'):
97             date = utcparse(record.expires)
98             expires = datetime_to_epoch(date)
99             new_cred.set_expiration(int(expires))
100         auth_kind = "authority,ma,sa"
101         # Parent not necessary, verify with certs
102         #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
103         new_cred.encode()
104         new_cred.sign()
105     
106         return new_cred.save_to_string(save_parents=True)
107     
108     
109     def Resolve(self, api, xrns, type=None, full=True):
110     
111         if not isinstance(xrns, types.ListType):
112             # try to infer type if not set and we get a single input
113             if not type:
114                 type = Xrn(xrns).get_type()
115             xrns = [xrns]
116         hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
117
118         # load all known registry names into a prefix tree and attempt to find
119         # the longest matching prefix
120         # create a dict where key is a registry hrn and its value is a list
121         # of hrns at that registry (determined by the known prefix tree).  
122         xrn_dict = {}
123         registries = api.registries
124         tree = prefixTree()
125         registry_hrns = registries.keys()
126         tree.load(registry_hrns)
127         for xrn in xrns:
128             registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
129             if registry_hrn not in xrn_dict:
130                 xrn_dict[registry_hrn] = []
131             xrn_dict[registry_hrn].append(xrn)
132             
133         records = [] 
134         for registry_hrn in xrn_dict:
135             # skip the hrn without a registry hrn
136             # XX should we let the user know the authority is unknown?       
137             if not registry_hrn:
138                 continue
139     
140             # if the best match (longest matching hrn) is not the local registry,
141             # forward the request
142             xrns = xrn_dict[registry_hrn]
143             if registry_hrn != api.hrn:
144                 credential = api.getCredential()
145                 interface = api.registries[registry_hrn]
146                 server_proxy = api.server_proxy(interface, credential)
147                 peer_records = server_proxy.Resolve(xrns, credential,type)
148                 # pass foreign records as-is
149                 # previous code used to read
150                 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
151                 # not sure why the records coming through xmlrpc had to be processed at all
152                 records.extend(peer_records)
153     
154         # try resolving the remaining unfound records at the local registry
155         local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
156         # 
157         local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
158         if type:
159             local_records = local_records.filter_by(type=type)
160         local_records=local_records.all()
161         logger.info("Resolve: local_records=%s (type=%s)"%(local_records,type))
162         local_dicts = [ record.__dict__ for record in local_records ]
163         
164         if full:
165             # in full mode we get as much info as we can, which involves contacting the 
166             # testbed for getting implementation details about the record
167             self.driver.augment_records_with_testbed_info(local_dicts)
168             # also we fill the 'url' field for known authorities
169             # used to be in the driver code, sounds like a poorman thing though
170             def solve_neighbour_url (record):
171                 if not record.type.startswith('authority'): return 
172                 hrn=record.hrn
173                 for neighbour_dict in [ api.aggregates, api.registries ]:
174                     if hrn in neighbour_dict:
175                         record.url=neighbour_dict[hrn].get_url()
176                         return 
177             for record in local_records: solve_neighbour_url (record)
178         
179         # convert local record objects to dicts for xmlrpc
180         # xxx somehow here calling dict(record) issues a weird error
181         # however record.todict() seems to work fine
182         # records.extend( [ dict(record) for record in local_records ] )
183         records.extend( [ record.todict() for record in local_records ] )    
184         if not records:
185             raise RecordNotFound(str(hrns))
186     
187         return records
188     
189     def List (self, api, xrn, origin_hrn=None):
190         hrn, type = urn_to_hrn(xrn)
191         # load all know registry names into a prefix tree and attempt to find
192         # the longest matching prefix
193         registries = api.registries
194         registry_hrns = registries.keys()
195         tree = prefixTree()
196         tree.load(registry_hrns)
197         registry_hrn = tree.best_match(hrn)
198        
199         #if there was no match then this record belongs to an unknow registry
200         if not registry_hrn:
201             raise MissingAuthority(xrn)
202         # if the best match (longest matching hrn) is not the local registry,
203         # forward the request
204         record_dicts = []    
205         if registry_hrn != api.hrn:
206             credential = api.getCredential()
207             interface = api.registries[registry_hrn]
208             server_proxy = api.server_proxy(interface, credential)
209             record_list = server_proxy.List(xrn, credential)
210             # same as above, no need to process what comes from through xmlrpc
211             # pass foreign records as-is
212             record_dicts = record_list
213         
214         # if we still have not found the record yet, try the local registry
215         if not record_dicts:
216             if not api.auth.hierarchy.auth_exists(hrn):
217                 raise MissingAuthority(hrn)
218             records = dbsession.query(RegRecord).filter_by(authority=hrn)
219             record_dicts=[ record.todict() for record in records ]
220     
221         return record_dicts
222     
223     
224     def CreateGid(self, api, xrn, cert):
225         # get the authority
226         authority = Xrn(xrn=xrn).get_authority_hrn()
227         auth_info = api.auth.get_auth_info(authority)
228         if not cert:
229             pkey = Keypair(create=True)
230         else:
231             certificate = Certificate(string=cert)
232             pkey = certificate.get_pubkey()    
233         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey) 
234         return gid.save_to_string(save_parents=True)
235     
236     ####################
237     # utility for handling relationships among the SFA objects 
238     # given that the SFA db does not handle this sort of relationsships
239     # it will rely on side-effects in the testbed to keep this persistent
240     
241     # subject_record describes the subject of the relationships
242     # ref_record contains the target values for the various relationships we need to manage
243     # (to begin with, this is just the slice x person relationship)
244     def update_relations (self, subject_obj, ref_obj):
245         type=subject_obj.type
246         if type=='slice':
247             self.update_relation(subject_obj, 'researcher', ref_obj.researcher, 'user')
248         
249     # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
250     # hrns is the list of hrns that should be linked to the subject from now on
251     # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
252     def update_relation (self, record_obj, field_key, hrns, target_type):
253         # locate the linked objects in our db
254         subject_type=record_obj.type
255         subject_id=record_obj.pointer
256         # get the 'pointer' field of all matching records
257         link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
258         # sqlalchemy returns named tuples for columns
259         link_ids = [ tuple.pointer for tuple in link_id_tuples ]
260         self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
261
262     def Register(self, api, record_dict):
263     
264         hrn, type = record_dict['hrn'], record_dict['type']
265         urn = hrn_to_urn(hrn,type)
266         # validate the type
267         if type not in ['authority', 'slice', 'node', 'user']:
268             raise UnknownSfaType(type) 
269         
270         # check if record_dict already exists
271         existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
272         if existing_records:
273             raise ExistingRecord(hrn)
274            
275         assert ('type' in record_dict)
276         # returns the right type of RegRecord according to type in record
277         record = make_record(dict=record_dict)
278         record.just_created()
279         record.authority = get_authority(record.hrn)
280         auth_info = api.auth.get_auth_info(record.authority)
281         pub_key = None
282         # make sure record has a gid
283         if not record.gid:
284             uuid = create_uuid()
285             pkey = Keypair(create=True)
286             if getattr(record,'keys',None):
287                 pub_key=record.keys
288                 # use only first key in record
289                 if isinstance(record.keys, types.ListType):
290                     pub_key = record.keys[0]
291                 pkey = convert_public_key(pub_key)
292     
293             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
294             gid = gid_object.save_to_string(save_parents=True)
295             record.gid = gid
296     
297         if isinstance (record, RegAuthority):
298             # update the tree
299             if not api.auth.hierarchy.auth_exists(hrn):
300                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
301     
302             # get the GID from the newly created authority
303             gid = auth_info.get_gid_object()
304             record.gid=gid.save_to_string(save_parents=True)
305
306         elif isinstance (record, RegSlice):
307             # locate objects for relationships
308             if hasattr (record, 'researcher'):
309                 # we get the list of researcher hrns as
310                 researcher_hrns = record.researcher
311                 # strip that in case we have <researcher> words </researcher>
312                 researcher_hrns = [ x.strip() for x in researcher_hrns ]
313                 logger.info ("incoming researchers %s"%researcher_hrns)
314                 request = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns))
315                 logger.info ("%d incoming hrns, %d matches found"%(len(researcher_hrns),request.count()))
316                 researchers = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns)).all()
317                 record.reg_researchers = researchers
318         
319         elif isinstance (record, RegUser):
320             # create RegKey objects for incoming keys
321             if hasattr(record,'keys'): 
322                 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
323                 record.reg_keys = [ RegKey (key) for key in record.keys ]
324             
325         # update testbed-specific data if needed
326         pointer = self.driver.register (record.__dict__, hrn, pub_key)
327
328         record.pointer=pointer
329         dbsession.add(record)
330         dbsession.commit()
331     
332         # update membership for researchers, pis, owners, operators
333         self.update_relations (record, record)
334         
335         return record.get_gid_object().save_to_string(save_parents=True)
336     
337     def Update(self, api, record_dict):
338         assert ('type' in record_dict)
339         new_record=RegRecord(dict=record_dict)
340         type = new_record.type
341         hrn = new_record.hrn
342         
343         # make sure the record exists
344         record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
345         if not record:
346             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
347         record.just_updated()
348     
349         # validate the type
350         if type not in ['authority', 'slice', 'node', 'user']:
351             raise UnknownSfaType(type) 
352
353         # Use the pointer from the existing record, not the one that the user
354         # gave us. This prevents the user from inserting a forged pointer
355         pointer = record.pointer
356     
357         # is the a change in keys ?
358         new_key=None
359         if type=='user':
360             if getattr(new_key,'keys',None):
361                 new_key=new_record.keys
362                 if isinstance (new_key,types.ListType):
363                     new_key=new_key[0]
364
365         # update the PLC information that was specified with the record
366         if not self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key):
367             logger.warning("driver.update failed")
368     
369         # take new_key into account
370         if new_key:
371             # update the openssl key and gid
372             pkey = convert_public_key(new_key)
373             uuid = create_uuid()
374             urn = hrn_to_urn(hrn,type)
375             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
376             gid = gid_object.save_to_string(save_parents=True)
377             record.gid = gid
378             dsession.commit()
379         
380         # update membership for researchers, pis, owners, operators
381         self.update_relations (record, new_record)
382         
383         return 1 
384     
385     # expecting an Xrn instance
386     def Remove(self, api, xrn, origin_hrn=None):
387         hrn=xrn.get_hrn()
388         type=xrn.get_type()
389         request=dbsession.query(RegRecord).filter_by(hrn=hrn)
390         if type and type not in ['all', '*']:
391             request=request.filter_by(type=type)
392     
393         record = request.first()
394         if not record:
395             msg="Could not find hrn %s"%hrn
396             if type: msg += " type=%s"%type
397             raise RecordNotFound(msg)
398
399         type = record.type
400         if type not in ['slice', 'user', 'node', 'authority'] :
401             raise UnknownSfaType(type)
402
403         credential = api.getCredential()
404         registries = api.registries
405     
406         # Try to remove the object from the PLCDB of federated agg.
407         # This is attempted before removing the object from the local agg's PLCDB and sfa table
408         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
409             for registry in registries:
410                 if registry not in [api.hrn]:
411                     try:
412                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
413                     except:
414                         pass
415
416         # call testbed callback first
417         # IIUC this is done on the local testbed TOO because of the refreshpeer link
418         if not self.driver.remove(record.__dict__):
419             logger.warning("driver.remove failed")
420
421         # delete from sfa db
422         dbsession.delete(record)
423         dbsession.commit()
424     
425         return 1
426
427     # This is a PLC-specific thing, won't work with other platforms
428     def get_key_from_incoming_ip (self, api):
429         # verify that the callers's ip address exist in the db and is an interface
430         # for a node in the db
431         (ip, port) = api.remote_addr
432         interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
433         if not interfaces:
434             raise NonExistingRecord("no such ip %(ip)s" % locals())
435         nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
436         if not nodes:
437             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
438         node = nodes[0]
439        
440         # look up the sfa record
441         record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
442         if not record:
443             raise RecordNotFound("node with pointer %s"%node['node_id'])
444         
445         # generate a new keypair and gid
446         uuid = create_uuid()
447         pkey = Keypair(create=True)
448         urn = hrn_to_urn(record.hrn, record.type)
449         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
450         gid = gid_object.save_to_string(save_parents=True)
451         record.gid = gid
452
453         # update the record
454         dbsession.commit()
455   
456         # attempt the scp the key
457         # and gid onto the node
458         # this will only work for planetlab based components
459         (kfd, key_filename) = tempfile.mkstemp() 
460         (gfd, gid_filename) = tempfile.mkstemp() 
461         pkey.save_to_file(key_filename)
462         gid_object.save_to_file(gid_filename, save_parents=True)
463         host = node['hostname']
464         key_dest="/etc/sfa/node.key"
465         gid_dest="/etc/sfa/node.gid" 
466         scp = "/usr/bin/scp" 
467         #identity = "/etc/planetlab/root_ssh_key.rsa"
468         identity = "/etc/sfa/root_ssh_key"
469         scp_options=" -i %(identity)s " % locals()
470         scp_options+="-o StrictHostKeyChecking=no " % locals()
471         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
472                          locals()
473         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
474                          locals()    
475
476         all_commands = [scp_key_command, scp_gid_command]
477         
478         for command in all_commands:
479             (status, output) = commands.getstatusoutput(command)
480             if status:
481                 raise Exception, output
482
483         for filename in [key_filename, gid_filename]:
484             os.unlink(filename)
485
486         return 1