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, hrn, type, is_self=False):
15 # Is this a root or sub authority
16 auth_hrn = api.auth.get_authority(hrn)
17 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
20 auth_info = api.auth.get_auth_info(auth_hrn)
22 records = table.findObjects({'type': type, 'hrn': hrn})
24 raise RecordNotFound(hrn)
27 # verify_cancreate_credential requires that the member lists
28 # (researchers, pis, etc) be filled in
29 api.fill_record_info(record)
32 # if this is a self cred the record's gid is the caller's gid
35 caller_gid = record.get_gid_object()
37 caller_gid = api.auth.client_cred.get_gid_caller()
38 caller_hrn = caller_gid.get_hrn()
40 object_hrn = record.get_gid_object().get_hrn()
41 rights = api.auth.determine_user_rights(caller_hrn, record)
42 # make sure caller has rights to this object
44 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
46 object_gid = GID(string=record['gid'])
47 new_cred = Credential(subject = object_gid.get_subject())
48 new_cred.set_gid_caller(caller_gid)
49 new_cred.set_gid_object(object_gid)
50 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
51 new_cred.set_pubkey(object_gid.get_pubkey())
52 new_cred.set_privileges(rights)
53 new_cred.set_delegate(True)
54 auth_kind = "authority,ma,sa"
55 new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
59 return new_cred.save_to_string(save_parents=True)
61 def resolve(api, hrns, type=None, origin_hrn=None):
63 # load all know registry names into a prefix tree and attempt to find
64 # the longest matching prefix
65 if not isinstance(hrns, types.ListType):
68 # create a dict whre key is an registry hrn and its value is a
69 # hrns at that registry (determined by the known prefix tree).
71 registries = Registries(api)
73 registry_hrns = registries.keys()
74 tree.load(registry_hrns)
76 registry_hrn = tree.best_match(hrn)
77 if registry_hrn not in hrn_dict:
78 hrn_dict[registry_hrn] = []
79 hrn_dict[registry_hrn].append(hrn)
82 for registry_hrn in hrn_dict:
83 # skip the hrn without a registry hrn
84 # XX should we let the user know the authority is unknown?
88 # if the best match (longest matching hrn) is not the local registry,
90 hrns = hrn_dict[registry_hrn]
91 if registry_hrn != api.hrn:
92 credential = api.getCredential()
93 peer_records = registries[registry_hrn].resolve(credential, hrn, origin_hrn)
94 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
96 # try resolving the remaining unfound records at the local registry
97 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
98 remaining_hrns = [hrn for hrn in remaining_hrns]
100 local_records = table.findObjects({'hrn': remaining_hrns})
101 for record in local_records:
103 api.fill_record_info(record)
104 records.append(dict(record))
105 except PlanetLabRecordDoesNotExist:
106 # silently drop the ones that are missing in PL
107 print >> log, "ignoring SFA record ", record['hrn'], \
108 " because pl record does not exist"
112 raise RecordNotFound(str(hrns))
115 records = filter(lambda rec: rec['type'] in [type], records)
120 # load all know registry names into a prefix tree and attempt to find
121 # the longest matching prefix
123 registries = Registries(api)
124 hrns = registries.keys()
127 registry_hrn = tree.best_match(hrn)
129 #if there was no match then this record belongs to an unknow registry
131 raise MissingAuthority(hrn)
133 # if the best match (longest matching hrn) is not the local registry,
134 # forward the request
136 if registry_hrn != api.hrn:
137 credential = api.getCredential()
138 record_list = registries[registry_hrn].list(credential, hrn, origin_hrn)
139 records = [SfaRecord(dict=record).as_dict() for record in record_list]
141 # if we still havnt found the record yet, try the local registry
143 if not api.auth.hierarchy.auth_exists(hrn):
144 raise MissingAuthority(hrn)
147 records = table.find({'authority': hrn})
152 def register(api, record):
154 hrn, type = record['hrn'], record['type']
157 if type not in ['authority', 'slice', 'node', 'user']:
158 raise UnknownSfaType(type)
160 # check if record already exists
162 existing_records = table.find({'type': type, 'hrn': hrn})
164 raise ExistingRecord(hrn)
166 record = SfaRecord(dict = record)
167 record['authority'] = get_authority(record['hrn'])
168 type = record['type']
170 api.auth.verify_object_permission(hrn)
171 auth_info = api.auth.get_auth_info(record['authority'])
173 # make sure record has a gid
174 if 'gid' not in record:
176 pkey = Keypair(create=True)
177 if 'key' in record and record['key']:
178 if isinstance(record['key'], types.ListType):
179 pub_key = record['key'][0]
181 pub_key = record['key']
182 pkey = convert_public_key(pub_key)
184 gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
185 gid = gid_object.save_to_string(save_parents=True)
189 if type in ["authority"]:
191 if not api.auth.hierarchy.auth_exists(hrn):
192 api.auth.hierarchy.create_auth(hrn)
194 # get the GID from the newly created authority
195 gid = auth_info.get_gid_object()
196 record.set_gid(gid.save_to_string(save_parents=True))
197 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
198 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
200 pointer = api.plshell.AddSite(api.plauth, pl_record)
202 pointer = sites[0]['site_id']
204 record.set_pointer(pointer)
205 record['pointer'] = pointer
207 elif (type == "slice"):
208 acceptable_fields=['url', 'instantiation', 'name', 'description']
209 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
210 for key in pl_record.keys():
211 if key not in acceptable_fields:
213 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
215 pointer = api.plshell.AddSlice(api.plauth, pl_record)
217 pointer = slices[0]['slice_id']
218 record.set_pointer(pointer)
219 record['pointer'] = pointer
221 elif (type == "user"):
222 persons = api.plshell.GetPersons(api.plauth, [record['email']])
224 pointer = api.plshell.AddPerson(api.plauth, dict(record))
226 pointer = persons[0]['person_id']
228 if 'enabled' in record and record['enabled']:
229 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
230 # add this persons to the site only if he is being added for the first
231 # time by sfa and doesont already exist in plc
232 if not persons or not persons[0]['site_ids']:
233 login_base = get_leaf(record['authority'])
234 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
236 # What roles should this user have?
237 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
240 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
242 elif (type == "node"):
243 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
244 login_base = hrn_to_pl_login_base(record['authority'])
245 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
247 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
249 pointer = nodes[0]['node_id']
251 record['pointer'] = pointer
252 record.set_pointer(pointer)
253 record_id = table.insert(record)
254 record['record_id'] = record_id
256 # update membership for researchers, pis, owners, operators
257 api.update_membership(None, record)
259 return record.get_gid_object().save_to_string(save_parents=True)
261 def update(api, record_dict):
262 new_record = SfaRecord(dict = record_dict)
263 type = new_record['type']
264 hrn = new_record['hrn']
265 api.auth.verify_object_permission(hrn)
267 # make sure the record exists
268 records = table.findObjects({'type': type, 'hrn': hrn})
270 raise RecordNotFound(hrn)
272 record['last_updated'] = time.gmtime()
274 # Update_membership needs the membership lists in the existing record
275 # filled in, so it can see if members were added or removed
276 api.fill_record_info(record)
278 # Use the pointer from the existing record, not the one that the user
279 # gave us. This prevents the user from inserting a forged pointer
280 pointer = record['pointer']
281 # update the PLC information that was specified with the record
283 if (type == "authority"):
284 api.plshell.UpdateSite(api.plauth, pointer, new_record)
286 elif type == "slice":
287 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
288 if 'name' in pl_record:
289 pl_record.pop('name')
290 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
293 # SMBAKER: UpdatePerson only allows a limited set of fields to be
294 # updated. Ideally we should have a more generic way of doing
295 # this. I copied the field names from UpdatePerson.py...
297 all_fields = new_record
298 for key in all_fields.keys():
299 if key in ['first_name', 'last_name', 'title', 'email',
300 'password', 'phone', 'url', 'bio', 'accepted_aup',
302 update_fields[key] = all_fields[key]
303 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
305 if 'key' in new_record and new_record['key']:
306 # must check this key against the previous one if it exists
307 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
309 keys = person['key_ids']
310 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
312 if isinstance(new_record['key'], types.ListType):
313 new_key = new_record['key'][0]
315 new_key = new_record['key']
317 # Delete all stale keys
319 if new_record['key'] != key['key']:
320 api.plshell.DeleteKey(api.plauth, key['key_id'])
324 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
326 # update the openssl key and gid
327 pkey = convert_public_key(new_key)
329 gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
330 gid = gid_object.save_to_string(save_parents=True)
332 record = SfaRecord(dict=record)
336 api.plshell.UpdateNode(api.plauth, pointer, new_record)
339 raise UnknownSfaType(type)
341 # update membership for researchers, pis, owners, operators
342 api.update_membership(record, new_record)
346 def remove(api, hrn, type, origin_hrn=None):
348 filter = {'hrn': hrn}
349 if type not in ['all', '*']:
350 filter['type'] = type
351 records = table.find(filter)
353 raise RecordNotFound(hrn)
355 type = record['type']
357 credential = api.getCredential()
358 registries = Registries(api)
360 # Try to remove the object from the PLCDB of federated agg.
361 # This is attempted before removing the object from the local agg's PLCDB and sfa table
362 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
363 for registry in registries:
364 if registry not in [api.hrn]:
366 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
370 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
371 # only delete this person if he has site ids. if he doesnt, it probably means
372 # he was just removed from a site, not actually deleted
373 if persons and persons[0]['site_ids']:
374 api.plshell.DeletePerson(api.plauth, record['pointer'])
375 elif type == "slice":
376 if api.plshell.GetSlices(api.plauth, record['pointer']):
377 api.plshell.DeleteSlice(api.plauth, record['pointer'])
379 if api.plshell.GetNodes(api.plauth, record['pointer']):
380 api.plshell.DeleteNode(api.plauth, record['pointer'])
381 elif type == "authority":
382 if api.plshell.GetSites(api.plauth, record['pointer']):
383 api.plshell.DeleteSite(api.plauth, record['pointer'])
385 raise UnknownSfaType(type)
391 def remove_peer_object(api, record, origin_hrn=None):
394 def register_peer_object(api, record, origin_hrn=None):