def test_assertion(acl): # set up assertion db = {'newsid': 1} def check(acl, role, operation, resource): return db['newsid'] == 10 assertion = check # set up rules acl.add_role('writer2', parents=['writer']) acl.allow('writer', 'edit', 'news', assertion) acl.allow('manager', 'edit', 'news') # test while assertion is invalid assert not acl.is_allowed('writer', 'edit', 'news') assert not acl.is_allowed('writer2', 'edit', 'news') assert acl.is_allowed('manager', 'edit', 'news') assert acl.is_allowed('editor', 'edit', 'news') # test while assertion is valid db['newsid'] = 10 assert acl.is_allowed('writer', 'edit', 'news') assert acl.is_allowed('editor', 'edit', 'news') assert acl.is_allowed('manager', 'edit', 'news')
def test_delete_role(acl): acl.add_role('nonspy') # our control who should remain unaffected acl.allow('nonspy', 'view', 'news') acl.deny('nonspy', 'edit', 'news') acl.add_role('spy') acl.allow('spy', 'view', 'news') acl.deny('spy', 'edit', 'news') assert acl.is_allowed('spy', 'view', 'news') assert not acl.is_allowed('spy', 'edit', 'news') # oh no! we found a spy! remove them! acl.delete_role('spy') # as the role no longer exists it should raise an assertion with pytest.raises(AssertionError): assert not acl.is_allowed('spy', 'view', 'news') with pytest.raises(AssertionError): assert not acl.is_allowed('spy', 'edit', 'news') # as an extra check let's make sure we don't see any orphaned # rules for 'spy' in _allowed or _denied for rule_list in (acl._allowed, acl._denied): for rule in rule_list: assert rule[0] != 'spy' # nonspy should be unaffected by all this assert acl.is_allowed('nonspy', 'view', 'news') assert not acl.is_allowed('nonspy', 'edit', 'news')
def test_child_role_deletion(acl): # create unrelated parent and child acl.add_role('unrelated') acl.add_role('unrelated', ['spawn']) acl.allow('unrelated', 'view', 'news') assert 'unrelated' in str(acl._children) assert 'spawn' in str(acl._children) # create parent and child, that we care about acl.add_role('daddy') acl.allow('daddy', 'view', 'news') assert 'daddy' not in str(acl._children) acl.add_role('kiddo', ['daddy']) assert 'daddy' in str(acl._children) assert 'kiddo' in str(acl._children) assert acl.is_allowed('kiddo', 'view', 'news') # ensure we can't delete a father who has a dependent child with pytest.raises(AssertionError): acl.delete_role('daddy') # delete child role acl.delete_role('kiddo') assert 'kiddo' not in str(acl._children) assert acl.is_allowed('daddy', 'view', 'news') # ensure we CAN delete a father with no dependent children acl.delete_role('daddy') with pytest.raises(AssertionError): acl.is_allowed('daddy', 'view', 'news') # make sure those unrelated father and child remain assert 'unrelated' in str(acl._children) assert 'spawn' in str(acl._children)
def test_remove_allow(acl): only_default_allowed = dict(acl._allowed) acl.allow('writer', 'new', 'news') allowed_after_allowing_writer = dict(acl._allowed) assert only_default_allowed != allowed_after_allowing_writer assert acl.is_allowed('writer', 'new', 'news') acl.remove_allow('writer', 'new', 'news') allowed_after_removing_allowing_writer = dict(acl._allowed) assert allowed_after_removing_allowing_writer == only_default_allowed assert not acl.is_allowed('writer', 'new', 'news')
def test_short_circuit_skip_allow(acl, context, evaluated_roles): """Once one role is passed, shouldn't other roles should not be checked.""" # track which roles have their assertion function evaluated assertion = _FunctionProxy(lambda *args, **kwargs: args[1] == '3', evaluated_roles, role_idx=1) acl.add_resource('my_resource') roles = [str(i) for i in range(10)] for i, role in enumerate(roles): acl.add_role(role) acl.allow(role, 'view', 'my_resource', assertion=assertion) context.set_roles_loader(lambda: roles) context.has_permission('view', 'my_resource') # since role '3' was allowed, 'allowed' isn't checked on any role assert evaluated_roles == roles[0:4]
def test_allow(acl): # add allowed rules acl.allow('actived_user', 'view', 'news') acl.allow('writer', 'new', 'news') # test 'view' operation roles = ['actived_user', 'writer', 'manager', 'editor'] for role in roles: for resource in ['news', 'event']: assert acl.is_allowed(role, 'view', resource) for resource in ['post', 'infor']: assert not acl.is_allowed(role, 'view', resource) for resource in ['news', 'event']: assert acl.is_any_allowed(roles, 'view', resource) for resource in ['post', 'infor']: assert not acl.is_any_allowed(roles, 'view', resource) for resource in ['post', 'news', 'infor', 'event']: assert not acl.is_allowed('user', 'view', resource) assert acl.is_allowed('super', 'view', resource) assert acl.is_allowed('super', 'new', resource) assert acl.is_any_allowed(['user', 'super'], 'view', resource) # test 'new' operation roles = ['writer', 'editor'] for role in roles: for resource in ['news', 'event']: assert acl.is_allowed(role, 'new', resource) for resource in ['post', 'infor']: assert not acl.is_allowed(role, 'new', resource) for resource in ['news', 'event']: assert acl.is_any_allowed(roles, 'new', resource) for resource in ['post', 'infor']: assert not acl.is_any_allowed(roles, 'new', resource) roles = ['user', 'manager'] for role in roles: for resource in ['news', 'event', 'post', 'infor']: assert not acl.is_allowed(role, 'new', resource) for resource in ['news', 'event', 'post', 'infor']: assert not acl.is_any_allowed(roles, 'new', resource)
def test_role_evaluation_order_preserved(acl, context, evaluated_roles): # decorate acl.is_allowed so we can track role evaluation order setattr(acl, 'is_allowed', _FunctionProxy(acl.is_allowed, evaluated_roles)) # add roles as a list in the expected order (1 through 10) acl.add_resource('my_resource') roles = [str(i) for i in range(10)] for i, role in enumerate(roles): acl.add_role(role) context.set_roles_loader(lambda: roles) # allow only the final role to avoid short-circuiting acl.allow(roles[9], 'view', 'my_resource') context.has_permission('view', 'my_resource') # check that the roles were evaluated in order assert evaluated_roles == roles
def acl(): # create context acl = rbac.acl.Registry() # self.denied_error = rbac.context.PermissionDenied # register roles and resources acl.add_role('staff') acl.add_role('editor', parents=['staff']) acl.add_role('badguy', parents=['staff']) acl.add_resource('article') # add rules acl.allow('staff', 'view', 'article') acl.allow('editor', 'edit', 'article') acl.deny('badguy', None, 'article') return acl
def test_delete_role_with_child_roles_fails(acl): acl.add_role('nonspy') # our control who should remain unaffected acl.allow('nonspy', 'view', 'news') acl.deny('nonspy', 'edit', 'news') acl.add_role('spy') acl.add_role('childspy', ['spy']) # should prevent deletion acl.allow('spy', 'view', 'news') acl.deny('spy', 'edit', 'news') assert acl.is_allowed('spy', 'view', 'news') assert not acl.is_allowed('spy', 'edit', 'news') # as it has a child role it should assert with pytest.raises(AssertionError): acl.delete_role('spy') # nonspy should be unaffected by all this assert acl.is_allowed('nonspy', 'view', 'news') assert not acl.is_allowed('nonspy', 'edit', 'news')
def test_deny(acl): # add allowed rule and denied rule acl.allow('actived_user', 'new', 'comment') acl.deny('manager', 'new', 'comment') # test allowed rules roles = ['actived_user', 'writer'] for role in roles: assert acl.is_allowed(role, 'new', 'comment') assert acl.is_any_allowed(roles, 'new', 'comment') # test denied rules roles = ['manager', 'editor'] for role in roles: assert not acl.is_allowed(role, 'new', 'comment') assert not acl.is_any_allowed(roles, 'new', 'comment')
def acl(request): # create acl registry from parametrized factory acl = request.param() # add roles acl.add_role('user') acl.add_role('actived_user', parents=['user']) acl.add_role('writer', parents=['actived_user']) acl.add_role('manager', parents=['actived_user']) acl.add_role('editor', parents=['writer', 'manager']) acl.add_role('super') # add resources acl.add_resource('comment') acl.add_resource('post') acl.add_resource('news', parents=['post']) acl.add_resource('infor', parents=['post']) acl.add_resource('event', parents=['news']) # set super permission acl.allow('super', None, None) return acl
def test_short_circuit_skip_deny(acl, context, evaluated_roles): """ If no remaining role could grant access, don't bother checking """ # track which roles are evaluated setattr(acl, 'is_allowed', _FunctionProxy(acl.is_allowed, evaluated_roles)) acl.add_resource('the dinosaurs') roles = ['tourist', 'scientist', 'intern'] for role in roles: acl.add_role(role) context.set_roles_loader(lambda: roles) # explicitly deny one role and don't allow any permissions to others acl.deny('intern', 'feed', 'the dinosaurs') context.has_permission('feed', 'the dinosaurs') # no roles checked, since all are deny-only assert evaluated_roles == [] acl.allow('scientist', 'study', 'the dinosaurs') context.has_permission('feed', 'the dinosaurs') # since scientist is no longer deny-only, # only the intern check will be skipped assert evaluated_roles == ['tourist', 'scientist']
def edit_role(user): role = input("which role you want to edit ") if acl.is_valid_role(role): allowed, denied = acl.get_role_permissions(role) print( f" Current permissions for {role} are: Allowed: {allowed}, Denied: {denied}" ) print(f" All available resources are: {acl.get_all_resources()}") resource = input(" Enter resource name ") if acl.is_valid_resource(resource): operation = input( " Enter permission name like read, write or delete ") allow_or_deny = input( " Enter permission Type, Press 1 for Allow, 2 for deny ") if allow_or_deny == "1": acl.allow(role, operation, resource) elif allow_or_deny == "2": acl.deny(role, operation, resource) else: print("Wrong input {allow_or_deny}") start_intracting(user) allowed, denied = acl.get_role_permissions(role) print( f" Updated permissions for {role} are: Allowed: {allowed}, Denied: {denied}" ) else: print( f" This {resource} is not a valid resource, you can try again") edit_role(user) else: print(f"{role} is not valid role") print(" Valid roles are: ", acl.get_all_roles()) print(" Press X for restart: ") if role.lower() == "x": start_intracting(user) edit_role(user)
# -*- coding: utf-8 -*- # __author__: musibii # __file__ : test1.py # __time__ : 2020/4/29 11:05 上午 import rbac.acl acl = rbac.acl.Registry() acl.add_role() acl.add_resource(acl) acl.allow() acl.deny() acl.is_allowed()
# create access control list acl = rbac.acl.Registry() # add roles acl.add_role("member") acl.add_role("student", ["member"]) acl.add_role("teacher", ["member"]) acl.add_role("junior-student", ["student"]) # add resources acl.add_resource("course") acl.add_resource("senior-course", ["course"]) # set rules acl.allow("member", "view", "course") acl.allow("student", "learn", "course") acl.allow("teacher", "teach", "course") acl.deny("junior-student", "learn", "senior-course") # use acl to check permission if acl.is_allowed("student", "view", "course"): print ("Students chould view courses.") else: print ("Students chould not view courses.") # use acl to check permission again if acl.is_allowed("junior-student", "learn", "senior-course"): print ("Junior students chould learn senior courses.") else: print ("Junior students chould not learn senior courses.")
# create access control list acl = rbac.acl.Registry() # add roles acl.add_role("member") acl.add_role("student", ["member"]) acl.add_role("teacher", ["member"]) acl.add_role("junior-student", ["student"]) # add resources acl.add_resource("course") acl.add_resource("senior-course", ["course"]) # set rules acl.allow("member", "view", "course") acl.allow("student", "learn", "course") acl.allow("teacher", "teach", "course") acl.deny("junior-student", "learn", "senior-course") # use acl to check permission if acl.is_allowed("student", "view", "course"): print("Students chould view courses.") else: print("Students chould not view courses.") # use acl to check permission again if acl.is_allowed("junior-student", "learn", "senior-course"): print("Junior students chould learn senior courses.") else: print("Junior students chould not learn senior courses.")
def main(): # current context user current_user = None # create a access control list acl = RegistryProxy(Registry()) identity = IdentityContext(acl, lambda: current_user.get_roles()) # registry roles and resources acl.add_role("staff") acl.add_role("admin") acl.add_resource(Message) # add rules is_message_owner = lambda acl, role, operation, resource: db.query(Message).get(resource.id).owner is current_user acl.allow("staff", "create", Message) acl.allow("staff", "edit", Message, assertion=is_message_owner) acl.allow("admin", "edit", Message) db = Session() ModelBase.metadata.create_all(engine) tonyseek = User(name="tonyseek") tonyseek.set_roles(["staff"]) tom = User(name="tom") tom.set_roles(["staff"]) admin = User(name="admin") admin.set_roles(["admin"]) db.add_all([tonyseek, tom, admin]) db.commit() @identity.check_permission("create", Message) def create_message(content): message = Message(content=content, owner=current_user) db.add(message) db.commit() print "%s has craeted a message: '%s'." % (current_user.name.capitalize(), content) def edit_message(content, new_content): message = db.query(Message).filter_by(content=content).one() if not identity.check_permission("edit", message): print "%s tried to edit the message '%s' but he will fail." % (current_user.name.capitalize(), content) else: print "%s will edit the message '%s'." % (current_user.name.capitalize(), content) with identity.check_permission("edit", message): message.content = new_content db.commit() print "The message '%s' has been edit by %s," % (content, current_user.name.capitalize()), print "the new content is '%s'" % new_content # tonyseek signed in and create a message current_user = tonyseek create_message("Please open the door.") # tom signed in and edit tonyseek's message current_user = tom try: edit_message("Please open the door.", "Please don't open the door.") except PermissionDenied: print "Oh, the operation has been denied." # tonyseek signed in and edit his message current_user = tonyseek edit_message("Please open the door.", "Please don't open the door.") # admin signed in and edit tonyseek's message current_user = admin edit_message("Please don't open the door.", "Please open the window.")
def main(): # current context user current_user = None # create a access control list acl = RegistryProxy(Registry()) identity = IdentityContext(acl, lambda: current_user.get_roles()) # registry roles and resources acl.add_role("staff") acl.add_role("admin") acl.add_resource(Message) # add rules is_message_owner = lambda acl, role, operation, resource: \ db.query(Message).get(resource.id).owner is current_user acl.allow("staff", "create", Message) acl.allow("staff", "edit", Message, assertion=is_message_owner) acl.allow("admin", "edit", Message) db = Session() ModelBase.metadata.create_all(engine) tonyseek = User(name="tonyseek") tonyseek.set_roles(["staff"]) tom = User(name="tom") tom.set_roles(["staff"]) admin = User(name="admin") admin.set_roles(["admin"]) db.add_all([tonyseek, tom, admin]) db.commit() @identity.check_permission("create", Message) def create_message(content): message = Message(content=content, owner=current_user) db.add(message) db.commit() print "%s has craeted a message: '%s'." % ( current_user.name.capitalize(), content) def edit_message(content, new_content): message = db.query(Message).filter_by(content=content).one() if not identity.check_permission("edit", message): print "%s tried to edit the message '%s' but he will fail." % ( current_user.name.capitalize(), content) else: print "%s will edit the message '%s'." % ( current_user.name.capitalize(), content) with identity.check_permission("edit", message): message.content = new_content db.commit() print "The message '%s' has been edit by %s," % ( content, current_user.name.capitalize()), print "the new content is '%s'" % new_content # tonyseek signed in and create a message current_user = tonyseek create_message("Please open the door.") # tom signed in and edit tonyseek's message current_user = tom try: edit_message("Please open the door.", "Please don't open the door.") except PermissionDenied: print "Oh, the operation has been denied." # tonyseek signed in and edit his message current_user = tonyseek edit_message("Please open the door.", "Please don't open the door.") # admin signed in and edit tonyseek's message current_user = admin edit_message("Please don't open the door.", "Please open the window.")
# add resources acl.add_resource("register") acl.add_resource("user_login") acl.add_resource("user_search") acl.add_resource("make_transaction") acl.add_resource("user_profile_view") acl.add_resource("user_profile") acl.add_resource("show_notification") acl.add_resource("delete_account") acl.add_resource("add_notification") acl.add_resource("move_notification") acl.add_resource("logout") # set rules acl.allow("viewer", "access", "register") acl.allow("viewer", "access", "user_login") acl.allow("user", "access", "user_search") acl.allow("user", "access", "make_transaction") acl.allow("user", "access", "user_profile_view") acl.allow("user", "access", "user_profile") acl.allow("user", "access", "show_notification") acl.allow("user", "access", "delete_account") acl.allow("user", "access", "add_notification") acl.allow("user", "access", "move_notification") acl.allow("user", "access", "logout") if (__name__ == "__main__"): # use acl to check permission if acl.is_allowed("viewer", "access", "register"): print("Viewer can access register.")
# add Default roles acl.add_role("admin") acl.add_role("developer") # add Default users acl.add_user("admin", ["admin"]) acl.add_user("user1", ["developer"]) # add resources acl.add_resource("resource-1") acl.add_resource("resource-2") # set rules # Admin have all permissions acl.allow("admin", "read", "resource-1") acl.allow("admin", "write", "resource-1") acl.allow("admin", "delete", "resource-1") acl.allow("admin", "read", "resource-2") acl.allow("admin", "write", "resource-2") acl.allow("admin", "delete", "resource-2") # Developer have read, write permission but not delete acl.allow("developer", "read", "resource-1") acl.allow("developer", "write", "resource-1") acl.deny("developer", "delete", "resource-1") def edit_role(user): role = input("which role you want to edit ")
def get(self, request, action, *args, **kwargs): acl = rbac.acl.Registry() if action == 'generate-roles': print 'Generating roles...' acl.add_role("InternUsers") print "\t Added Role: InternUsers" acl.add_role("Directors",["InternUsers"]) print "\t Added Role: Directors" acl.add_role("Writers",["InternUsers"]) print "\t Added Role: Writers" acl.add_role("Auditors",["InternUsers"]) print "\t Added Role: Auditors" acl.add_role("ExternUsers") print "\t Added Role: ExternUsers" print "\t\t[Done]" #TODO [POM] Agregar usuarios creados a roles como hojas del arbol elif action == 'generate-resources': print 'Generating resources...' acl.add_resource("noticia") print "\t Added Resource: Noticia" noticias = Noticia.objects.all() for noticia in noticias: acl.add_resource("noticia-"+noticia.title, ["noticia"]) print "\t Added Resource: noticia-%s" % noticia.title print "\t\t[Done]" elif action == 'generate-rules': print 'Generating rules...' acl.allow("InternUsers","read","noticia") print "\tInternUsers can read noticia" acl.allow("Writers","write","noticia") print "\tWriters can write noticia" acl.allow("Auditors","update","noticia") print "\tAuditors can update noticia" acl.allow("Auditors","delete","noticia") print "\tAuditors can delete noticia" acl.deny("ExternUsers","write","noticia") print "\tExternUsers can not write noticia" acl.deny("ExternUsers","update","noticia") print "\tExternUsers can not update noticia" acl.deny("ExternUsers","delete","noticia") print "\tExternUsers can not delete noticia" print "\t\t[Done]" #TODO [POM] Permitir a usuarios que compartan la misma revista, que compartan el mismo permiso elif action == 'test-onthefly': print 'Generating roles...' acl.add_role("InternUsers") print "\t Added Role: InternUsers" acl.add_role("Directors",["InternUsers"]) print "\t Added Role: Directors" acl.add_role("Writers",["InternUsers"]) print "\t Added Role: Writers" acl.add_role("Auditors",["InternUsers"]) print "\t Added Role: Auditors" acl.add_role("ExternUsers") print "\t Added Role: ExternUsers" print "\t\t[Done]" print 'Generating resources...' acl.add_resource("noticia") print "\t Added Resource: Noticia" noticias = Noticia.objects.all() for noticia in noticias: acl.add_resource("noticia-"+noticia.title, ["noticia"]) print "\t Added Resource: noticia-%s" % noticia.title print "\t\t[Done]" print 'Generating rules...' acl.allow("InternUsers","read","noticia") print "\tInternUsers can read noticia" acl.allow("Writers","write","noticia") print "\tWriters can write noticia" acl.allow("Auditors","update","noticia") print "\tAuditors can update noticia" acl.allow("Auditors","delete","noticia") print "\tAuditors can delete noticia" acl.deny("ExternUsers","write","noticia") print "\tExternUsers can not write noticia" acl.deny("ExternUsers","update","noticia") print "\tExternUsers can not update noticia" acl.deny("ExternUsers","delete","noticia") print "\tExternUsers can not delete noticia" print "\t\t[Done]" if acl.is_allowed("Auditors","write","noticia"): print "Auditors can write noticia" else: print "Auditors can not write noticia" else: print 'Command unknown.' return super(RoleManager,self).get(self,request,*args,**kwargs)