def test_change_owner() -> None: uuid = str(uuid4()) alice = User(id=1) bob = User(id=2) repository = Mock() user_service = Mock() service = StorageService( study_service=Mock(), importer_service=Mock(), exporter_service=Mock(), user_service=user_service, repository=repository, event_bus=Mock(), ) repository.get.return_value = Study(id=uuid, owner=alice) user_service.get_user.return_value = bob service.change_owner( uuid, 2, RequestParameters(JWTUser(id=1, impersonator=1, type="users"))) user_service.get_user.assert_called_once_with( 2, RequestParameters(JWTUser(id=1, impersonator=1, type="users"))) repository.save.assert_called_once_with(Study(id=uuid, owner=bob)) with pytest.raises(UserHasNotPermissionError): service.change_owner( uuid, 1, RequestParameters(JWTUser(id=1, impersonator=1, type="users")), )
def test_get_studies_uuid() -> None: bob = User(id=1, name="bob") alice = User(id=2, name="alice") a = Study(id="A", owner=bob) b = Study(id="B", owner=alice) c = Study(id="C", owner=bob) # Mock repository = Mock() repository.get_all.return_value = [a, b, c] study_service = Mock() service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) studies = service._get_study_metadatas( RequestParameters(user=JWTUser(id=1, impersonator=1, type="users"))) assert [a, c] == studies
def test_users(): engine = create_engine("sqlite:///:memory:", echo=True) session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.metadata.create_all(engine) repo = UserRepository( config=Config(security=SecurityConfig(admin_pwd="admin")), session=session, ) a = User( name="a", password=Password("a"), ) b = User(name="b", password=Password("b")) a = repo.save(a) b = repo.save(b) assert b.id c = repo.get(a.id) assert a == c assert a.password.check("a") assert b == repo.get_by_name("b") repo.delete(a.id) assert repo.get(a.id) is None
def test_authenticate(): users = Mock() users.get_by_name.return_value = User(id=0, password=Password("pwd")) users.get.return_value = User(id=0, name="linus") ldap = Mock() ldap.login.return_value = None ldap.get.return_value = None roles = Mock() roles.get_all_by_user.return_value = [ Role(type=RoleType.READER, group=Group(id="group", name="group")) ] exp = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="group", name="group", role=RoleType.READER)], ) service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=roles, ldap=ldap, event_bus=Mock(), ) assert exp == service.authenticate("dupond", "pwd") users.get_by_name.assert_called_once_with("dupond") roles.get_all_by_user.assert_called_once_with(0)
def test_user_id() -> None: service = Mock() service.get_user.return_value = User(id=1, name="user") app = create_app(service) client = app.test_client() res = client.get("/users/1", headers=create_auth_token(app)) assert res.status_code == 200 assert res.json == User(id=1, name="user").to_dict()
def test_is_himself(): jwt = JWTUser( id=1, impersonator=0, type="users", ) assert jwt.is_himself(User(id=1)) assert not JWTUser( id=0, impersonator=0, type="users", ).is_himself(User(id=1))
def _save_study( self, study: RawStudy, owner: Optional[JWTUser] = None, group_ids: List[str] = list(), content_status: StudyContentStatus = StudyContentStatus.VALID, ) -> None: if not owner: raise UserHasNotPermissionError info = self.study_service.get_study_information(study)["antares"] study.name = info["caption"] study.version = info["version"] study.author = info["author"] study.created_at = datetime.fromtimestamp(info["created"]) study.updated_at = datetime.fromtimestamp(info["lastsave"]) study.content_status = content_status if owner: study.owner = User(id=owner.impersonator) groups = [] for gid in group_ids: group = next(filter(lambda g: g.id == gid, owner.groups), None) if group is None or not group.role.is_higher_or_equals( RoleType.WRITER): raise UserHasNotPermissionError() groups.append(Group(id=group.id, name=group.name)) study.groups = groups self.repository.save(study)
def test_get_user(): user = User(id=3) users = Mock() users.get.return_value = user ldap = Mock() ldap.get.return_value = None role = Role(type=RoleType.READER, identity=user, group=Group(id="group")) roles = Mock() roles.get_all_by_user.return_value = [role] service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=roles, ldap=ldap, event_bus=Mock(), ) assert_permission( test=lambda x: service.get_user(3, x), values=[(SADMIN, True), (GADMIN, True), (USER3, True)], error=UserNotFoundError, )
def test_study_inheritance(): engine = create_engine("sqlite:///:memory:", echo=True) sess = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) user = User(id=0, name="admin") group = Group(id="my-group", name="group") Base.metadata.create_all(engine) repo = StudyMetadataRepository(session=sess) a = RawStudy( name="a", version="42", author="John Smith", created_at=datetime.now(), updated_at=datetime.now(), public_mode=PublicMode.FULL, owner=user, groups=[group], workspace=DEFAULT_WORKSPACE_NAME, path="study", content_status=StudyContentStatus.WARNING, ) repo.save(a) b = repo.get(a.id) assert isinstance(b, RawStudy) assert b.path == "study"
def test_sync_studies_from_disk() -> None: ma = RawStudy(id="a", path="a") fa = StudyFolder(path=Path("a"), workspace="", groups=[]) mb = RawStudy(id="b", path="b") mc = RawStudy( id="c", path="c", name="c", content_status=StudyContentStatus.WARNING, workspace=DEFAULT_WORKSPACE_NAME, owner=User(id=0), ) fc = StudyFolder(path=Path("c"), workspace=DEFAULT_WORKSPACE_NAME, groups=[]) repository = Mock() repository.get_all.side_effect = [[ma, mb], [ma]] service = StorageService( study_service=Mock(), importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) service.sync_studies_on_disk([fa, fc]) repository.delete.assert_called_once_with(mb.id) repository.save.assert_called_once()
def create_user(self, create: UserCreateDTO, param: RequestParameters) -> Identity: if param.user and param.user.is_site_admin(): if self.users.get_by_name(create.name): raise UserAlreadyExistError() return self.users.save( User(name=create.name, password=Password(create.password))) else: raise UserHasNotPermissionError()
def __init__(self, session: Session): self.session = session if self.get(1, "admin") is None: self.save( Role( type=RoleType.ADMIN, identity=User(id=1), group=Group(id="admin"), ))
def test_save_metadata() -> None: # Mock repository = Mock() uuid = str(uuid4()) study_service = Mock() study_service.get_study_information.return_value = { "antares": { "caption": "CAPTION", "version": "VERSION", "author": "AUTHOR", "created": 1234, "lastsave": 9876, } } # Input jwt = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="my-group", name="group", role=RoleType.ADMIN)], ) user = User(id=0, name="user") group = Group(id="my-group", name="group") # Expected study = RawStudy( id=uuid, name="CAPTION", version="VERSION", author="AUTHOR", created_at=datetime.fromtimestamp(1234), updated_at=datetime.fromtimestamp(9876), content_status=StudyContentStatus.VALID, workspace=DEFAULT_WORKSPACE_NAME, owner=user, groups=[group], ) service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) service._save_study( RawStudy(id=uuid, workspace=DEFAULT_WORKSPACE_NAME), owner=jwt, ) repository.save.assert_called_once_with(study)
def delete_user(self, id: int, params: RequestParameters) -> None: if params.user and any( (params.user.is_site_admin(), params.user.is_himself( User(id=id)))): for b in self.bots.get_all_by_owner(id): self.delete_bot(b.id, params) self.ldap.delete(id) return self.users.delete(id) # return for test purpose else: raise UserHasNotPermissionError()
def test_create_user(): create = UserCreateDTO(name="hello", password="******") ldap = Mock() ldap.save.return_value = None users = Mock() users.save.return_value = User(id=3, name="hello") users.get_by_name.return_value = None service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=Mock(), ldap=ldap, event_bus=Mock(), ) service.create_user(create, param=SADMIN) users.save.assert_called_once_with( User(name="hello", password=Password("world")) )
def test_expiration() -> None: service = Mock() service.get_user.return_value = User(id=0, name="admin") app = create_app(service) client = app.test_client() res = client.post( "/users", headers=create_auth_token(app, expires_delta=timedelta(days=-1)), ) assert res.status_code == 401 data = res.json assert data["msg"] == "Token has expired"
def test_role() -> None: role = Role( identity=User(id=0, name="n"), group=Group(id="g", name="n"), type=RoleType.ADMIN, ) service = Mock() service.get_all_roles_in_group.return_value = [role] app = create_app(service) client = app.test_client() res = client.get("/roles/group/g", headers=create_auth_token(app)) assert res.status_code == 200 assert res.json == [role.to_dict()]
def test_user_save() -> None: user = User(id=0, name="a", password=Password("b")) service = Mock() service.save_user.return_value = user app = create_app(service) client = app.test_client() res = client.put( "/users/0", headers=create_auth_token(app), json=user.to_dict(), ) assert res.status_code == 200 service.save_user.assert_called_once_with(user, PARAMS) assert res.json == user.to_dict()
def test_auth() -> None: service = Mock() service.authenticate.return_value = User(id=0, name="admin") app = create_app(service) client = app.test_client() res = client.post("/login", json={ "username": "******", "password": "******" }) assert res.status_code == 200 assert res.json["access_token"] service.authenticate.assert_called_once_with("admin", "admin")
def __init__(self, config: Config, session: Session) -> None: self.session = session # init seed admin user from conf admin_user = self.get_by_name("admin") if admin_user is None: self.save( User( id=1, name="admin", password=Password(config.security.admin_pwd), )) elif not admin_user.password.check( config.security.admin_pwd): # type: ignore admin_user.password = Password( config.security.admin_pwd) # type: ignore self.save(admin_user)
def test_refresh() -> None: service = Mock() service.get_jwt.return_value = User(id=0, name="admin") app = create_app(service) client = app.test_client() res = client.post( "/refresh", headers=create_auth_token(app, type=TokenType.REFRESH), ) assert res.status_code == 200 data = res.json meta, b64, sign = str(data["access_token"]).split(".") data = b64 + "===" # fix padding issue identity = json.loads(base64.b64decode(data))["sub"]
def test_save_user(): user = User(id=3) users = Mock() users.save.return_value = user service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=Mock(), ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.save_user(user, x), values=[(SADMIN, True), (GADMIN, False), (USER3, True)], )
def test_roles(): engine = create_engine("sqlite:///:memory:", echo=True) session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.metadata.create_all(engine) repo = RoleRepository(session=session) a = Role(type=RoleType.ADMIN, identity=User(id=0), group=Group(id="group")) a = repo.save(a) assert a == repo.get(user=0, group="group") assert [a] == repo.get_all_by_user(user=0) assert [a] == repo.get_all_by_group(group="group") repo.delete(user=0, group="group") assert repo.get(user=0, group="group") is None
def test_get_all_users(): users = Mock() users.get_all.return_value = [User(id=0, name="alice")] ldap = Mock() ldap.get_all.return_value = [] service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=Mock(), ldap=ldap, event_bus=Mock(), ) assert_permission( test=lambda x: service.get_all_users(x), values=[(SADMIN, True), (GADMIN, False), (USER3, False)], )
def test_cyclelife(): engine = create_engine("sqlite:///:memory:", echo=True) sess = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) user = User(id=0, name="admin") group = Group(id="my-group", name="group") Base.metadata.create_all(engine) repo = StudyMetadataRepository(session=sess) a = Study( name="a", version="42", author="John Smith", created_at=datetime.now(), updated_at=datetime.now(), public_mode=PublicMode.FULL, owner=user, groups=[group], ) b = Study( name="b", version="43", author="Morpheus", created_at=datetime.now(), updated_at=datetime.now(), public_mode=PublicMode.FULL, owner=user, groups=[group], ) a = repo.save(a) b = repo.save(b) assert b.id c = repo.get(a.id) assert a == c repo.delete(a.id) assert repo.get(a.id) is None
def test_role_create() -> None: role = Role( identity=User(id=0, name="n"), group=Group(id="g", name="n"), type=RoleType.ADMIN, ) service = Mock() service.save_role.return_value = role app = create_app(service) client = app.test_client() res = client.post( "/roles", headers=create_auth_token(app), json={ "type": RoleType.ADMIN.value, "identity_id": 0, "group_id": "g" }, ) assert res.status_code == 200 assert res.json == role.to_dict()
def test_delete_user(): users = Mock() users.delete.return_value = User() bots = Mock() bots.get_all_by_owner.return_value = [Bot(id=4, owner=3)] bots.get.return_value = Bot(id=4, owner=3) service = LoginService( user_repo=users, bot_repo=bots, group_repo=Mock(), role_repo=Mock(), ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.delete_user(3, x), values=[(SADMIN, True), (GADMIN, False), (USER3, True)], ) users.delete.assert_called_with(3) bots.delete.assert_called_with(4)
def test_save_role(): role = RoleCreationDTO( type=RoleType.ADMIN, identity_id=0, group_id="group" ) users = Mock() users.get.return_value = User(id=0, name="admin") groups = Mock() groups.get.return_value = Group(id="group", name="some group") roles = Mock() roles.save.return_value = role service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=groups, role_repo=roles, ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.save_role(role, x), values=[(SADMIN, True), (GADMIN, True), (USER3, False)], )
def test_assert_permission() -> None: uuid = str(uuid4()) admin_group = JWTGroup(id="admin", name="admin", role=RoleType.ADMIN) admin = JWTUser(id=1, impersonator=1, type="users", groups=[admin_group]) group = JWTGroup(id="my-group", name="g", role=RoleType.ADMIN) jwt = JWTUser(id=0, impersonator=0, type="users", groups=[group]) group_2 = JWTGroup(id="my-group-2", name="g2", role=RoleType.RUNNER) jwt_2 = JWTUser(id=3, impersonator=3, type="users", groups=[group_2]) good = User(id=0) wrong = User(id=2) repository = Mock() service = StorageService( study_service=Mock(), importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) # wrong owner repository.get.return_value = Study(id=uuid, owner=wrong) study = service._get_study(uuid) with pytest.raises(UserHasNotPermissionError): service._assert_permission(jwt, study, StudyPermissionType.READ) assert not service._assert_permission( jwt, study, StudyPermissionType.READ, raising=False) # good owner study = Study(id=uuid, owner=good) assert service._assert_permission(jwt, study, StudyPermissionType.MANAGE_PERMISSIONS) # wrong group study = Study(id=uuid, owner=wrong, groups=[Group(id="wrong")]) with pytest.raises(UserHasNotPermissionError): service._assert_permission(jwt, study, StudyPermissionType.READ) assert not service._assert_permission( jwt, study, StudyPermissionType.READ, raising=False) # good group study = Study(id=uuid, owner=wrong, groups=[Group(id="my-group")]) assert service._assert_permission(jwt, study, StudyPermissionType.MANAGE_PERMISSIONS) # super admin can do whatever he wants.. study = Study(id=uuid) assert service._assert_permission(admin, study, StudyPermissionType.MANAGE_PERMISSIONS) # when study found in workspace without group study = Study(id=uuid, public_mode=PublicMode.FULL) assert not service._assert_permission( jwt, study, StudyPermissionType.MANAGE_PERMISSIONS, raising=False) assert service._assert_permission(jwt, study, StudyPermissionType.DELETE) assert service._assert_permission(jwt, study, StudyPermissionType.READ) assert service._assert_permission(jwt, study, StudyPermissionType.WRITE) assert service._assert_permission(jwt, study, StudyPermissionType.RUN) # some group roles study = Study(id=uuid, owner=wrong, groups=[Group(id="my-group-2")]) assert not service._assert_permission( jwt_2, study, StudyPermissionType.WRITE, raising=False) assert service._assert_permission(jwt_2, study, StudyPermissionType.READ)
def test_create_study() -> None: # Mock repository = Mock() # Input user = User(id=0, name="user") group = Group(id="my-group", name="group") expected = RawStudy( id=str(uuid4()), name="new-study", version="VERSION", author="AUTHOR", created_at=datetime.fromtimestamp(1234), updated_at=datetime.fromtimestamp(9876), content_status=StudyContentStatus.VALID, workspace=DEFAULT_WORKSPACE_NAME, owner=user, groups=[group], ) study_service = Mock() study_service.get_default_workspace_path.return_value = Path("") study_service.get_study_information.return_value = { "antares": { "caption": "CAPTION", "version": "VERSION", "author": "AUTHOR", "created": 1234, "lastsave": 9876, } } study_service.create_study.return_value = expected service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) with pytest.raises(UserHasNotPermissionError): service.create_study( "new-study", ["my-group"], RequestParameters(JWTUser(id=0, impersonator=0, type="users")), ) service.create_study( "new-study", ["my-group"], RequestParameters( JWTUser( id=0, impersonator=0, type="users", groups=[ JWTGroup(id="my-group", name="group", role=RoleType.WRITER) ], )), ) study_service.create_study.assert_called() repository.save.assert_called_once_with(expected)