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_remove_deny(acl): acl.add_role('spy') only_default_denied = dict(acl._denied) acl.deny('spy', 'view', 'news') denied_after_denying_spy = dict(acl._denied) assert only_default_denied != denied_after_denying_spy assert not acl.is_allowed('spy', 'view', 'news') acl.remove_deny('spy', 'view', 'news') denied_after_removing_deny_spy = dict(acl._denied) assert denied_after_removing_deny_spy == only_default_denied assert not acl.is_allowed('spy', 'view', 'news') # this should still not be allowed
def create_user(): user = input(" Type new user name ") role_list = [] while True: role = input(" Please provide a role of new user ") if role == "1": break role_list.append(role) acl.add_role(role) print(" Press 1 if you are done with all roles ") acl.add_user(user, role_list) print(f"sucessfully created new uer {user} with role(s) {role_list}")
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_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_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 test_remove_role_from_parent(): acl = rbac.acl.Registry() # start with a user role, with no sub-role acl.add_role('user') roles_before_child_role = dict(acl._roles) children_before_child_role = dict(acl._children) # create the sub-role and ensure the state differs acl.add_role('activated_user', parents=['user']) children_after_child_role = dict(acl._children) roles_after_child_role = dict(acl._roles) assert children_before_child_role != children_after_child_role assert roles_before_child_role != roles_after_child_role # remove the subrole and ensure state is restored to original state acl.remove_role_from_parent(role='activated_user', parent='user') children_after_removing_child_role = dict(acl._children) roles_after_removing_child_role = dict(acl._roles) assert children_after_removing_child_role == children_before_child_role assert roles_after_removing_child_role == roles_before_child_role
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 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 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.")
import rbac.acl # create access control list acl = rbac.acl.Registry() # add roles acl.add_role("viewer") acl.add_role("user", ["viewer"]) # 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")
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 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 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)
#!/usr/bin/env python import rbac.acl # create access control list acl = rbac.acl.Registry() # 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")
__FILENAME__ = acl #!/usr/bin/env python #-*- coding:utf-8 -*- import rbac.acl # 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.")
# -*- 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()
__FILENAME__ = acl #!/usr/bin/env python # -*- coding:utf-8 -*- import rbac.acl # 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.")
#!/usr/bin/env python #-*- coding:utf-8 -*- import rbac.acl # 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.")
#!/usr/bin/env python #-*- coding:utf-8 -*- import rbac.acl # 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