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 *
13 def get_credential(api, xrn, type, is_self=False):
16 hrn = urn_to_hrn(xrn)[0]
18 hrn, type = urn_to_hrn(xrn)
19 # Is this a root or sub authority
20 auth_hrn = api.auth.get_authority(hrn)
21 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
24 auth_info = api.auth.get_auth_info(auth_hrn)
26 records = table.findObjects({'type': type, 'hrn': hrn})
28 raise RecordNotFound(hrn)
31 # verify_cancreate_credential requires that the member lists
32 # (researchers, pis, etc) be filled in
33 api.fill_record_info(record)
34 if record['type']=='user':
35 if not record['enabled']:
36 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
39 # if this is a self cred the record's gid is the caller's gid
42 caller_gid = record.get_gid_object()
44 caller_gid = api.auth.client_cred.get_gid_caller()
45 caller_hrn = caller_gid.get_hrn()
47 object_hrn = record.get_gid_object().get_hrn()
48 rights = api.auth.determine_user_rights(caller_hrn, record)
49 # make sure caller has rights to this object
51 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
53 object_gid = GID(string=record['gid'])
54 new_cred = Credential(subject = object_gid.get_subject())
55 new_cred.set_gid_caller(caller_gid)
56 new_cred.set_gid_object(object_gid)
57 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
58 new_cred.set_pubkey(object_gid.get_pubkey())
59 new_cred.set_privileges(rights)
60 new_cred.set_delegate(True)
61 auth_kind = "authority,ma,sa"
62 new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
66 return new_cred.save_to_string(save_parents=True)
68 def resolve(api, xrns, type=None, origin_hrn=None, full=True):
70 # load all know registry names into a prefix tree and attempt to find
71 # the longest matching prefix
72 if not isinstance(xrns, types.ListType):
74 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
75 # create a dict whre key is an registry hrn and its value is a
76 # hrns at that registry (determined by the known prefix tree).
78 registries = api.registries
80 registry_hrns = registries.keys()
81 tree.load(registry_hrns)
83 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
84 if registry_hrn not in xrn_dict:
85 xrn_dict[registry_hrn] = []
86 xrn_dict[registry_hrn].append(xrn)
89 for registry_hrn in xrn_dict:
90 # skip the hrn without a registry hrn
91 # XX should we let the user know the authority is unknown?
95 # if the best match (longest matching hrn) is not the local registry,
97 xrns = xrn_dict[registry_hrn]
98 if registry_hrn != api.hrn:
99 credential = api.getCredential()
100 peer_records = registries[registry_hrn].resolve(credential, xrns, origin_hrn)
101 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
103 # try resolving the remaining unfound records at the local registry
104 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
105 # convert set to list
106 remaining_hrns = [hrn for hrn in remaining_hrns]
108 local_records = table.findObjects({'hrn': remaining_hrns})
110 api.fill_record_info(local_records)
112 # convert local record objects to dicts
113 records.extend([dict(record) for record in local_records])
115 raise RecordNotFound(str(hrns))
118 records = filter(lambda rec: rec['type'] in [type], records)
122 def list(api, xrn, origin_hrn=None):
123 hrn, type = urn_to_hrn(xrn)
124 # load all know registry names into a prefix tree and attempt to find
125 # the longest matching prefix
127 registries = api.registries
128 registry_hrns = registries.keys()
130 tree.load(registry_hrns)
131 registry_hrn = tree.best_match(hrn)
133 #if there was no match then this record belongs to an unknow registry
135 raise MissingAuthority(xrn)
137 # if the best match (longest matching hrn) is not the local registry,
138 # forward the request
140 if registry_hrn != api.hrn:
141 credential = api.getCredential()
142 record_list = registries[registry_hrn].list(credential, xrn, origin_hrn)
143 records = [SfaRecord(dict=record).as_dict() for record in record_list]
145 # if we still havnt found the record yet, try the local registry
147 if not api.auth.hierarchy.auth_exists(hrn):
148 raise MissingAuthority(hrn)
151 records = table.find({'authority': hrn})
156 def register(api, record):
158 hrn, type = record['hrn'], record['type']
161 if type not in ['authority', 'slice', 'node', 'user']:
162 raise UnknownSfaType(type)
164 # check if record already exists
166 existing_records = table.find({'type': type, 'hrn': hrn})
168 raise ExistingRecord(hrn)
170 record = SfaRecord(dict = record)
171 record['authority'] = get_authority(record['hrn'])
172 type = record['type']
174 api.auth.verify_object_permission(hrn)
175 auth_info = api.auth.get_auth_info(record['authority'])
177 # make sure record has a gid
178 if 'gid' not in record:
180 pkey = Keypair(create=True)
181 if 'key' in record and record['key']:
182 if isinstance(record['key'], types.ListType):
183 pub_key = record['key'][0]
185 pub_key = record['key']
186 pkey = convert_public_key(pub_key)
188 gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
189 gid = gid_object.save_to_string(save_parents=True)
193 if type in ["authority"]:
195 if not api.auth.hierarchy.auth_exists(hrn):
196 api.auth.hierarchy.create_auth(hrn)
198 # get the GID from the newly created authority
199 gid = auth_info.get_gid_object()
200 record.set_gid(gid.save_to_string(save_parents=True))
201 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
202 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
204 pointer = api.plshell.AddSite(api.plauth, pl_record)
206 pointer = sites[0]['site_id']
208 record.set_pointer(pointer)
209 record['pointer'] = pointer
211 elif (type == "slice"):
212 acceptable_fields=['url', 'instantiation', 'name', 'description']
213 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
214 for key in pl_record.keys():
215 if key not in acceptable_fields:
217 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
219 pointer = api.plshell.AddSlice(api.plauth, pl_record)
221 pointer = slices[0]['slice_id']
222 record.set_pointer(pointer)
223 record['pointer'] = pointer
225 elif (type == "user"):
226 persons = api.plshell.GetPersons(api.plauth, [record['email']])
228 pointer = api.plshell.AddPerson(api.plauth, dict(record))
230 pointer = persons[0]['person_id']
232 if 'enabled' in record and record['enabled']:
233 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
234 # add this persons to the site only if he is being added for the first
235 # time by sfa and doesont already exist in plc
236 if not persons or not persons[0]['site_ids']:
237 login_base = get_leaf(record['authority'])
238 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
240 # What roles should this user have?
241 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
244 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
246 elif (type == "node"):
247 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
248 login_base = hrn_to_pl_login_base(record['authority'])
249 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
251 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
253 pointer = nodes[0]['node_id']
255 record['pointer'] = pointer
256 record.set_pointer(pointer)
257 record_id = table.insert(record)
258 record['record_id'] = record_id
260 # update membership for researchers, pis, owners, operators
261 api.update_membership(None, record)
263 return record.get_gid_object().save_to_string(save_parents=True)
265 def update(api, record_dict):
266 new_record = SfaRecord(dict = record_dict)
267 type = new_record['type']
268 hrn = new_record['hrn']
269 api.auth.verify_object_permission(hrn)
271 # make sure the record exists
272 records = table.findObjects({'type': type, 'hrn': hrn})
274 raise RecordNotFound(hrn)
276 record['last_updated'] = time.gmtime()
278 # Update_membership needs the membership lists in the existing record
279 # filled in, so it can see if members were added or removed
280 api.fill_record_info(record)
282 # Use the pointer from the existing record, not the one that the user
283 # gave us. This prevents the user from inserting a forged pointer
284 pointer = record['pointer']
285 # update the PLC information that was specified with the record
287 if (type == "authority"):
288 api.plshell.UpdateSite(api.plauth, pointer, new_record)
290 elif type == "slice":
291 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
292 if 'name' in pl_record:
293 pl_record.pop('name')
294 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
297 # SMBAKER: UpdatePerson only allows a limited set of fields to be
298 # updated. Ideally we should have a more generic way of doing
299 # this. I copied the field names from UpdatePerson.py...
301 all_fields = new_record
302 for key in all_fields.keys():
303 if key in ['first_name', 'last_name', 'title', 'email',
304 'password', 'phone', 'url', 'bio', 'accepted_aup',
306 update_fields[key] = all_fields[key]
307 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
309 if 'key' in new_record and new_record['key']:
310 # must check this key against the previous one if it exists
311 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
313 keys = person['key_ids']
314 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
316 if isinstance(new_record['key'], types.ListType):
317 new_key = new_record['key'][0]
319 new_key = new_record['key']
321 # Delete all stale keys
323 if new_record['key'] != key['key']:
324 api.plshell.DeleteKey(api.plauth, key['key_id'])
328 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
330 # update the openssl key and gid
331 pkey = convert_public_key(new_key)
333 gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
334 gid = gid_object.save_to_string(save_parents=True)
336 record = SfaRecord(dict=record)
340 api.plshell.UpdateNode(api.plauth, pointer, new_record)
343 raise UnknownSfaType(type)
345 # update membership for researchers, pis, owners, operators
346 api.update_membership(record, new_record)
350 def remove(api, xrn, type, origin_hrn=None):
353 hrn = urn_to_hrn(xrn)[0]
355 hrn, type = urn_to_hrn(xrn)
358 filter = {'hrn': hrn}
359 if type not in ['all', '*']:
360 filter['type'] = type
361 records = table.find(filter)
363 raise RecordNotFound(hrn)
365 type = record['type']
367 credential = api.getCredential()
368 registries = api.registries
370 # Try to remove the object from the PLCDB of federated agg.
371 # This is attempted before removing the object from the local agg's PLCDB and sfa table
372 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
373 for registry in registries:
374 if registry not in [api.hrn]:
376 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
380 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
381 # only delete this person if he has site ids. if he doesnt, it probably means
382 # he was just removed from a site, not actually deleted
383 if persons and persons[0]['site_ids']:
384 api.plshell.DeletePerson(api.plauth, record['pointer'])
385 elif type == "slice":
386 if api.plshell.GetSlices(api.plauth, record['pointer']):
387 api.plshell.DeleteSlice(api.plauth, record['pointer'])
389 if api.plshell.GetNodes(api.plauth, record['pointer']):
390 api.plshell.DeleteNode(api.plauth, record['pointer'])
391 elif type == "authority":
392 if api.plshell.GetSites(api.plauth, record['pointer']):
393 api.plshell.DeleteSite(api.plauth, record['pointer'])
395 raise UnknownSfaType(type)
401 def remove_peer_object(api, record, origin_hrn=None):
404 def register_peer_object(api, record, origin_hrn=None):