def role_for_system_scope(): role = Role( name="requestcreator", permissions=["request:create", "request:read"] ).save() yield role role.delete()
def system_admin_role(): role = Role(name="system_admin", permissions=["system:read", "system:update", "queue:read"]).save() yield role role.delete()
def test_create_with_invalid_permissions(self): permissions = ["invalid_permission"] role = Role(name="test_role", permissions=permissions) with pytest.raises(ValidationError): role.save()
def test_patch_add_role(self, http_client, base_url, mongo_principal, mongo_role): mongo_role.save() mongo_principal.save() new_role = Role(name="new_role", description="Some desc", roles=[], permissions=["bg-all"]) new_role.save() body = PatchOperation(operation="add", path="/roles", value="new_role") url = base_url + "/api/v1/users/" + str(mongo_principal.id) request = HTTPRequest( url, method="PATCH", headers={"content-type": "application/json"}, body=SchemaParser.serialize_patch(body), ) response = yield http_client.fetch(request, raise_error=False) assert response.code == 200 updated = SchemaParser.parse_principal(response.body.decode("utf-8"), from_string=True) assert len(updated.roles) == 2
def event_forward_role(): role = Role( name="event_forward", permissions=["event:forward"], ).save() yield role role.delete()
def user_admin_role(): role = Role( name="user_admin", permissions=["user:create", "user:read", "user:update", "user:delete"], ).save() yield role role.delete()
def garden_read_role(): role = Role( name="garden_read", permissions=["garden:read"], ).save() yield role role.delete()
def garden_create_role(): role = Role( name="garden_create", permissions=["garden:create"], ).save() yield role role.delete()
def system_read_role(): role = Role( name="system_admin", permissions=["system:read"], ).save() yield role role.delete()
def queue_manager_role(): role = Role( name="queue_manager", permissions=["queue:read", "queue:delete"], ).save() yield role role.delete()
def garden_admin_role(): role = Role( name="garden_admin", permissions=["garden:read", "garden:update"], ).save() yield role role.delete()
def role_for_garden_scope(): role = Role( name="gardenreader", permissions=["garden:read", "system:read", "job:read", "request:read"], ).save() yield role role.delete()
def user_to_sync(self): role = Role(name="role1").save() role_assignment = RoleAssignment(role=role, domain={"scope": "Global"}) user = User(username="******", password="******", role_assignments=[role_assignment]) yield user role.delete()
def test_create_with_valid_permissions(self): permissions = [ Permissions.REQUEST_READ.value, Permissions.REQUEST_CREATE.value ] role = Role(name="test_role", permissions=permissions) role.save() assert Role.objects.filter(name="test_role").count() == 1
def remove_role(role: Role): """Remove a Role. This will also remove any references to the Role, such as those in User role assignments. Args: role: The Role document object. Returns: None """ remove_role_assignments_for_role(role) role.delete()
def operator_role(): role = Role( name="operator", permissions=[ "request:create", "request:read", "request:update", "request:delete", ], ).save() yield role role.delete()
def job_manager_role(): role = Role( name="job_manager", permissions=[ "job:create", "job:read", "job:update", "job:delete", ], ).save() yield role role.delete()
def test_ensure_roles_preserves_existing_superuser(self, monkeypatch): """An existing superuser role should be left untouched by ensure_roles""" monkeypatch.setattr(beer_garden.db.mongo.util, "_sync_roles_from_role_definition_file", Mock()) superuser = Role(name="superuser", permissions=[list(Permissions)[0].value]).save() monkeypatch.setattr(Role, "save", Mock()) ensure_roles() assert Role.save.called is False assert len(superuser.reload().permissions) == 1
def data_cleanup(): """Cleanup all data between test modules to ensure each one is independent""" yield Event.drop_collection() File.drop_collection() Garden.drop_collection() Job.drop_collection() RawFile.drop_collection() Request.drop_collection() RemoteUser.drop_collection() Role.drop_collection() System.drop_collection() User.drop_collection() UserToken.drop_collection()
def user_with_role_assignments(): role = Role(name="assignedrole1", permissions=["garden:read"]).save() role_assignment = RoleAssignment(domain={ "scope": "Garden", "identifiers": { "name": "garden1" } }, role=role) user = User(username="******", role_assignments=[role_assignment]).save() yield user user.delete() role.delete()
def roles(): role1 = Role(name="role1").save() role2 = Role(name="role2").save() yield [role1, role2] role1.delete() role2.delete()
def anonymous_principal() -> BrewtilsPrincipal: """Load correct anonymous permissions This exists in a weird space. We need to set the roles attribute to a 'real' Role object so it works correctly when the REST handler goes to serialize this principal. However, we also need to set the permissions attribute to the consolidated permission list so that ``check_permission`` will be able to do a comparison without having to calculate effective permissions every time. """ # auth_config = config.get("auth") # if auth_config.enabled and auth_config.guest_login_enabled: # roles = Principal.objects.get(username="******").roles # elif auth_config.enabled: # # By default, if no guest login is available, there is no anonymous # # user, which means there are no roles. # roles = [] # else: roles = [Role(name="bg-admin", permissions=["bg-all"])] _, permissions = coalesce_permissions(roles) return BrewtilsPrincipal(username="******", roles=roles, permissions=permissions)
def test_sync_roles_deletes_roles_not_present(self, role_sync_data): """sync_roles should delete roles in the database that are are not present in the role_sync_data """ Role(name="notinsyncdata", permissions=["garden:read"]).save() sync_roles(role_sync_data) with pytest.raises(DoesNotExist): Role.objects.get(name="notinsyncdata")
def _create_superuser_role(): """Creates the superuser role if it does not already exist""" # If users already exist, assume that some setup has already occurred and # leave it be. if User.objects.count() == 0: try: Role.objects.get(name="superuser") except Role.DoesNotExist: logger.info("Creating superuser role with all permissions") all_permissions = [permission.value for permission in Permissions] Role(name="superuser", permissions=all_permissions).save()
def test_sync_roles_updates_existing_roles(self, role_sync_data): """sync_roles should update any existing Roles based on what is in the provided role_sync_data """ Role(name="testrole1", description="somethingwitty", permissions=["system:read"]).save() sync_roles(role_sync_data) role = Role.objects.get(name="testrole1") assert role.description == role_sync_data[0]["description"] assert role.permissions == role_sync_data[0]["permissions"]
def sync_roles(role_sync_data: list): """Syncs the Roles in the database with a provided role list. Args: role_sync_data: A list of dictionaries containing role data. See RoleSyncSchema for the expected format. Returns: None """ roles = RoleSyncSchema(strict=True).load(role_sync_data, many=True).data _delete_roles_not_in_list(roles) for role in roles: try: role_obj = Role.objects.get(name=role["name"]) role_obj.description = role["description"] role_obj.permissions = role["permissions"] except DoesNotExist: role_obj = Role(**role) role_obj.save()
def ensure_v2_to_v3_model_migration(): """Ensures that the Role model is flatten and Command model is an EmbeddedDocument In Version 2 and earlier the Role model allowed for nested roles. This caused recursive approach to determining Principal permissions. This is changed in Version 3 to allow for Roles to add complexity of Namespace restrictions which would not work properly with nesting. Right now if the check fails this will just drop the Roles and Principle collections. Since they'll be recreated anyway this isn't the worst, but it would be better if we could seamlessly flatten existing permissions. In version 2 and earlier the Command model was a top-level collection. This causes organization and performance issues, so in version 3 it was changed to be an embedded document of the System model. This ensures that's the case. Right now if the check fails this will just drop the Systems, Commands, and Instances collections. Since they'll be recreated anyway this isn't the worst, but it would be better if we could seamlessly move the existing commands into existing Systems. """ from beer_garden.db.mongo.models import Role, System try: if Role.objects.count() > 0: _ = Role.objects()[0] if System.objects.count() > 0: _ = System.objects()[0] except (FieldDoesNotExist, InvalidDocumentError): logger.warning( "Encountered an error loading Roles or Systems. This is most likely because " "the database is using the old (v2) style of storing in the database. " "To fix this the roles, principles, systems, instances, and commands " "collections will be dropped.") db = get_db() db.drop_collection("principal") db.drop_collection("role") db.drop_collection("command") db.drop_collection("instance") db.drop_collection("system")
def roles(self): ensure_roles() yield Role.drop_collection()
def role_for_global_scope(): role = Role(name="gardencreator", permissions=["garden:create"]).save() yield role role.delete()
def drop(): Garden.drop_collection() Role.drop_collection() System.drop_collection() User.drop_collection()