3 from sfa.server.registry import Registries
4 from sfa.util.prefixTree import prefixTree
5 from sfa.util.record import SfaRecord
6 from sfa.util.table import SfaTable
7 from sfa.util.record import SfaRecord
8 from sfa.trust.gid import GID
9 from sfa.util.namespace import *
10 from sfa.trust.credential import *
11 from sfa.trust.certificate import *
12 from sfa.util.faults import *
14 def get_credential(api, xrn, type, is_self=False):
17 hrn = urn_to_hrn(xrn)[0]
19 hrn, type = urn_to_hrn(xrn)
20 # Is this a root or sub authority
21 auth_hrn = api.auth.get_authority(hrn)
22 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
25 auth_info = api.auth.get_auth_info(auth_hrn)
27 records = table.findObjects({'type': type, 'hrn': hrn})
29 raise RecordNotFound(hrn)
32 # verify_cancreate_credential requires that the member lists
33 # (researchers, pis, etc) be filled in
34 api.fill_record_info(record)
35 if record['type']=='user':
36 if not record['enabled']:
37 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
40 # if this is a self cred the record's gid is the caller's gid
43 caller_gid = record.get_gid_object()
45 caller_gid = api.auth.client_cred.get_gid_caller()
46 caller_hrn = caller_gid.get_hrn()
48 object_hrn = record.get_gid_object().get_hrn()
49 rights = api.auth.determine_user_rights(caller_hrn, record)
50 # make sure caller has rights to this object
52 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
54 object_gid = GID(string=record['gid'])
55 new_cred = Credential(subject = object_gid.get_subject())
56 new_cred.set_gid_caller(caller_gid)
57 new_cred.set_gid_object(object_gid)
58 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
59 new_cred.set_pubkey(object_gid.get_pubkey())
60 new_cred.set_privileges(rights)
61 new_cred.set_delegate(True)
62 auth_kind = "authority,ma,sa"
63 new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
67 return new_cred.save_to_string(save_parents=True)
69 def resolve(api, xrns, type=None, origin_hrn=None):
71 # load all know registry names into a prefix tree and attempt to find
72 # the longest matching prefix
73 if not isinstance(xrns, types.ListType):
75 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
76 # create a dict whre key is an registry hrn and its value is a
77 # hrns at that registry (determined by the known prefix tree).
79 registries = Registries(api)
81 registry_hrns = registries.keys()
82 tree.load(registry_hrns)
84 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
85 if registry_hrn not in xrn_dict:
86 xrn_dict[registry_hrn] = []
87 xrn_dict[registry_hrn].append(xrn)
90 for registry_hrn in xrn_dict:
91 # skip the hrn without a registry hrn
92 # XX should we let the user know the authority is unknown?
96 # if the best match (longest matching hrn) is not the local registry,
98 xrns = xrn_dict[registry_hrn]
99 if registry_hrn != api.hrn:
100 credential = api.getCredential()
101 peer_records = registries[registry_hrn].resolve(credential, xrns, origin_hrn)
102 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
104 # try resolving the remaining unfound records at the local registry
105 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
106 # convert set to list
107 remaining_hrns = [hrn for hrn in remaining_hrns]
109 local_records = table.findObjects({'hrn': remaining_hrns})
110 for record in local_records:
112 api.fill_record_info(record)
113 records.append(dict(record))
114 except PlanetLabRecordDoesNotExist:
115 # silently drop the ones that are missing in PL
116 print >> log, "ignoring SFA record ", record['hrn'], \
117 " because pl record does not exist"
121 raise RecordNotFound(str(hrns))
124 records = filter(lambda rec: rec['type'] in [type], records)
128 def list(api, xrn, origin_hrn=None):
129 hrn, type = urn_to_hrn(xrn)
130 # load all know registry names into a prefix tree and attempt to find
131 # the longest matching prefix
133 registries = Registries(api)
134 registry_hrns = registries.keys()
136 tree.load(registry_hrns)
137 registry_hrn = tree.best_match(hrn)
139 #if there was no match then this record belongs to an unknow registry
141 raise MissingAuthority(xrn)
143 # if the best match (longest matching hrn) is not the local registry,
144 # forward the request
146 if registry_hrn != api.hrn:
147 credential = api.getCredential()
148 record_list = registries[registry_hrn].list(credential, xrn, origin_hrn)
149 records = [SfaRecord(dict=record).as_dict() for record in record_list]
151 # if we still havnt found the record yet, try the local registry
153 if not api.auth.hierarchy.auth_exists(hrn):
154 raise MissingAuthority(hrn)
157 records = table.find({'authority': hrn})
162 def register(api, record):
164 hrn, type = record['hrn'], record['type']
167 if type not in ['authority', 'slice', 'node', 'user']:
168 raise UnknownSfaType(type)
170 # check if record already exists
172 existing_records = table.find({'type': type, 'hrn': hrn})
174 raise ExistingRecord(hrn)
176 record = SfaRecord(dict = record)
177 record['authority'] = get_authority(record['hrn'])
178 type = record['type']
180 api.auth.verify_object_permission(hrn)
181 auth_info = api.auth.get_auth_info(record['authority'])
183 # make sure record has a gid
184 if 'gid' not in record:
186 pkey = Keypair(create=True)
187 if 'key' in record and record['key']:
188 if isinstance(record['key'], types.ListType):
189 pub_key = record['key'][0]
191 pub_key = record['key']
192 pkey = convert_public_key(pub_key)
194 gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
195 gid = gid_object.save_to_string(save_parents=True)
199 if type in ["authority"]:
201 if not api.auth.hierarchy.auth_exists(hrn):
202 api.auth.hierarchy.create_auth(hrn)
204 # get the GID from the newly created authority
205 gid = auth_info.get_gid_object()
206 record.set_gid(gid.save_to_string(save_parents=True))
207 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
208 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
210 pointer = api.plshell.AddSite(api.plauth, pl_record)
212 pointer = sites[0]['site_id']
214 record.set_pointer(pointer)
215 record['pointer'] = pointer
217 elif (type == "slice"):
218 acceptable_fields=['url', 'instantiation', 'name', 'description']
219 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
220 for key in pl_record.keys():
221 if key not in acceptable_fields:
223 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
225 pointer = api.plshell.AddSlice(api.plauth, pl_record)
227 pointer = slices[0]['slice_id']
228 record.set_pointer(pointer)
229 record['pointer'] = pointer
231 elif (type == "user"):
232 persons = api.plshell.GetPersons(api.plauth, [record['email']])
234 pointer = api.plshell.AddPerson(api.plauth, dict(record))
236 pointer = persons[0]['person_id']
238 if 'enabled' in record and record['enabled']:
239 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
240 # add this persons to the site only if he is being added for the first
241 # time by sfa and doesont already exist in plc
242 if not persons or not persons[0]['site_ids']:
243 login_base = get_leaf(record['authority'])
244 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
246 # What roles should this user have?
247 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
250 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
252 elif (type == "node"):
253 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
254 login_base = hrn_to_pl_login_base(record['authority'])
255 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
257 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
259 pointer = nodes[0]['node_id']
261 record['pointer'] = pointer
262 record.set_pointer(pointer)
263 record_id = table.insert(record)
264 record['record_id'] = record_id
266 # update membership for researchers, pis, owners, operators
267 api.update_membership(None, record)
269 return record.get_gid_object().save_to_string(save_parents=True)
271 def update(api, record_dict):
272 new_record = SfaRecord(dict = record_dict)
273 type = new_record['type']
274 hrn = new_record['hrn']
275 api.auth.verify_object_permission(hrn)
277 # make sure the record exists
278 records = table.findObjects({'type': type, 'hrn': hrn})
280 raise RecordNotFound(hrn)
282 record['last_updated'] = time.gmtime()
284 # Update_membership needs the membership lists in the existing record
285 # filled in, so it can see if members were added or removed
286 api.fill_record_info(record)
288 # Use the pointer from the existing record, not the one that the user
289 # gave us. This prevents the user from inserting a forged pointer
290 pointer = record['pointer']
291 # update the PLC information that was specified with the record
293 if (type == "authority"):
294 api.plshell.UpdateSite(api.plauth, pointer, new_record)
296 elif type == "slice":
297 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
298 if 'name' in pl_record:
299 pl_record.pop('name')
300 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
303 # SMBAKER: UpdatePerson only allows a limited set of fields to be
304 # updated. Ideally we should have a more generic way of doing
305 # this. I copied the field names from UpdatePerson.py...
307 all_fields = new_record
308 for key in all_fields.keys():
309 if key in ['first_name', 'last_name', 'title', 'email',
310 'password', 'phone', 'url', 'bio', 'accepted_aup',
312 update_fields[key] = all_fields[key]
313 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
315 if 'key' in new_record and new_record['key']:
316 # must check this key against the previous one if it exists
317 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
319 keys = person['key_ids']
320 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
322 if isinstance(new_record['key'], types.ListType):
323 new_key = new_record['key'][0]
325 new_key = new_record['key']
327 # Delete all stale keys
329 if new_record['key'] != key['key']:
330 api.plshell.DeleteKey(api.plauth, key['key_id'])
334 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
336 # update the openssl key and gid
337 pkey = convert_public_key(new_key)
339 gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
340 gid = gid_object.save_to_string(save_parents=True)
342 record = SfaRecord(dict=record)
346 api.plshell.UpdateNode(api.plauth, pointer, new_record)
349 raise UnknownSfaType(type)
351 # update membership for researchers, pis, owners, operators
352 api.update_membership(record, new_record)
356 def remove(api, xrn, type, origin_hrn=None):
359 hrn = urn_to_hrn(xrn)[0]
361 hrn, type = urn_to_hrn(xrn)
364 filter = {'hrn': hrn}
365 if type not in ['all', '*']:
366 filter['type'] = type
367 records = table.find(filter)
369 raise RecordNotFound(hrn)
371 type = record['type']
373 credential = api.getCredential()
374 registries = Registries(api)
376 # Try to remove the object from the PLCDB of federated agg.
377 # This is attempted before removing the object from the local agg's PLCDB and sfa table
378 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
379 for registry in registries:
380 if registry not in [api.hrn]:
382 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
386 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
387 # only delete this person if he has site ids. if he doesnt, it probably means
388 # he was just removed from a site, not actually deleted
389 if persons and persons[0]['site_ids']:
390 api.plshell.DeletePerson(api.plauth, record['pointer'])
391 elif type == "slice":
392 if api.plshell.GetSlices(api.plauth, record['pointer']):
393 api.plshell.DeleteSlice(api.plauth, record['pointer'])
395 if api.plshell.GetNodes(api.plauth, record['pointer']):
396 api.plshell.DeleteNode(api.plauth, record['pointer'])
397 elif type == "authority":
398 if api.plshell.GetSites(api.plauth, record['pointer']):
399 api.plshell.DeleteSite(api.plauth, record['pointer'])
401 raise UnknownSfaType(type)
407 def remove_peer_object(api, record, origin_hrn=None):
410 def register_peer_object(api, record, origin_hrn=None):