Merge branch 'master' of ssh://git.onelab.eu/git/sfa
[sfa.git] / sfa / managers / registry_manager.py
1 import types
2 import time 
3
4 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
5     UnknownSfaType, ExistingRecord
6 from sfa.util.prefixTree import prefixTree
7 from sfa.util.record import SfaRecord
8 from sfa.util.table import SfaTable
9 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
10 from sfa.util.plxrn import hrn_to_pl_login_base
11 from sfa.util.version import version_core
12
13 from sfa.trust.gid import GID 
14 from sfa.trust.credential import Credential
15 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
16 from sfa.trust.gid import create_uuid
17
18 # The GENI GetVersion call
19 def GetVersion(api):
20     peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.iteritems() 
21                    if peername != api.hrn])
22     xrn=Xrn(api.hrn)
23     return version_core({'interface':'registry',
24                          'hrn':xrn.get_hrn(),
25                          'urn':xrn.get_urn(),
26                          'peers':peers})
27
28 def get_credential(api, xrn, type, is_self=False):
29     # convert xrn to hrn     
30     if type:
31         hrn = urn_to_hrn(xrn)[0]
32     else:
33         hrn, type = urn_to_hrn(xrn)
34         
35     # Is this a root or sub authority
36     auth_hrn = api.auth.get_authority(hrn)
37     if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
38         auth_hrn = hrn
39     # get record info
40     auth_info = api.auth.get_auth_info(auth_hrn)
41     table = SfaTable()
42     records = table.findObjects({'type': type, 'hrn': hrn})
43     if not records:
44         raise RecordNotFound(hrn)
45     record = records[0]
46
47     # verify_cancreate_credential requires that the member lists
48     # (researchers, pis, etc) be filled in
49     api.fill_record_info(record)
50     if record['type']=='user':
51        if not record['enabled']:
52           raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
53
54     # get the callers gid
55     # if this is a self cred the record's gid is the caller's gid
56     if is_self:
57         caller_hrn = hrn
58         caller_gid = record.get_gid_object()
59     else:
60         caller_gid = api.auth.client_cred.get_gid_caller() 
61         caller_hrn = caller_gid.get_hrn()
62     
63     object_hrn = record.get_gid_object().get_hrn()
64     rights = api.auth.determine_user_rights(caller_hrn, record)
65     # make sure caller has rights to this object
66     if rights.is_empty():
67         raise PermissionError(caller_hrn + " has no rights to " + record['name'])
68
69     object_gid = GID(string=record['gid'])
70     new_cred = Credential(subject = object_gid.get_subject())
71     new_cred.set_gid_caller(caller_gid)
72     new_cred.set_gid_object(object_gid)
73     new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
74     #new_cred.set_pubkey(object_gid.get_pubkey())
75     new_cred.set_privileges(rights)
76     new_cred.get_privileges().delegate_all_privileges(True)
77     if 'expires' in record:
78         new_cred.set_expiration(int(record['expires']))
79     auth_kind = "authority,ma,sa"
80     # Parent not necessary, verify with certs
81     #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
82     new_cred.encode()
83     new_cred.sign()
84
85     return new_cred.save_to_string(save_parents=True)
86
87
88 def resolve(api, xrns, type=None, full=True):
89
90     # load all known registry names into a prefix tree and attempt to find
91     # the longest matching prefix
92     if not isinstance(xrns, types.ListType):
93         if not type:
94             type = Xrn(xrns).get_type()
95         xrns = [xrns]
96     hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
97     # create a dict where key is a registry hrn and its value is a
98     # hrns at that registry (determined by the known prefix tree).  
99     xrn_dict = {}
100     registries = api.registries
101     tree = prefixTree()
102     registry_hrns = registries.keys()
103     tree.load(registry_hrns)
104     for xrn in xrns:
105         registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
106         if registry_hrn not in xrn_dict:
107             xrn_dict[registry_hrn] = []
108         xrn_dict[registry_hrn].append(xrn)
109         
110     records = [] 
111     for registry_hrn in xrn_dict:
112         # skip the hrn without a registry hrn
113         # XX should we let the user know the authority is unknown?       
114         if not registry_hrn:
115             continue
116
117         # if the best match (longest matching hrn) is not the local registry,
118         # forward the request
119         xrns = xrn_dict[registry_hrn]
120         if registry_hrn != api.hrn:
121             credential = api.getCredential()
122             peer_records = registries[registry_hrn].Resolve(xrns, credential)
123             records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
124
125     # try resolving the remaining unfound records at the local registry
126     remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
127     # convert set to list
128     remaining_hrns = [hrn for hrn in remaining_hrns] 
129     table = SfaTable()
130     local_records = table.findObjects({'hrn': remaining_hrns})
131     if full:
132         api.fill_record_info(local_records)
133     
134     # convert local record objects to dicts
135     records.extend([dict(record) for record in local_records])
136     if not records:
137         raise RecordNotFound(str(hrns))
138
139     if type:
140         records = filter(lambda rec: rec['type'] in [type], records)
141
142     return records
143
144 def list(api, xrn, origin_hrn=None):
145     hrn, type = urn_to_hrn(xrn)
146     # load all know registry names into a prefix tree and attempt to find
147     # the longest matching prefix
148     records = []
149     registries = api.registries
150     registry_hrns = registries.keys()
151     tree = prefixTree()
152     tree.load(registry_hrns)
153     registry_hrn = tree.best_match(hrn)
154    
155     #if there was no match then this record belongs to an unknow registry
156     if not registry_hrn:
157         raise MissingAuthority(xrn)
158     
159     # if the best match (longest matching hrn) is not the local registry,
160     # forward the request
161     records = []    
162     if registry_hrn != api.hrn:
163         credential = api.getCredential()
164         record_list = registries[registry_hrn].List(xrn, credential)
165         records = [SfaRecord(dict=record).as_dict() for record in record_list]
166     
167     # if we still have not found the record yet, try the local registry
168     if not records:
169         if not api.auth.hierarchy.auth_exists(hrn):
170             raise MissingAuthority(hrn)
171
172         table = SfaTable()
173         records = table.find({'authority': hrn})
174
175     return records
176
177
178 def create_gid(api, xrn, cert):
179     # get the authority
180     authority = Xrn(xrn=xrn).get_authority_hrn()
181     auth_info = api.auth.get_auth_info(authority)
182     if not cert:
183         pkey = Keypair(create=True)
184     else:
185         certificate = Certificate(string=cert)
186         pkey = certificate.get_pubkey()    
187     gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey) 
188     return gid.save_to_string(save_parents=True)
189     
190 def register(api, record):
191
192     hrn, type = record['hrn'], record['type']
193     urn = hrn_to_urn(hrn,type)
194     # validate the type
195     if type not in ['authority', 'slice', 'node', 'user']:
196         raise UnknownSfaType(type) 
197     
198     # check if record already exists
199     table = SfaTable()
200     existing_records = table.find({'type': type, 'hrn': hrn})
201     if existing_records:
202         raise ExistingRecord(hrn)
203        
204     record = SfaRecord(dict = record)
205     record['authority'] = get_authority(record['hrn'])
206     type = record['type']
207     hrn = record['hrn']
208     auth_info = api.auth.get_auth_info(record['authority'])
209     pub_key = None
210     # make sure record has a gid
211     if 'gid' not in record:
212         uuid = create_uuid()
213         pkey = Keypair(create=True)
214         if 'key' in record and record['key']:
215             if isinstance(record['key'], types.ListType):
216                 pub_key = record['key'][0]
217             else:
218                 pub_key = record['key']
219             pkey = convert_public_key(pub_key)
220
221         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
222         gid = gid_object.save_to_string(save_parents=True)
223         record['gid'] = gid
224         record.set_gid(gid)
225
226     if type in ["authority"]:
227         # update the tree
228         if not api.auth.hierarchy.auth_exists(hrn):
229             api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
230
231         # get the GID from the newly created authority
232         gid = auth_info.get_gid_object()
233         record.set_gid(gid.save_to_string(save_parents=True))
234         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
235         sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
236         if not sites:
237             pointer = api.plshell.AddSite(api.plauth, pl_record)
238         else:
239             pointer = sites[0]['site_id']
240
241         record.set_pointer(pointer)
242         record['pointer'] = pointer
243
244     elif (type == "slice"):
245         acceptable_fields=['url', 'instantiation', 'name', 'description']
246         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
247         for key in pl_record.keys():
248             if key not in acceptable_fields:
249                 pl_record.pop(key)
250         slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
251         if not slices:
252              pointer = api.plshell.AddSlice(api.plauth, pl_record)
253         else:
254              pointer = slices[0]['slice_id']
255         record.set_pointer(pointer)
256         record['pointer'] = pointer
257
258     elif  (type == "user"):
259         persons = api.plshell.GetPersons(api.plauth, [record['email']])
260         if not persons:
261             pointer = api.plshell.AddPerson(api.plauth, dict(record))
262         else:
263             pointer = persons[0]['person_id']
264
265         if 'enabled' in record and record['enabled']:
266             api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
267         # add this persons to the site only if he is being added for the first
268         # time by sfa and doesont already exist in plc
269         if not persons or not persons[0]['site_ids']:
270             login_base = get_leaf(record['authority'])
271             api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
272
273         # What roles should this user have?
274         api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
275         # Add the user's key
276         if pub_key:
277             api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
278
279     elif (type == "node"):
280         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
281         login_base = hrn_to_pl_login_base(record['authority'])
282         nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
283         if not nodes:
284             pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
285         else:
286             pointer = nodes[0]['node_id']
287
288     record['pointer'] = pointer
289     record.set_pointer(pointer)
290     record_id = table.insert(record)
291     record['record_id'] = record_id
292
293     # update membership for researchers, pis, owners, operators
294     api.update_membership(None, record)
295
296     return record.get_gid_object().save_to_string(save_parents=True)
297
298 def update(api, record_dict):
299     new_record = SfaRecord(dict = record_dict)
300     type = new_record['type']
301     hrn = new_record['hrn']
302     urn = hrn_to_urn(hrn,type)
303     table = SfaTable()
304     # make sure the record exists
305     records = table.findObjects({'type': type, 'hrn': hrn})
306     if not records:
307         raise RecordNotFound(hrn)
308     record = records[0]
309     record['last_updated'] = time.gmtime()
310
311     # Update_membership needs the membership lists in the existing record
312     # filled in, so it can see if members were added or removed
313     api.fill_record_info(record)
314
315     # Use the pointer from the existing record, not the one that the user
316     # gave us. This prevents the user from inserting a forged pointer
317     pointer = record['pointer']
318     # update the PLC information that was specified with the record
319
320     if (type == "authority"):
321         api.plshell.UpdateSite(api.plauth, pointer, new_record)
322
323     elif type == "slice":
324         pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
325         if 'name' in pl_record:
326             pl_record.pop('name')
327             api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
328
329     elif type == "user":
330         # SMBAKER: UpdatePerson only allows a limited set of fields to be
331         #    updated. Ideally we should have a more generic way of doing
332         #    this. I copied the field names from UpdatePerson.py...
333         update_fields = {}
334         all_fields = new_record
335         for key in all_fields.keys():
336             if key in ['first_name', 'last_name', 'title', 'email',
337                        'password', 'phone', 'url', 'bio', 'accepted_aup',
338                        'enabled']:
339                 update_fields[key] = all_fields[key]
340         api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
341
342         if 'key' in new_record and new_record['key']:
343             # must check this key against the previous one if it exists
344             persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
345             person = persons[0]
346             keys = person['key_ids']
347             keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
348             key_exists = False
349             if isinstance(new_record['key'], types.ListType):
350                 new_key = new_record['key'][0]
351             else:
352                 new_key = new_record['key']
353             
354             # Delete all stale keys
355             for key in keys:
356                 if new_record['key'] != key['key']:
357                     api.plshell.DeleteKey(api.plauth, key['key_id'])
358                 else:
359                     key_exists = True
360             if not key_exists:
361                 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
362
363             # update the openssl key and gid
364             pkey = convert_public_key(new_key)
365             uuid = create_uuid()
366             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
367             gid = gid_object.save_to_string(save_parents=True)
368             record['gid'] = gid
369             record = SfaRecord(dict=record)
370             table.update(record)
371
372     elif type == "node":
373         api.plshell.UpdateNode(api.plauth, pointer, new_record)
374
375     else:
376         raise UnknownSfaType(type)
377
378     # update membership for researchers, pis, owners, operators
379     api.update_membership(record, new_record)
380     
381     return 1 
382
383 # expecting an Xrn instance
384 def remove(api, xrn, origin_hrn=None):
385
386     table = SfaTable()
387     filter = {'hrn': xrn.get_hrn()}
388     hrn=xrn.get_hrn()
389     type=xrn.get_type()
390     if type and type not in ['all', '*']:
391         filter['type'] = type
392
393     records = table.find(filter)
394     if not records: raise RecordNotFound(hrn)
395     record = records[0]
396     type = record['type']
397
398     credential = api.getCredential()
399     registries = api.registries
400
401     # Try to remove the object from the PLCDB of federated agg.
402     # This is attempted before removing the object from the local agg's PLCDB and sfa table
403     if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
404         for registry in registries:
405             if registry not in [api.hrn]:
406                 try:
407                     result=registries[registry].remove_peer_object(credential, record, origin_hrn)
408                 except:
409                     pass
410     if type == "user":
411         persons = api.plshell.GetPersons(api.plauth, record['pointer'])
412         # only delete this person if he has site ids. if he doesnt, it probably means
413         # he was just removed from a site, not actually deleted
414         if persons and persons[0]['site_ids']:
415             api.plshell.DeletePerson(api.plauth, record['pointer'])
416     elif type == "slice":
417         if api.plshell.GetSlices(api.plauth, record['pointer']):
418             api.plshell.DeleteSlice(api.plauth, record['pointer'])
419     elif type == "node":
420         if api.plshell.GetNodes(api.plauth, record['pointer']):
421             api.plshell.DeleteNode(api.plauth, record['pointer'])
422     elif type == "authority":
423         if api.plshell.GetSites(api.plauth, record['pointer']):
424             api.plshell.DeleteSite(api.plauth, record['pointer'])
425     else:
426         raise UnknownSfaType(type)
427
428     table.remove(record)
429
430     return 1
431
432 def remove_peer_object(api, record, origin_hrn=None):
433     pass
434
435 def register_peer_object(api, record, origin_hrn=None):
436     pass