本文整理汇总了Python中calvin.utilities.security.Security类的典型用法代码示例。如果您正苦于以下问题:Python Security类的具体用法?Python Security怎么用?Python Security使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Security类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: new_from_migration
def new_from_migration(self, actor_type, state, prev_connections=None, callback=None):
"""Instantiate an actor of type 'actor_type' and apply the 'state' to the actor."""
try:
_log.analyze(self.node.id, "+", state)
subject_attributes = state.pop('subject_attributes', None)
migration_info = state.pop('migration_info', None)
try:
state['_managed'].remove('subject_attributes')
state['_managed'].remove('migration_info')
except:
pass
if security_enabled():
security = Security(self.node)
security.set_subject_attributes(subject_attributes)
else:
security = None
actor_def, signer = self.lookup_and_verify(actor_type, security)
requirements = actor_def.requires if hasattr(actor_def, "requires") else []
self.check_requirements_and_sec_policy(requirements, security, state['id'],
signer, migration_info,
CalvinCB(self.new, actor_type, None,
state, prev_connections,
callback=callback,
actor_def=actor_def,
security=security))
except Exception:
# Still want to create shadow actor.
self.new(actor_type, None, state, prev_connections, callback=callback, shadow_actor=True)
示例2: testPositive_External_Authentication
def testPositive_External_Authentication(self):
_log.analyze("TESTRUN", "+", {})
result = {}
try:
content = Security.verify_signature_get_files(os.path.join(application_store_path, "correctly_signed.calvin"))
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
request_handler.set_credentials({"user": "user5", "password": "pass5"})
result = request_handler.deploy_application(runtimes[1]["RT"], "correctly_signed", content['file'],
content=content,
check=True)
except Exception as e:
if isinstance(e, Timeout):
raise Exception("Can't connect to runtime 5.\n\te={}".format(e))
elif e.message.startswith("401"):
raise Exception("Failed security verification of app correctly_signed")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app correctly_signed, no use to verify if requirements fulfilled")
# Verify that actors exist like this
try:
actors = helpers.fetch_and_log_runtime_actors(runtimes, request_handler)
except Exception as err:
_log.error("Failed to get actors from runtimes, err={}".format(err))
raise
assert result['actor_map']['correctly_signed:src'] in actors[1]
assert result['actor_map']['correctly_signed:sum'] in actors[1]
assert result['actor_map']['correctly_signed:snk'] in actors[1]
time.sleep(0.1)
actual = request_handler.report(runtimes[1]["RT"], result['actor_map']['correctly_signed:snk'])
assert len(actual) > 2
request_handler.delete_application(runtimes[1]["RT"], result['application_id'])
示例3: __init__
def __init__(self, deployable, node, name=None, deploy_info=None, credentials=None, verify=True, cb=None):
super(Deployer, self).__init__()
self.deployable = deployable
self.deploy_info = deploy_info
self.credentials = credentials
self.sec = Security(node)
self.sec.set_subject(self.credentials)
self.actorstore = ActorStore(security=self.sec)
self.actor_map = {}
self.actor_connections = {}
self.node = node
self.verify = verify
self.cb = cb
self._deploy_cont_done = False
if name:
self.name = name
self.app_id = self.node.app_manager.new(self.name)
self.ns = os.path.splitext(os.path.basename(self.name))[0]
elif "name" in self.deployable:
self.name = self.deployable["name"]
self.app_id = self.node.app_manager.new(self.name)
self.ns = os.path.splitext(os.path.basename(self.name))[0]
else:
self.app_id = self.node.app_manager.new(None)
self.name = self.app_id
self.ns = ""
self.group_components()
_log.analyze(self.node.id, "+ SECURITY", {'sec': str(self.sec)})
示例4: deploy_signed_application_that_should_fail
def deploy_signed_application_that_should_fail(request_handler, runtimes, name, application_path, retries=20):
"""
Deploys app associated w/ deployer and then tries to verify its
presence in registry (for all runtimes).
"""
from calvin.utilities.security import Security
delay = 0.1
retry = 0
result = None
while retry < retries:
try:
content = Security.verify_signature_get_files(application_path)
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
result = request_handler.deploy_application(runtimes, name, script=content['file'], content=content, check=True)
except Exception as e:
try:
if e.message.startswith("401"):
return
except Exception as e:
_log.error("Failed for other reasons, continue, e={}".format(e))
continue
delay = min(2, delay * 1.5); retry += 1
time.sleep(delay)
_log.info("Deployment failed, but not due to security reasons, %d retries" % (retry))
raise Exception("Deployment of app correctly_signed, did not fail for security reasons")
示例5: testSecurity_NEGATIVE_CorrectlySignedApp_IncorrectlySignedActor
def testSecurity_NEGATIVE_CorrectlySignedApp_IncorrectlySignedActor(self):
_log.analyze("TESTRUN", "+", {})
global rt1
global security_test_dir
self.verify_storage()
result = {}
try:
content = Security.verify_signature_get_files(security_test_dir + "/scripts/test_security1_correctlySignedApp_incorrectlySignedActor.calvin")
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
result = request_handler.deploy_application(rt1, "test_security1_correctlySignedApp_incorrectlySignedActor", content['file'],
credentials={"user": ["user1"], "password": ["pass1"]}, content=content,
check=True)
except Exception as e:
_log.debug(str(e))
if e.message.startswith("401"):
raise Exception("Failed security verification of app testSecurity_NEGATIVE_CorrectlySignedApp_IncorrectlySignedActor")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app testSecurity_NEGATIVE_CorrectlySignedApp_IncorrectlySignedActor, no use to verify if requirements fulfilled")
#print "RESULT:", result
time.sleep(2)
# Verify that actors exist like this
actors = request_handler.get_actors(rt1)
assert result['actor_map']['test_security1_correctlySignedApp_incorrectlySignedActor:src'] in actors
assert result['actor_map']['test_security1_correctlySignedApp_incorrectlySignedActor:sum'] in actors
assert result['actor_map']['test_security1_correctlySignedApp_incorrectlySignedActor:snk'] in actors
actual = request_handler.report(rt1, result['actor_map']['test_security1_correctlySignedApp_incorrectlySignedActor:snk'])
assert len(actual) == 0
request_handler.delete_application(rt1, result['application_id'])
示例6: testPositive_Permit_UnsignedApp_Unsigned_Actor
def testPositive_Permit_UnsignedApp_Unsigned_Actor(self):
_log.analyze("TESTRUN", "+", {})
result = {}
try:
content = Security.verify_signature_get_files(os.path.join(application_store_path, "unsignedApp_unsignedActors.calvin"))
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
request_handler.set_credentials({"user": "user3", "password": "pass3"})
result = request_handler.deploy_application(runtimes[1]["RT"], "unsignedApp_unsignedActors", content['file'],
content=content,
check=True)
except Exception as e:
if e.message.startswith("401"):
raise Exception("Failed security verification of app unsignedApp_unsignedActors")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app unsignedApp_unsignedActors, no use to verify if requirements fulfilled")
# Verify that actors exist like this
try:
actors = helpers.fetch_and_log_runtime_actors(runtimes, request_handler)
except Exception as err:
_log.error("Failed to get actors from runtimes, err={}".format(err))
raise
assert result['actor_map']['unsignedApp_unsignedActors:src'] in actors[1]
assert result['actor_map']['unsignedApp_unsignedActors:sum'] in actors[1]
assert result['actor_map']['unsignedApp_unsignedActors:snk'] in actors[1]
actual = request_handler.report(runtimes[1]["RT"], result['actor_map']['unsignedApp_unsignedActors:snk'])
assert len(actual) > 2
request_handler.delete_application(runtimes[1]["RT"], result['application_id'])
示例7: testSecurity_POSITIVE_RADIUS_Authentication
def testSecurity_POSITIVE_RADIUS_Authentication(self):
_log.analyze("TESTRUN", "+", {})
global rt3
global security_test_dir
self.verify_storage()
result = {}
try:
content = Security.verify_signature_get_files(security_test_dir + "/scripts/test_security1_correctly_signed.calvin")
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
result = request_handler.deploy_application(rt3, "test_security1_correctly_signed", content['file'],
credentials={"user": ["radius_user1"], "password": ["radius_passwd1"]}, content=content,
check=True)
except Exception as e:
if e.message.startswith("401"):
raise Exception("Failed security verification of app test_security1_correctly_signed")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app test_security1_correctly_signed, no use to verify if requirements fulfilled")
#print "RESULT:", result
time.sleep(2)
# For example verify that actors exist like this
actors = request_handler.get_actors(rt3)
assert result['actor_map']['test_security1_correctly_signed:src'] in actors
assert result['actor_map']['test_security1_correctly_signed:sum'] in actors
assert result['actor_map']['test_security1_correctly_signed:snk'] in actors
actual = request_handler.report(rt3, result['actor_map']['test_security1_correctly_signed:snk'])
assert len(actual) > 5
request_handler.delete_application(rt3, result['application_id'])
示例8: testNegative_Deny_SignedApp_SignedActor_UnallowedRequirement
def testNegative_Deny_SignedApp_SignedActor_UnallowedRequirement(self):
_log.analyze("TESTRUN", "+", {})
result = {}
try:
content = Security.verify_signature_get_files(os.path.join(application_store_path, "correctly_signed.calvin"))
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
request_handler.set_credentials({"user": "user1", "password": "pass1"})
result = request_handler.deploy_application(runtimes[2]["RT"], "correctly_signed", content['file'],
content=content,
check=True)
except Exception as e:
_log.debug(str(e))
if e.message.startswith("401"):
raise Exception("Failed security verification of app correctly_signed")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app correctly_signed, no use to verify if requirements fulfilled")
# Verify that actors exist like this
try:
actors = helpers.fetch_and_log_runtime_actors(runtimes, request_handler)
except Exception as err:
_log.error("Failed to get actors from runtimes, err={}".format(err))
raise
assert result['actor_map']['correctly_signed:src'] in actors[2]
assert result['actor_map']['correctly_signed:sum'] in actors[2]
assert result['actor_map']['correctly_signed:snk'] in actors[2]
actual = request_handler.report(runtimes[2]["RT"], result['actor_map']['correctly_signed:snk'])
_log.debug("actual={}".format(actual))
assert len(actual) == 0 # Means that the actor with unallowed requirements was not accepted
request_handler.delete_application(runtimes[2]["RT"], result['application_id'])
示例9: testSecurity_NEGATIVE_IncorrectPassword
def testSecurity_NEGATIVE_IncorrectPassword(self):
_log.analyze("TESTRUN", "+", {})
global rt1
global security_test_dir
self.verify_storage()
result = {}
try:
content = Security.verify_signature_get_files(
os.path.join(security_test_dir, "scripts", "test_security1_correctly_signed.calvin")
)
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
result = request_handler.deploy_application(
rt1,
"test_security1_correctly_signed",
content["file"],
credentials={"testdomain": {"user": "user1", "password": "incorrect_password"}},
content=content,
check=True,
)
except Exception as e:
if e.message.startswith("401"):
# We were blocked, as we should
return
_log.exception("Test deploy failed for non security reasons")
raise Exception("Deployment of app test_security1_correctly_signed, did not fail for security reasons")
示例10: testSecurity_POSITIVE_External_Authorization
def testSecurity_POSITIVE_External_Authorization(self):
_log.analyze("TESTRUN", "+", {})
global rt4
global security_test_dir
self.verify_storage()
result = {}
try:
content = Security.verify_signature_get_files(os.path.join(security_test_dir, "scripts", "test_security1_unsignedApp_signedActors.calvin"))
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
result = request_handler.deploy_application(rt4, "test_security1_unsignedApp_signedActors", content['file'],
credentials={"user": ["user2"], "password": ["pass2"]}, content=content,
check=True)
except Exception as e:
if e.message.startswith("401"):
raise Exception("Failed security verification of app test_security1_unsignedApp_signedActors")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app test_security1_unsignedApp_signedActors, no use to verify if requirements fulfilled")
time.sleep(2)
# Verify that actors exist like this
actors = request_handler.get_actors(rt4)
assert result['actor_map']['test_security1_unsignedApp_signedActors:src'] in actors
assert result['actor_map']['test_security1_unsignedApp_signedActors:sum'] in actors
assert result['actor_map']['test_security1_unsignedApp_signedActors:snk'] in actors
actual = request_handler.report(rt4, result['actor_map']['test_security1_unsignedApp_signedActors:snk'])
assert len(actual) > 5
request_handler.delete_application(rt4, result['application_id'])
示例11: testSecurity_NEGATIVE_Deny_SignedApp_SignedActor_UnallowedRequirement
def testSecurity_NEGATIVE_Deny_SignedApp_SignedActor_UnallowedRequirement(self):
_log.analyze("TESTRUN", "+", {})
global rt2
global security_test_dir
self.verify_storage()
result = {}
try:
content = Security.verify_signature_get_files(os.path.join(security_test_dir, "scripts", "test_security1_correctly_signed.calvin"))
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
result = request_handler.deploy_application(rt2, "test_security1_correctly_signed", content['file'],
credentials={"user": ["user1"], "password": ["pass1"]}, content=content,
check=True)
except Exception as e:
_log.debug(str(e))
if e.message.startswith("401"):
raise Exception("Failed security verification of app test_security1_correctly_signed")
_log.exception("Test deploy failed")
raise Exception("Failed deployment of app test_security1_correctly_signed, no use to verify if requirements fulfilled")
time.sleep(2)
# Verify that actors exist like this
actors = request_handler.get_actors(rt2)
assert result['actor_map']['test_security1_correctly_signed:src'] in actors
assert result['actor_map']['test_security1_correctly_signed:sum'] in actors
assert result['actor_map']['test_security1_correctly_signed:snk'] in actors
actual = request_handler.report(rt2, result['actor_map']['test_security1_correctly_signed:snk'])
assert len(actual) == 0 # Means that the actor with unallowed requirements was not accepted
request_handler.delete_application(rt2, result['application_id'])
示例12: control_deploy
def control_deploy(args):
response = None
reqs = requirements_file(args.reqs) if args.reqs else None
if args.signer:
conf = certificate.Config(configfile=None, domain=args.signer, readonly=True)
certificate.sign_file(conf, args.script.name)
source_text = args.script.read()
credentials_ = None
content = None
if args.credentials:
try:
credentials_ = json.loads(args.credentials)
except Exception as e:
print "Credentials not JSON:\n", e
return -1
if credentials_:
content = Security.verify_signature_get_files(args.script.name, skip_file=True)
if content:
content['file'] = source_text
try:
response = get_request_handler().deploy_application(args.node, args.script.name, source_text, reqs,
credentials=credentials_, content=content, check=args.check)
except Exception as e:
print e
return response
示例13: compile_file
def compile_file(file, credentials=None):
with open(file, 'r') as source:
sourceText = source.read()
content = None
if credentials:
content = Security.verify_signature_get_files(file, skip_file=True)
if content:
content['file'] = sourceText
return compile(sourceText, file, content=content, credentials=credentials)
示例14: deploy_signed_application
def deploy_signed_application(request_handler, runtimes, name, application_path, retries=10):
"""
Deploys app associated w/ deployer and then tries to verify its
presence in registry (for all runtimes).
"""
from functools import partial
from calvin.utilities.security import Security
content = Security.verify_signature_get_files(application_path)
if not content:
raise Exception("Failed finding script, signature and cert, stopping here")
return retry(retries, partial(request_handler.deploy_application, runtimes, name, script=content['file'], content=content, check=True), lambda _: True, "Failed to deploy application")
示例15: compile
def compile(source_text, filename='', content=None, credentials=None, verify=True):
# Steps taken:
# 1) Verify signature when credentials supplied
# 2) parser .calvin file -> IR. May produce syntax errors/warnings
# 3) checker IR -> IR. May produce syntax errors/warnings
# 4) analyzer IR -> app. Should not fail. Sets 'valid' property of IR to True/False
deployable = {'valid': False, 'actors': {}, 'connections': {}}
errors = [] #TODO: fill in something meaningful
warnings = []
if credentials:
_log.debug("Check credentials...")
sec = Security()
sec.set_principal(credentials)
if not sec.authenticate_principal():
_log.error("Check credentials...failed authentication")
# This error reason is detected in calvin control and gives proper REST response
errors.append({'reason': "401: UNAUTHORIZED", 'line': 0, 'col': 0})
return deployable, errors, warnings
if not sec.verify_signature_content(content, "application"):
_log.error("Check credentials...failed application verification")
# This error reason is detected in calvin control and gives proper REST response
errors.append({'reason': "401: UNAUTHORIZED", 'line': None, 'col': None})
return deployable, errors, warnings
_log.debug("Parsing...")
ir, errors, warnings = calvin_parser(source_text, filename)
_log.debug("Parsed %s, %s, %s" % (ir, errors, warnings))
# If there were errors during parsing no IR will be generated
if not errors:
c_errors, c_warnings = check(ir, verify=verify)
errors.extend(c_errors)
warnings.extend(c_warnings)
deployable = generate_app_info(ir, verify=verify)
if errors:
deployable['valid'] = False
_log.debug("Compiled %s, %s, %s" % (deployable, errors, warnings))
return deployable, errors, warnings