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