本文整理汇总了Python中sfa.trust.credential.Credential类的典型用法代码示例。如果您正苦于以下问题:Python Credential类的具体用法?Python Credential怎么用?Python Credential使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Credential类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: call
def call(self, cred, record_dict, origin_hrn=None):
user_cred = Credential(string=cred)
#log the call
if not origin_hrn:
origin_hrn = user_cred.get_gid_caller().get_hrn()
self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, None, self.name))
# validate the cred
self.api.auth.check(cred, "register")
# make sure this is a peer record
if 'peer_authority' not in record_dict or \
not record_dict['peer_authority']:
raise SfaInvalidArgument, "peer_authority must be specified"
record = SfaRecord(dict = record_dict)
type, hrn, peer_authority = record['type'], record['hrn'], record['peer_authority']
record['authority'] = get_authority(record['hrn'])
# verify permissions
self.api.auth.verify_cred_is_me(cred)
# check if record already exists
table = SfaTable()
existing_records = table.find({'type': type, 'hrn': hrn, 'peer_authority': peer_authority})
if existing_records:
for existing_record in existing_records:
if existing_record['pointer'] != record['pointer']:
record['record_id'] = existing_record['record_id']
table.update(record)
else:
record_id = table.insert(record)
return 1
开发者ID:planetlab,项目名称:sfa,代码行数:34,代码来源:RegisterPeerObject.py
示例2: validate_credential
def validate_credential(self, filename):
valid = True
cred = Credential(filename=filename)
# check if credential is expires
if cred.get_expiration() < datetime.utcnow():
valid = False
return valid
开发者ID:nfvproject,项目名称:SFA,代码行数:7,代码来源:sfaclientlib.py
示例3: get_cred
def get_cred(self, file, type, hrn):
# attempt to load a cached credential
cred = self.get_cached_credential(file)
if not cred:
if type in ['user']:
cert_string = self.cert.save_to_string(save_parents=True)
user_name = self.user.replace(self.authority + ".", '')
if user_name.count(".") > 0:
user_name = user_name.replace(".", '_')
self.user = self.authority + "." + user_name
cred_str = self.registry.GetSelfCredential(cert_string, hrn, "user")
else:
# bootstrap slice credential from user credential
user_cred = self.get_user_cred().save_to_string(save_parents=True)
cred_str = self.registry.GetCredential(user_cred, hrn, type)
if not cred_str:
self.logger.critical("Failed to get %s credential" % type)
sys.exit(-1)
cred = Credential(string=cred_str)
cred.save_to_file(file, save_parents=True)
self.logger.info("Writing %s credential to %s" %(type, file))
return cred
开发者ID:planetlab,项目名称:sfa,代码行数:25,代码来源:sfi.py
示例4: getCredential
def getCredential(self):
"""
Get our credential from a remote registry
"""
path = self.config.SFA_DATA_DIR
config_dir = self.config.config_path
cred_filename = path + os.sep + 'node.cred'
try:
credential = Credential(filename = cred_filename)
return credential.save_to_string(save_parents=True)
except IOError:
node_pkey_file = config_dir + os.sep + "node.key"
node_gid_file = config_dir + os.sep + "node.gid"
cert_filename = path + os.sep + 'server.cert'
if not os.path.exists(node_pkey_file) or \
not os.path.exists(node_gid_file):
self.get_node_key()
# get node's hrn
gid = GID(filename=node_gid_file)
hrn = gid.get_hrn()
# get credential from registry
cert_str = Certificate(filename=cert_filename).save_to_string(save_parents=True)
registry = self.get_registry()
cred = registry.GetSelfCredential(cert_str, hrn, 'node')
Credential(string=cred).save_to_file(credfile, save_parents=True)
return cred
开发者ID:planetlab,项目名称:sfa,代码行数:28,代码来源:api.py
示例5: delegate_credential_string
def delegate_credential_string (self, original_credential, to_hrn, to_type='authority'):
"""
sign a delegation credential to someone else
original_credential : typically one's user- or slice- credential to be delegated to s/b else
to_hrn : the hrn of the person that will be allowed to do stuff on our behalf
to_type : goes with to_hrn, usually 'user' or 'authority'
returns a string with the delegated credential
this internally uses self.my_gid()
it also retrieves the gid for to_hrn/to_type
and uses Credential.delegate()"""
# the gid and hrn of the object we are delegating
if isinstance (original_credential, str):
original_credential = Credential (string=original_credential)
original_gid = original_credential.get_gid_object()
original_hrn = original_gid.get_hrn()
if not original_credential.get_privileges().get_all_delegate():
self.logger.error("delegate_credential_string: original credential %s does not have delegate bit set"%original_hrn)
return
# the delegating user's gid
my_gid = self.my_gid()
# retrieve the GID for the entity that we're delegating to
to_gidfile = self.gid (to_hrn,to_type)
# to_gid = GID ( to_gidfile )
# to_hrn = delegee_gid.get_hrn()
# print 'to_hrn',to_hrn
delegated_credential = original_credential.delegate(to_gidfile, self.private_key(), my_gid)
return delegated_credential.save_to_string(save_parents=True)
开发者ID:nfvproject,项目名称:SFA,代码行数:34,代码来源:sfaclientlib.py
示例6: __get_registry_objects
def __get_registry_objects(slice_xrn, creds, users):
"""
"""
hrn, type = urn_to_hrn(slice_xrn)
hrn_auth = get_authority(hrn)
# Build up objects that an SFA registry would return if SFA
# could contact the slice's registry directly
reg_objects = None
if users:
# dont allow special characters in the site login base
#only_alphanumeric = re.compile('[^a-zA-Z0-9]+')
#login_base = only_alphanumeric.sub('', hrn_auth[:20]).lower()
slicename = hrn_to_pl_slicename(hrn)
login_base = slicename.split('_')[0]
reg_objects = {}
site = {}
site['site_id'] = 0
site['name'] = 'geni.%s' % login_base
site['enabled'] = True
site['max_slices'] = 100
# Note:
# Is it okay if this login base is the same as one already at this myplc site?
# Do we need uniqueness? Should use hrn_auth instead of just the leaf perhaps?
site['login_base'] = login_base
site['abbreviated_name'] = login_base
site['max_slivers'] = 1000
reg_objects['site'] = site
slice = {}
# get_expiration always returns a normalized datetime - no need to utcparse
extime = Credential(string=creds[0]).get_expiration()
# If the expiration time is > 60 days from now, set the expiration time to 60 days from now
if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
extime = datetime.datetime.utcnow() + datetime.timedelta(days=60)
slice['expires'] = int(time.mktime(extime.timetuple()))
slice['hrn'] = hrn
slice['name'] = hrn_to_pl_slicename(hrn)
slice['url'] = hrn
slice['description'] = hrn
slice['pointer'] = 0
reg_objects['slice_record'] = slice
reg_objects['users'] = {}
for user in users:
user['key_ids'] = []
hrn, _ = urn_to_hrn(user['urn'])
user['email'] = hrn_to_pl_slicename(hrn) + "@geni.net"
user['first_name'] = hrn
user['last_name'] = hrn
reg_objects['users'][user['email']] = user
return reg_objects
开发者ID:planetlab,项目名称:sfa,代码行数:58,代码来源:aggregate_manager_pl.py
示例7: verify_cred_is_me
def verify_cred_is_me(self, credential):
is_me = False
cred = Credential(string=credential)
caller_gid = cred.get_gid_caller()
caller_hrn = caller_gid.get_hrn()
if caller_hrn != self.config.SFA_INTERFACE_HRN:
raise SfaPermissionDenied(self.config.SFA_INTEFACE_HRN)
return
开发者ID:kongseokhwan,项目名称:sfa,代码行数:9,代码来源:auth.py
示例8: log_invalid_cred
def log_invalid_cred(cred):
if not isinstance (cred, StringTypes):
logger.info("cannot validate credential %s - expecting a string"%cred)
error="checkCredentials: expected a string, received %s"%(type(cred))
else:
cred_obj=Credential(string=cred)
logger.info("failed to validate credential - dump=%s"%\
cred_obj.dump_string(dump_parents=True))
error = sys.exc_info()[:2]
return error
开发者ID:kongseokhwan,项目名称:sfa,代码行数:10,代码来源:auth.py
示例9: get_cached_credential
def get_cached_credential(self, file):
"""
Return a cached credential only if it hasn't expired.
"""
if (os.path.isfile(file)):
credential = Credential(filename=file)
# make sure it isnt expired
if not credential.get_expiration or \
datetime.datetime.today() < credential.get_expiration():
return credential
return None
开发者ID:planetlab,项目名称:sfa,代码行数:11,代码来源:sfi.py
示例10: check
def check(self, credential, operation, hrn = None):
"""
Check the credential against the peer cert (callerGID) included
in the credential matches the caller that is connected to the
HTTPS connection, check if the credential was signed by a
trusted cert and check if the credential is allowed to perform
the specified operation.
"""
cred = Credential(cred=credential)
self.client_cred = cred
logger.debug("Auth.check: handling hrn=%s and credential=%s"%\
(hrn,cred.pretty_cred()))
if cred.type not in ['geni_sfa']:
raise CredentialNotVerifiable(cred.type, "%s not supported" % cred.type)
self.client_gid = self.client_cred.get_gid_caller()
self.object_gid = self.client_cred.get_gid_object()
# make sure the client_gid is not blank
if not self.client_gid:
raise MissingCallerGID(self.client_cred.pretty_subject())
# validate the client cert if it exists
if self.peer_cert:
self.verifyPeerCert(self.peer_cert, self.client_gid)
# make sure the client is allowed to perform the operation
if operation:
if not self.client_cred.can_perform(operation):
raise InsufficientRights(operation)
if self.trusted_cert_list:
self.client_cred.verify(self.trusted_cert_file_list,
self.config.SFA_CREDENTIAL_SCHEMA)
else:
raise MissingTrustedRoots(self.config.get_trustedroots_dir())
# Make sure the credential's target matches the specified hrn.
# This check does not apply to trusted peers
trusted_peers = [gid.get_hrn() for gid in self.trusted_cert_list]
if hrn and self.client_gid.get_hrn() not in trusted_peers:
target_hrn = self.object_gid.get_hrn()
if not hrn == target_hrn:
raise PermissionError("Target hrn: %s doesn't match specified hrn: %s " % \
(target_hrn, hrn) )
return True
开发者ID:kongseokhwan,项目名称:sfa,代码行数:46,代码来源:auth.py
示例11: filter_creds_by_caller
def filter_creds_by_caller(self, creds, caller_hrn_list):
"""
Returns a list of creds who's gid caller matches the
specified caller hrn
"""
if not isinstance(creds, list):
creds = [creds]
creds = []
if not isinstance(caller_hrn_list, list):
caller_hrn_list = [caller_hrn_list]
for cred in creds:
try:
tmp_cred = Credential(string=cred)
if tmp_cred.get_gid_caller().get_hrn() in [caller_hrn_list]:
creds.append(cred)
except: pass
return creds
开发者ID:kongseokhwan,项目名称:sfa,代码行数:17,代码来源:auth.py
示例12: server_proxy
def server_proxy(self, interface, cred, timeout=30):
"""
Returns a connection to the specified interface. Use the specified
credential to determine the caller and look for the caller's key/cert
in the registry hierarchy cache.
"""
from sfa.trust.hierarchy import Hierarchy
if not isinstance(cred, Credential):
cred_obj = Credential(string=cred)
else:
cred_obj = cred
caller_gid = cred_obj.get_gid_caller()
hierarchy = Hierarchy()
auth_info = hierarchy.get_auth_info(caller_gid.get_hrn())
key_file = auth_info.get_privkey_filename()
cert_file = auth_info.get_gid_filename()
server = interface.server_proxy(key_file, cert_file, timeout)
return server
开发者ID:gnogueras,项目名称:sfa,代码行数:18,代码来源:sfaapi.py
示例13: checkCredentials
def checkCredentials(self, creds, operation, hrn = None):
valid = []
if not isinstance(creds, list):
creds = [creds]
logger.debug("Auth.checkCredentials with %d creds"%len(creds))
for cred in creds:
try:
self.check(cred, operation, hrn)
valid.append(cred)
except:
cred_obj=Credential(string=cred)
logger.debug("failed to validate credential - dump=%s"%cred_obj.dump_string(dump_parents=True))
error = sys.exc_info()[:2]
continue
if not len(valid):
raise InsufficientRights('Access denied: %s -- %s' % (error[0],error[1]))
return valid
开发者ID:tubav,项目名称:sfa,代码行数:19,代码来源:auth.py
示例14: handle_input_kind
def handle_input_kind (filename, options, kind):
# dump methods current do 'print' so let's go this road for now
if kind=="certificate":
cert=Certificate (filename=filename)
print '--------------------',filename,'IS A',kind
cert.dump(show_extensions=options.show_extensions)
elif kind=="credential":
cred = Credential(filename = filename)
print '--------------------',filename,'IS A',kind
cred.dump(dump_parents = options.dump_parents, show_xml=options.show_xml)
if options.extract_gids:
print '--------------------',filename,'embedded GIDS'
extract_gids(cred, extract_parents = options.dump_parents)
elif kind=="gid":
gid = GID(filename = filename)
print '--------------------',filename,'IS A',kind
gid.dump(dump_parents = options.dump_parents)
else:
print "%s: unknown filekind '%s'"% (filename,kind)
开发者ID:tubav,项目名称:sfa,代码行数:21,代码来源:sfadump.py
示例15: delegate_cred
def delegate_cred(self, object_cred, hrn):
# the gid and hrn of the object we are delegating
if isinstance(object_cred, str):
object_cred = Credential(string=object_cred)
object_gid = object_cred.get_gid_object()
object_hrn = object_gid.get_hrn()
if not object_cred.get_privileges().get_all_delegate():
self.logger.error("Object credential %s does not have delegate bit set"%object_hrn)
return
# the delegating user's gid
caller_gid = self._get_gid(self.user)
caller_gidfile = os.path.join(self.options.sfi_dir, self.user + ".gid")
# the gid of the user who will be delegated to
delegee_gid = self._get_gid(hrn)
delegee_hrn = delegee_gid.get_hrn()
delegee_gidfile = os.path.join(self.options.sfi_dir, delegee_hrn + ".gid")
delegee_gid.save_to_file(filename=delegee_gidfile)
dcred = object_cred.delegate(delegee_gidfile, self.get_key_file(), caller_gidfile)
return dcred.save_to_string(save_parents=True)
开发者ID:planetlab,项目名称:sfa,代码行数:22,代码来源:sfi.py
示例16: call
def call(self, cred, record, origin_hrn=None):
user_cred = Credential(string=cred)
#log the call
if not origin_hrn:
origin_hrn = user_cred.get_gid_caller().get_hrn()
self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, record['hrn'], self.name))
self.api.auth.check(cred, "remove")
# Only allow the local interface or record owner to delete peer_records
try: self.api.auth.verify_object_permission(record['hrn'])
except: self.api.auth.verify_cred_is_me(cred)
table = SfaTable()
hrn, type = record['hrn'], record['type']
records = table.find({'hrn': hrn, 'type': type })
for record in records:
if record['peer_authority']:
self.remove_plc_record(record)
table.remove(record)
return 1
开发者ID:planetlab,项目名称:sfa,代码行数:23,代码来源:remove_peer_object.py
示例17: call
def call(self, xrn, creds, rspec, options):
xrn = Xrn(xrn, type='slice')
# Find the valid credentials
valid_creds = self.api.auth.checkCredentialsSpeaksFor(creds, 'createsliver', xrn.get_hrn(), options=options)
the_credential = Credential(cred=valid_creds[0])
# use the expiration from the first valid credential to determine when
# the slivers should expire.
expiration = datetime_to_string(the_credential.expiration)
self.api.logger.debug("Allocate, received expiration from credential: %s"%expiration)
# turned off, as passing an empty rspec is indeed useful for cleaning up the slice
# # make sure request is not empty
# slivers = RSpec(rspec).version.get_nodes_with_slivers()
# if not slivers:
# raise InvalidRSpec("Missing <sliver_type> or <sliver> element. Request rspec must explicitly allocate slivers")
# flter rspec through sfatables
if self.api.interface in ['aggregate']:
chain_name = 'INCOMING'
elif self.api.interface in ['slicemgr']:
chain_name = 'FORWARD-INCOMING'
self.api.logger.debug("Allocate: sfatables on chain %s"%chain_name)
actual_caller_hrn = the_credential.actual_caller_hrn()
self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, actual_caller_hrn, xrn.get_hrn(), self.name))
rspec = run_sfatables(chain_name, xrn.get_hrn(), actual_caller_hrn, rspec)
# turned off, as passing an empty rspec is indeed useful for cleaning up the slice
# slivers = RSpec(rspec).version.get_nodes_with_slivers()
# if not slivers:
# raise SfatablesRejected(slice_xrn)
# pass this to the driver code in case they need it
options['actual_caller_hrn'] = actual_caller_hrn
result = self.api.manager.Allocate(self.api, xrn.get_urn(), creds, rspec, expiration, options)
return result
开发者ID:kongseokhwan,项目名称:sfa,代码行数:37,代码来源:Allocate.py
示例18: call
def call(self, urns, creds, expiration_time, options):
# Find the valid credentials
valid_creds = self.api.auth.checkCredentialsSpeaksFor(creds, 'renewsliver', urns,
check_sliver_callback = self.api.driver.check_sliver_credentials,
options=options)
the_credential = Credential(cred=valid_creds[0])
actual_caller_hrn = the_credential.actual_caller_hrn()
self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-urns: %s\texpiration:%s\tmethod-name: %s"%\
(self.api.interface, actual_caller_hrn, urns, expiration_time,self.name))
# extend as long as possible : take the min of requested and now+SFA_MAX_SLICE_RENEW
if options.get('geni_extend_alap'):
# ignore requested time and set to max
expiration_time = add_datetime(datetime.datetime.utcnow(), days=int(self.api.config.SFA_MAX_SLICE_RENEW))
# Validate that the time does not go beyond the credential's expiration time
requested_expire = utcparse(expiration_time)
self.api.logger.info("requested_expire = %s"%requested_expire)
credential_expire = the_credential.get_expiration()
self.api.logger.info("credential_expire = %s"%credential_expire)
max_renew_days = int(self.api.config.SFA_MAX_SLICE_RENEW)
max_expire = datetime.datetime.utcnow() + datetime.timedelta (days=max_renew_days)
if requested_expire > credential_expire:
# used to throw an InsufficientRights exception here, this was not right
self.api.logger.warning("Requested expiration %s, after credential expiration (%s) -> trimming to the latter/sooner"%\
(requested_expire, credential_expire))
requested_expire = credential_expire
if requested_expire > max_expire:
# likewise
self.api.logger.warning("Requested expiration %s, after maximal expiration %s days (%s) -> trimming to the latter/sooner"%\
(requested_expire, self.api.config.SFA_MAX_SLICE_RENEW,max_expire))
requested_expire = max_expire
return self.api.manager.Renew(self.api, urns, creds, requested_expire, options)
开发者ID:kongseokhwan,项目名称:sfa,代码行数:37,代码来源:Renew.py
示例19: getCredential
def getCredential(self, minimumExpiration=0):
"""
Return a valid credential for this interface.
"""
type = 'authority'
path = self.config.SFA_DATA_DIR
filename = ".".join([self.interface, self.hrn, type, "cred"])
cred_filename = os.path.join(path,filename)
cred = None
if os.path.isfile(cred_filename):
cred = Credential(filename = cred_filename)
# make sure cred isnt expired
if not cred.get_expiration or \
datetime.datetime.utcnow() + datetime.timedelta(seconds=minimumExpiration) < cred.get_expiration():
return cred.save_to_string(save_parents=True)
# get a new credential
if self.interface in ['registry']:
cred = self._getCredentialRaw()
else:
cred = self._getCredential()
cred.save_to_file(cred_filename, save_parents=True)
return cred.save_to_string(save_parents=True)
开发者ID:gnogueras,项目名称:sfa,代码行数:24,代码来源:sfaapi.py
示例20: delegate
def delegate(self, opts, args):
delegee_hrn = args[0]
if opts.delegate_user:
user_cred = self.get_user_cred()
cred = self.delegate_cred(user_cred, delegee_hrn)
elif opts.delegate_slice:
slice_cred = self.get_slice_cred(opts.delegate_slice)
cred = self.delegate_cred(slice_cred, delegee_hrn)
else:
self.logger.warning("Must specify either --user or --slice <hrn>")
return
delegated_cred = Credential(string=cred)
object_hrn = delegated_cred.get_gid_object().get_hrn()
if opts.delegate_user:
dest_fn = os.path.join(self.options.sfi_dir, get_leaf(delegee_hrn) + "_"
+ get_leaf(object_hrn) + ".cred")
elif opts.delegate_slice:
dest_fn = os.path.join(self.options.sfi_dir, get_leaf(delegee_hrn) + "_slice_"
+ get_leaf(object_hrn) + ".cred")
delegated_cred.save_to_file(dest_fn, save_parents=True)
self.logger.info("delegated credential for %s to %s and wrote to %s"%(object_hrn, delegee_hrn,dest_fn))
开发者ID:planetlab,项目名称:sfa,代码行数:24,代码来源:sfi.py
注:本文中的sfa.trust.credential.Credential类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论