@Nullable
private Boolean local;
- @Nullable
- private Boolean root;
-
@Nullable
private Long lastConnectionDate;
this.externalLogin = userDto.getExternalLogin();
this.externalIdentityProvider = userDto.getExternalIdentityProvider();
this.local = userDto.isLocal();
- this.root = userDto.isRoot();
this.lastConnectionDate = userDto.getLastConnectionDate();
}
return this.local;
}
- @CheckForNull
- public Boolean isRoot() {
- return this.root;
- }
-
@CheckForNull
public Long getLastConnectionDate() {
return this.lastConnectionDate;
addField(sb, "\"externalLogin\": ", this.externalLogin, true);
addField(sb, "\"externalIdentityProvider\": ", this.externalIdentityProvider, true);
addField(sb, "\"local\": ", ObjectUtils.toString(this.local), false);
- addField(sb, "\"root\": ", ObjectUtils.toString(this.root), false);
addField(sb, "\"lastConnectionDate\": ", this.lastConnectionDate == null ?
"" : DateUtils.formatDateTime(this.lastConnectionDate), true);
endString(sb);
return mapper(dbSession).selectUsers(query);
}
- public long countRootUsersButLogin(DbSession dbSession, String login) {
- return mapper(dbSession).countRootUsersButLogin(login);
- }
-
public UserDto insert(DbSession session, UserDto dto) {
long now = system2.now();
mapper(session).insert(dto.setUuid(uuidFactory.create()).setCreatedAt(now).setUpdatedAt(now));
mapper(session).dismissSonarlintAd(login);
}
- public void setRoot(DbSession session, String login, boolean root) {
- mapper(session).setRoot(login, root, system2.now());
- }
-
public void deactivateUser(DbSession dbSession, UserDto user) {
mapper(dbSession).deactivateUser(user.getLogin(), system2.now());
auditPersister.deactivateUser(dbSession, new UserNewValue(user.getUuid(), user.getLogin()));
private String homepageType;
private String homepageParameter;
private boolean local = true;
- private boolean root = false;
private boolean resetPassword = false;
private boolean sonarlintAdSeen = false;
return this;
}
- public boolean isRoot() {
- return root;
- }
-
- /**
- * Setters is not accessible as MyBatis doesn't need setter to set the field and dedicated SQL requests must be used
- * to update the root flag of a user:
- * <ul>
- * <li>a user can not be created root</li>
- * <li>the generic update method of a user can not change its root flag</li>
- * </ul>
- */
- protected void setRoot(boolean root) {
- this.root = root;
- }
-
public boolean isResetPassword() {
return resetPassword;
}
void updateSonarlintLastConnectionDate(@Param("login") String login, @Param("now") long now);
- /**
- * Count actives users which are root and which login is not the specified one.
- */
- long countRootUsersButLogin(@Param("login") String login);
-
void insert(@Param("user") UserDto userDto);
void update(@Param("user") UserDto userDto);
- void setRoot(@Param("login") String login, @Param("root") boolean root, @Param("now") long now);
-
void deactivateUser(@Param("login") String login, @Param("now") long now);
void clearHomepages(@Param("homepageType") String type, @Param("homepageParameter") String value, @Param("now") long now);
u.external_login as "externalLogin",
u.external_identity_provider as "externalIdentityProvider",
u.user_local as "local",
- u.is_root as "root",
u.reset_password as "resetPassword",
u.homepage_type as "homepageType",
u.homepage_parameter as "homepageParameter",
<if test="searchText != null">
AND (u.login LIKE #{searchTextSql, jdbcType=VARCHAR} ESCAPE '/' OR u.name LIKE #{searchTextSql, jdbcType=VARCHAR} ESCAPE '/')
</if>
- <if test="mustBeRoot != null and mustBeRoot==true">
- AND u.is_root = ${_true}
- </if>
- <if test="mustBeRoot != null and mustBeRoot==false">
- AND u.is_root = ${_false}
- </if>
</where>
ORDER BY u.name
</select>
WHERE u.external_login=#{externalLogin, jdbcType=VARCHAR} AND u.external_identity_provider=#{externalIdentityProvider, jdbcType=VARCHAR}
</select>
- <select id="countRootUsersButLogin" parameterType="String" resultType="long">
- select
- count(1)
- from
- users u
- where
- u.active = ${_true}
- and u.is_root = ${_true}
- and u.login <> #{login}
- </select>
-
<sql id="deactivateUserUpdatedFields">
active = ${_false},
email = null,
login = #{login, jdbcType=VARCHAR}
</update>
- <update id="setRoot">
- update users set
- is_root = #{root, jdbcType=BOOLEAN},
- updated_at = #{now, jdbcType=BIGINT}
- where
- login = #{login, jdbcType=VARCHAR}
- and active = ${_true}
- </update>
-
<insert id="insert" parameterType="map" useGeneratedKeys="false">
insert into users (
uuid,
salt,
crypted_password,
hash_method,
- is_root,
last_sonarlint_connection,
sonarlint_ad_seen,
reset_password,
#{user.salt,jdbcType=VARCHAR},
#{user.cryptedPassword,jdbcType=VARCHAR},
#{user.hashMethod,jdbcType=VARCHAR},
- #{user.root,jdbcType=BOOLEAN},
#{user.lastSonarlintConnectionDate,jdbcType=BIGINT},
#{user.sonarlintAdSeen,jdbcType=BOOLEAN},
#{user.resetPassword,jdbcType=BOOLEAN},
"EXTERNAL_LOGIN" CHARACTER VARYING(255) NOT NULL,
"EXTERNAL_IDENTITY_PROVIDER" CHARACTER VARYING(100) NOT NULL,
"EXTERNAL_ID" CHARACTER VARYING(255) NOT NULL,
- "IS_ROOT" BOOLEAN NOT NULL,
"USER_LOCAL" BOOLEAN,
"HOMEPAGE_TYPE" CHARACTER VARYING(40),
"HOMEPAGE_PARAMETER" CHARACTER VARYING(40),
assertThat(users).isEmpty();
}
- @Test
- public void selectUsers_returns_both_only_root_or_only_non_root_depending_on_mustBeRoot_and_mustNotBeRoot_calls_on_query() {
- UserDto user1 = insertUser(true);
- UserDto root1 = insertRootUser(newUserDto());
- UserDto user2 = insertUser(true);
- UserDto root2 = insertRootUser(newUserDto());
-
- assertThat(underTest.selectUsers(session, UserQuery.builder().build()))
- .extracting(UserDto::getLogin)
- .containsOnly(user1.getLogin(), user2.getLogin(), root1.getLogin(), root2.getLogin());
- assertThat(underTest.selectUsers(session, UserQuery.builder().mustBeRoot().build()))
- .extracting(UserDto::getLogin)
- .containsOnly(root1.getLogin(), root2.getLogin());
- assertThat(underTest.selectUsers(session, UserQuery.builder().mustNotBeRoot().build()))
- .extracting(UserDto::getLogin)
- .containsOnly(user1.getLogin(), user2.getLogin());
- }
-
- @Test
- public void countRootUsersButLogin_returns_0_when_there_is_no_user_at_all() {
- assertThat(underTest.countRootUsersButLogin(session, "bla")).isZero();
- }
-
- @Test
- public void countRootUsersButLogin_returns_0_when_there_is_no_root() {
- underTest.insert(session, newUserDto());
- session.commit();
-
- assertThat(underTest.countRootUsersButLogin(session, "bla")).isZero();
- }
-
- @Test
- public void countRootUsersButLogin_returns_0_when_there_is_no_active_root() {
- insertNonRootUser(newUserDto());
- insertInactiveRootUser(newUserDto());
- session.commit();
-
- assertThat(underTest.countRootUsersButLogin(session, "bla")).isZero();
- }
-
- @Test
- public void countRootUsersButLogin_returns_count_of_all_active_roots_when_there_specified_login_does_not_exist() {
- insertRootUser(newUserDto());
- insertNonRootUser(newUserDto());
- insertRootUser(newUserDto());
- insertRootUser(newUserDto());
- insertInactiveRootUser(newUserDto());
- insertInactiveRootUser(newUserDto());
- session.commit();
-
- assertThat(underTest.countRootUsersButLogin(session, "bla")).isEqualTo(3);
- }
-
- @Test
- public void countRootUsersButLogin_returns_count_of_all_active_roots_when_specified_login_is_not_root() {
- insertRootUser(newUserDto());
- String login = insertNonRootUser(newUserDto()).getLogin();
- insertRootUser(newUserDto());
- insertRootUser(newUserDto());
- insertInactiveRootUser(newUserDto());
- insertInactiveRootUser(newUserDto());
- session.commit();
-
- assertThat(underTest.countRootUsersButLogin(session, login)).isEqualTo(3);
- }
-
- @Test
- public void countRootUsersButLogin_returns_count_of_all_active_roots_when_specified_login_is_inactive_root() {
- insertRootUser(newUserDto());
- insertNonRootUser(newUserDto());
- insertRootUser(newUserDto());
- insertRootUser(newUserDto());
- String inactiveRootLogin = insertInactiveRootUser(newUserDto()).getLogin();
- insertInactiveRootUser(newUserDto());
- session.commit();
-
- assertThat(underTest.countRootUsersButLogin(session, inactiveRootLogin)).isEqualTo(3);
- }
-
- @Test
- public void countRootUsersButLogin_returns_count_of_all_active_roots_minus_one_when_specified_login_is_active_root() {
- insertRootUser(newUserDto());
- insertNonRootUser(newUserDto());
- insertRootUser(newUserDto());
- String rootLogin = insertRootUser(newUserDto()).getLogin();
- insertInactiveRootUser(newUserDto());
- insertInactiveRootUser(newUserDto());
- session.commit();
-
- assertThat(underTest.countRootUsersButLogin(session, rootLogin)).isEqualTo(2);
- }
-
- private UserDto insertInactiveRootUser(UserDto dto) {
- insertRootUser(dto);
- dto.setActive(false);
- underTest.update(session, dto);
- session.commit();
- return dto;
- }
-
- private UserDto insertRootUser(UserDto dto) {
- underTest.insert(session, dto);
- underTest.setRoot(session, dto.getLogin(), true);
- session.commit();
- return dto;
- }
-
- private UserDto insertNonRootUser(UserDto dto) {
- underTest.insert(session, dto);
- session.commit();
- return dto;
- }
@Test
public void insert_user_with_default_values() {
assertThat(user.isActive()).isTrue();
assertThat(user.isResetPassword()).isFalse();
assertThat(user.isLocal()).isTrue();
- assertThat(user.isRoot()).isFalse();
assertThat(user.getScmAccountsAsList()).isEmpty();
assertThat(user.getScmAccounts()).isNull();
assertThat(user.getExternalIdentityProvider()).isEqualTo("github");
assertThat(user.getExternalId()).isEqualTo("EXT_ID");
assertThat(user.isLocal()).isTrue();
- assertThat(user.isRoot()).isFalse();
assertThat(user.getHomepageType()).isEqualTo("project");
assertThat(user.getHomepageParameter()).isEqualTo("OB1");
}
assertThat(reloaded.getExternalIdentityProvider()).isEqualTo("github");
assertThat(reloaded.getExternalId()).isEqualTo("EXT_ID");
assertThat(reloaded.isLocal()).isFalse();
- assertThat(reloaded.isRoot()).isFalse();
assertThat(reloaded.getHomepageType()).isEqualTo("project");
assertThat(reloaded.getHomepageParameter()).isEqualTo("OB1");
assertThat(reloaded.getLastConnectionDate()).isEqualTo(10_000_000_000L);
assertThat(userReloaded.getScmAccounts()).isNull();
assertThat(userReloaded.getSalt()).isNull();
assertThat(userReloaded.getCryptedPassword()).isNull();
- assertThat(userReloaded.isRoot()).isFalse();
assertThat(userReloaded.getUpdatedAt()).isEqualTo(NOW);
assertThat(userReloaded.getHomepageType()).isNull();
assertThat(userReloaded.getHomepageParameter()).isNull();
.setCryptedPassword("650d2261c98361e2f67f90ce5c65a95e7d8ea2fg")
.setHomepageType("project")
.setHomepageParameter("OB1"));
- UserDto user2 = db.users().insertUser();
- underTest.setRoot(session, user2.getLogin(), true);
UserDto dto = underTest.selectByLogin(session, user1.getLogin());
assertThat(dto.getUuid()).isEqualTo(user1.getUuid());
assertThat(dto.getScmAccountsAsList()).containsOnly("ma", "marius33");
assertThat(dto.getSalt()).isEqualTo("79bd6a8e79fb8c76ac8b121cc7e8e11ad1af8365");
assertThat(dto.getCryptedPassword()).isEqualTo("650d2261c98361e2f67f90ce5c65a95e7d8ea2fg");
- assertThat(dto.isRoot()).isFalse();
assertThat(dto.getCreatedAt()).isEqualTo(user1.getCreatedAt());
assertThat(dto.getUpdatedAt()).isEqualTo(user1.getUpdatedAt());
assertThat(dto.getHomepageType()).isEqualTo("project");
assertThat(dto.getHomepageParameter()).isEqualTo("OB1");
- dto = underTest.selectByLogin(session, user2.getLogin());
- assertThat(dto.isRoot()).isTrue();
}
@Test
assertThat(underTest.selectByExternalLoginAndIdentityProvider(session, "unknown", "unknown")).isNull();
}
- @Test
- public void setRoot_does_not_fail_on_non_existing_login() {
- underTest.setRoot(session, "unkown", true);
- underTest.setRoot(session, "unkown", false);
- }
-
- @Test
- public void setRoot_set_root_flag_of_specified_user_to_specified_value_and_updates_udpateAt() {
- String login = insertActiveUser().getLogin();
- UserDto otherUser = insertActiveUser();
- assertThat(underTest.selectByLogin(session, login).isRoot()).isFalse();
- assertThat(underTest.selectByLogin(session, otherUser.getLogin()).isRoot()).isFalse();
-
- // does not fail when changing to same value
- system2.setNow(15_000L);
- commit(() -> underTest.setRoot(session, login, false));
- verifyRootAndUpdatedAt(login, false, 15_000L);
- verifyRootAndUpdatedAt(otherUser.getLogin(), false, otherUser.getUpdatedAt());
-
- // change value
- system2.setNow(26_000L);
- commit(() -> underTest.setRoot(session, login, true));
- verifyRootAndUpdatedAt(login, true, 26_000L);
- verifyRootAndUpdatedAt(otherUser.getLogin(), false, otherUser.getUpdatedAt());
-
- // does not fail when changing to same value
- system2.setNow(37_000L);
- commit(() -> underTest.setRoot(session, login, true));
- verifyRootAndUpdatedAt(login, true, 37_000L);
- verifyRootAndUpdatedAt(otherUser.getLogin(), false, otherUser.getUpdatedAt());
-
- // change value back
- system2.setNow(48_000L);
- commit(() -> underTest.setRoot(session, login, false));
- verifyRootAndUpdatedAt(login, false, 48_000L);
- verifyRootAndUpdatedAt(otherUser.getLogin(), false, otherUser.getUpdatedAt());
- }
-
- private void verifyRootAndUpdatedAt(String login1, boolean root, long updatedAt) {
- UserDto userDto = underTest.selectByLogin(session, login1);
- assertThat(userDto.isRoot()).isEqualTo(root);
- assertThat(userDto.getUpdatedAt()).isEqualTo(updatedAt);
- }
-
- @Test
- public void setRoot_has_no_effect_on_root_flag_of_inactive_user() {
- String nonRootInactiveUser = insertUser(false).getLogin();
- commit(() -> underTest.setRoot(session, nonRootInactiveUser, true));
- assertThat(underTest.selectByLogin(session, nonRootInactiveUser).isRoot()).isFalse();
-
- // create inactive root user
- UserDto rootUser = insertActiveUser();
- commit(() -> underTest.setRoot(session, rootUser.getLogin(), true));
- rootUser.setActive(false);
- commit(() -> underTest.update(session, rootUser));
- UserDto inactiveRootUser = underTest.selectByLogin(session, rootUser.getLogin());
- assertThat(inactiveRootUser.isRoot()).isTrue();
- assertThat(inactiveRootUser.isActive()).isFalse();
-
- commit(() -> underTest.setRoot(session, inactiveRootUser.getLogin(), false));
- assertThat(underTest.selectByLogin(session, inactiveRootUser.getLogin()).isRoot()).isTrue();
- }
-
@Test
public void scrollByLUuids() {
UserDto u1 = insertUser(true);
assertThat(newValue)
.extracting(UserNewValue::getUserUuid, UserNewValue::getUserLogin, UserNewValue::getName, UserNewValue::getEmail, UserNewValue::isActive,
UserNewValue::getScmAccounts, UserNewValue::getExternalId, UserNewValue::getExternalLogin, UserNewValue::getExternalIdentityProvider,
- UserNewValue::isLocal, UserNewValue::isRoot, UserNewValue::getLastConnectionDate)
+ UserNewValue::isLocal, UserNewValue::getLastConnectionDate)
.containsExactly(updatedUser.getUuid(), updatedUser.getLogin(), updatedUser.getName(), updatedUser.getEmail(), updatedUser.isActive(),
updatedUser.getScmAccounts(), updatedUser.getExternalId(), updatedUser.getExternalLogin(), updatedUser.getExternalIdentityProvider(),
- updatedUser.isLocal(), updatedUser.isRoot(), updatedUser.getLastConnectionDate());
+ updatedUser.isLocal(), updatedUser.getLastConnectionDate());
assertThat(newValue.toString())
.contains("name")
.contains(DateUtils.formatDateTime(updatedUser.getLastConnectionDate()));
import org.sonar.db.qualityprofile.QualityProfileDbTester;
import org.sonar.db.rule.RuleDbTester;
import org.sonar.db.source.FileSourceTester;
-import org.sonar.db.user.RootFlagAssertions;
import org.sonar.db.user.UserDbTester;
import org.sonar.db.webhook.WebhookDbTester;
import org.sonar.db.webhook.WebhookDeliveryDbTester;
private final RuleDbTester ruleDbTester;
private final NewCodePeriodDbTester newCodePeriodTester;
private final NotificationDbTester notificationDbTester;
- private final RootFlagAssertions rootFlagAssertions;
private final QualityProfileDbTester qualityProfileDbTester;
private final MeasureDbTester measureDbTester;
private final FileSourceTester fileSourceTester;
this.issueDbTester = new IssueDbTester(this);
this.ruleDbTester = new RuleDbTester(this);
this.notificationDbTester = new NotificationDbTester(this);
- this.rootFlagAssertions = new RootFlagAssertions(this);
this.qualityProfileDbTester = new QualityProfileDbTester(this);
this.measureDbTester = new MeasureDbTester(this);
this.fileSourceTester = new FileSourceTester(this);
return qualityGateDbTester;
}
- public RootFlagAssertions rootFlag() {
- return rootFlagAssertions;
- }
-
public IssueDbTester issues() {
return issueDbTester;
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.db.user;
-
-import java.util.Map;
-import org.sonar.db.DbTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class RootFlagAssertions {
- private final DbTester db;
-
- public RootFlagAssertions(DbTester db) {
- this.db = db;
- }
-
- public void verify(UserDto userDto, boolean root, long updatedAt) {
- Map<String, Object> row = db.selectFirst("select is_root as \"isRoot\", updated_at as \"updatedAt\" from users where login = '" + userDto.getLogin() + "'");
- Object isRoot = row.get("isRoot");
- assertThat(isRoot)
- .as("Root flag of user '%s' is same as when created", userDto.getLogin())
- .isEqualTo(isRoot instanceof Long ? toLong(root) : root);
- assertThat(row.get("updatedAt"))
- .as("UpdatedAt of user '%s' has not changed since created")
- .isEqualTo(updatedAt);
- }
-
- public void verify(UserDto userDto, boolean root) {
- Map<String, Object> row = db.selectFirst("select is_root as \"isRoot\", updated_at as \"updatedAt\" from users where login = '" + userDto.getLogin() + "'");
- Object isRoot = row.get("isRoot");
- assertThat(isRoot)
- .as("Root flag of user '%s' is '%s'", userDto.getLogin(), root)
- .isEqualTo(isRoot instanceof Long ? toLong(root) : root);
- assertThat(row.get("updatedAt"))
- .as("UpdatedAt of user '%s' has changed since insertion", userDto.getLogin())
- .isNotEqualTo(userDto.getUpdatedAt());
- }
-
- private static Long toLong(boolean root) {
- return root ? 1L : 0L;
- }
-
- public void verify(String login, boolean root) {
- assertThat(db.getDbClient().userDao().selectByLogin(db.getSession(), login).isRoot())
- .as("Root flag of user '%s' is '%s'", login, root)
- .isEqualTo(root);
- }
-}
return updatedUser;
}
- public UserDto makeRoot(UserDto userDto) {
- dbClient.userDao().setRoot(db.getSession(), userDto.getLogin(), true);
- db.commit();
- return dbClient.userDao().selectByLogin(db.getSession(), userDto.getLogin());
- }
-
public UserDto insertAdminByUserPermission() {
UserDto user = insertUser();
insertPermissionOnUser(user, ADMINISTER);
import org.sonar.server.platform.db.migration.version.v93.DbVersion93;
import org.sonar.server.platform.db.migration.version.v94.DbVersion94;
import org.sonar.server.platform.db.migration.version.v95.DbVersion95;
+import org.sonar.server.platform.db.migration.version.v96.DbVersion96;
public class MigrationConfigurationModule extends Module {
@Override
DbVersion93.class,
DbVersion94.class,
DbVersion95.class,
+ DbVersion96.class,
// migration steps
MigrationStepRegistryImpl.class,
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.platform.db.migration.version.v96;
+
+import org.sonar.server.platform.db.migration.step.MigrationStepRegistry;
+import org.sonar.server.platform.db.migration.version.DbVersion;
+
+public class DbVersion96 implements DbVersion {
+
+ @Override
+ public void addSteps(MigrationStepRegistry registry) {
+ registry
+ .add(6500, "remove root column from users table", DropRootColumnFromUsersTable.class)
+ ;
+ }
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.platform.db.migration.version.v96;
+
+import org.sonar.db.Database;
+import org.sonar.server.platform.db.migration.step.DropColumnChange;
+
+public class DropRootColumnFromUsersTable extends DropColumnChange {
+
+ public static final String TABLE_NAME = "users";
+ public static final String COLUMN_NAME = "is_root";
+
+ public DropRootColumnFromUsersTable(Database db) {
+ super(db, TABLE_NAME, COLUMN_NAME);
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.platform.db.migration.version.v96;
+
+import org.junit.Test;
+
+import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMigrationNotEmpty;
+import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMinimumMigrationNumber;
+
+public class DbVersion96Test {
+
+
+ private final DbVersion96 underTest = new DbVersion96();
+
+ @Test
+ public void migrationNumber_starts_at_6401() {
+ verifyMinimumMigrationNumber(underTest, 6500);
+ }
+
+ @Test
+ public void verify_migration_count() {
+ verifyMigrationNotEmpty(underTest);
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.platform.db.migration.version.v96;
+
+import java.sql.SQLException;
+import java.sql.Types;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.db.CoreDbTester;
+import org.sonar.server.platform.db.migration.step.DdlChange;
+
+public class DropRootColumnFromUsersTableTest {
+
+ private static final String COLUMN_NAME = "is_root";
+ private static final String TABLE_NAME = "users";
+
+ @Rule
+ public final CoreDbTester db = CoreDbTester.createForSchema(DropRootColumnFromUsersTableTest.class, "schema.sql");
+
+ private final DdlChange dropRuleDescriptionColumn = new DropRootColumnFromUsersTable(db.database());
+
+ @Test
+ public void migration_should_drop_is_root_column() throws SQLException {
+ db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.BOOLEAN, null, false);
+ dropRuleDescriptionColumn.execute();
+ db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
+ }
+
+ @Test
+ public void migration_should_be_reentrant() throws SQLException {
+ db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.BOOLEAN, null, false);
+ dropRuleDescriptionColumn.execute();
+ // re-entrant
+ dropRuleDescriptionColumn.execute();
+ db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
+ }
+}
\ No newline at end of file
--- /dev/null
+CREATE TABLE "USERS"(
+ "UUID" CHARACTER VARYING(255) NOT NULL,
+ "LOGIN" CHARACTER VARYING(255) NOT NULL,
+ "NAME" CHARACTER VARYING(200),
+ "EMAIL" CHARACTER VARYING(100),
+ "CRYPTED_PASSWORD" CHARACTER VARYING(100),
+ "SALT" CHARACTER VARYING(40),
+ "HASH_METHOD" CHARACTER VARYING(10),
+ "ACTIVE" BOOLEAN DEFAULT TRUE,
+ "SCM_ACCOUNTS" CHARACTER VARYING(4000),
+ "EXTERNAL_LOGIN" CHARACTER VARYING(255) NOT NULL,
+ "EXTERNAL_IDENTITY_PROVIDER" CHARACTER VARYING(100) NOT NULL,
+ "EXTERNAL_ID" CHARACTER VARYING(255) NOT NULL,
+ "IS_ROOT" BOOLEAN NOT NULL,
+ "USER_LOCAL" BOOLEAN,
+ "HOMEPAGE_TYPE" CHARACTER VARYING(40),
+ "HOMEPAGE_PARAMETER" CHARACTER VARYING(40),
+ "LAST_CONNECTION_DATE" BIGINT,
+ "CREATED_AT" BIGINT,
+ "UPDATED_AT" BIGINT,
+ "RESET_PASSWORD" BOOLEAN NOT NULL,
+ "LAST_SONARLINT_CONNECTION" BIGINT,
+ "SONARLINT_AD_SEEN" BOOLEAN DEFAULT FALSE
+);
+ALTER TABLE "USERS" ADD CONSTRAINT "PK_USERS" PRIMARY KEY("UUID");
+CREATE UNIQUE INDEX "USERS_LOGIN" ON "USERS"("LOGIN" NULLS FIRST);
+CREATE INDEX "USERS_UPDATED_AT" ON "USERS"("UPDATED_AT" NULLS FIRST);
+CREATE UNIQUE INDEX "UNIQ_EXTERNAL_ID" ON "USERS"("EXTERNAL_IDENTITY_PROVIDER" NULLS FIRST, "EXTERNAL_ID" NULLS FIRST);
+CREATE UNIQUE INDEX "UNIQ_EXTERNAL_LOGIN" ON "USERS"("EXTERNAL_IDENTITY_PROVIDER" NULLS FIRST, "EXTERNAL_LOGIN" NULLS FIRST);
return false;
}
- @Override
- public boolean isRoot() {
- return false;
- }
-
@Override
public boolean isSystemAdministrator() {
return false;
@Override
public final boolean hasPermission(GlobalPermission permission) {
- return isRoot() || hasPermissionImpl(permission);
+ return hasPermissionImpl(permission);
}
protected abstract boolean hasPermissionImpl(GlobalPermission permission);
@Override
public final boolean hasComponentPermission(String permission, ComponentDto component) {
- if (isRoot()) {
- return true;
- }
String projectUuid = defaultString(component.getMainBranchProjectUuid(), component.projectUuid());
return hasProjectUuidPermission(permission, projectUuid);
}
@Override
public final boolean hasProjectPermission(String permission, ProjectDto project) {
- if (isRoot()) {
- return true;
- }
return hasProjectUuidPermission(permission, project.getUuid());
}
@Override
public final boolean hasProjectPermission(String permission, String projectUuid) {
- if (isRoot()) {
- return true;
- }
return hasProjectUuidPermission(permission, projectUuid);
}
@Override
public final boolean hasChildProjectsPermission(String permission, ComponentDto component) {
- if (isRoot()) {
- return true;
- }
String applicationUuid = defaultString(component.getMainBranchProjectUuid(), component.projectUuid());
return hasChildProjectsPermission(permission, applicationUuid);
}
@Override
public final boolean hasChildProjectsPermission(String permission, ProjectDto project) {
- if (isRoot()) {
- return true;
- }
return hasChildProjectsPermission(permission, project.getUuid());
}
@Override
public final boolean hasPortfolioChildProjectsPermission(String permission, ComponentDto portfolio) {
- if (isRoot()) {
- return true;
- }
-
return hasPortfolioChildProjectsPermission(permission, portfolio.uuid());
}
@Override
public final boolean hasComponentUuidPermission(String permission, String componentUuid) {
- if (isRoot()) {
- return true;
- }
Optional<String> projectUuid = componentUuidToProjectUuid(componentUuid);
return projectUuid
.map(s -> hasProjectUuidPermission(permission, s))
@Override
public final List<ComponentDto> keepAuthorizedComponents(String permission, Collection<ComponentDto> components) {
- if (isRoot()) {
- return new ArrayList<>(components);
- }
return doKeepAuthorizedComponents(permission, components);
}
@Override
public List<ProjectDto> keepAuthorizedProjects(String permission, Collection<ProjectDto> projects) {
- if (isRoot()) {
- return new ArrayList<>(projects);
- }
return doKeepAuthorizedProjects(permission, projects);
}
.collect(MoreCollectors.toList());
}
- @Override
- public UserSession checkIsRoot() {
- if (!isRoot()) {
- throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE);
- }
- return this;
- }
-
@Override
public final UserSession checkLoggedIn() {
if (!isLoggedIn()) {
@Override
public UserSession checkProjectPermission(String projectPermission, ProjectDto project) {
- if (isRoot() || hasProjectUuidPermission(projectPermission, project.getUuid())) {
+ if (hasProjectUuidPermission(projectPermission, project.getUuid())) {
return this;
}
@Override
public UserSession checkChildProjectsPermission(String projectPermission, ComponentDto component) {
- if (isRoot() || !APP.equals(component.qualifier()) || hasChildProjectsPermission(projectPermission, component)) {
+ if (!APP.equals(component.qualifier()) || hasChildProjectsPermission(projectPermission, component)) {
return this;
}
@Override
public UserSession checkChildProjectsPermission(String projectPermission, ProjectDto application) {
- if (isRoot() || !APP.equals(application.getQualifier()) || hasChildProjectsPermission(projectPermission, application)) {
+ if (!APP.equals(application.getQualifier()) || hasChildProjectsPermission(projectPermission, application)) {
return this;
}
return false;
}
- @Override
- public boolean isRoot() {
- return true;
- }
-
@Override
public Optional<IdentityProvider> getIdentityProvider() {
return Optional.empty();
return userDto != null;
}
- @Override
- public boolean isRoot() {
- return userDto != null && userDto.isRoot();
- }
-
@Override
public Optional<IdentityProvider> getIdentityProvider() {
return ofNullable(userDto).map(d -> computeIdentity(d).getIdentityProvider());
}
private boolean loadIsSystemAdministrator() {
- if (isRoot()) {
- return true;
- }
return hasPermission(GlobalPermission.ADMINISTER);
}
}
return get().isLoggedIn();
}
- @Override
- public UserSession checkIsRoot() {
- return get().checkIsRoot();
- }
-
- @Override
- public boolean isRoot() {
- return get().isRoot();
- }
-
@Override
public UserSession checkLoggedIn() {
get().checkLoggedIn();
*/
boolean isLoggedIn();
- /**
- * Whether the user has root privileges. If {@code true}, then user automatically
- * benefits from all the permissions on all projects.
- */
- boolean isRoot();
-
- /**
- * Ensures that {@link #isRoot()} returns {@code true} otherwise throws a
- * {@link org.sonar.server.exceptions.ForbiddenException}.
- */
- UserSession checkIsRoot();
-
/**
* Ensures that user is logged in otherwise throws {@link org.sonar.server.exceptions.UnauthorizedException}.
*/
/**
* Returns {@code true} if the permission is granted, otherwise {@code false}.
*
- * Always returns {@code true} if {@link #isRoot()} is {@code true}.
*/
boolean hasPermission(GlobalPermission permission);
*
* If the component does not exist, then returns {@code false}.
*
- * Always returns {@code true} if {@link #isRoot()} is {@code true}, even if
- * component does not exist.
- *
* @param component non-null component.
* @param permission project permission as defined by {@link org.sonar.server.permission.PermissionService}
*/
*
* Returns {@code true} if:
* <ul>
- * <li>{@link #isRoot()} is {@code true}</li>
* <li>user is administrator</li>
* </ul>
*/
@Test
public void session_has_no_permissions() {
assertThat(underTest.shouldResetPassword()).isFalse();
- assertThat(underTest.isRoot()).isFalse();
assertThat(underTest.isSystemAdministrator()).isFalse();
assertThat(underTest.hasPermissionImpl(GlobalPermission.ADMINISTER)).isFalse();
assertThat(underTest.hasProjectUuidPermission(UserRole.USER, "foo")).isFalse();
assertThat(user.getExternalLogin()).isEqualTo(USER_LOGIN);
assertThat(user.getExternalIdentityProvider()).isEqualTo("github");
assertThat(user.getExternalId()).isEqualTo("ABCD");
- assertThat(user.isRoot()).isFalse();
checkGroupMembership(user, defaultGroup);
}
assertThat(user.getExternalIdentityProvider()).isEqualTo("sonarqube");
assertThat(user.getExternalId()).isEqualTo("ABCD");
assertThat(user.isLocal()).isFalse();
- assertThat(user.isRoot()).isFalse();
checkGroupMembership(user, defaultGroup);
}
assertThat(userDto.getExternalId()).isEqualTo(USER_IDENTITY.getProviderId());
assertThat(userDto.getExternalLogin()).isEqualTo(USER_IDENTITY.getProviderLogin());
assertThat(userDto.getExternalIdentityProvider()).isEqualTo(GH_IDENTITY_PROVIDER.getKey());
- assertThat(userDto.isRoot()).isFalse();
}
@Test
assertThat(newUserSession(notActive).isActive()).isFalse();
}
- @Test
- public void isRoot_is_false_is_flag_root_is_false_on_UserDto() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- assertThat(newUserSession(root).isRoot()).isTrue();
-
- UserDto notRoot = db.users().insertUser();
- assertThat(newUserSession(notRoot).isRoot()).isFalse();
- }
-
- @Test
- public void checkIsRoot_throws_IPFE_if_flag_root_is_false_on_UserDto() {
- UserDto user = db.users().insertUser();
- UserSession underTest = newUserSession(user);
-
- assertThatForbiddenExceptionIsThrown(underTest::checkIsRoot);
- }
-
- @Test
- public void checkIsRoot_does_not_fail_if_flag_root_is_true_on_UserDto() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
-
- UserSession underTest = newUserSession(root);
-
- assertThat(underTest.checkIsRoot()).isSameAs(underTest);
- }
-
- @Test
- public void hasComponentUuidPermission_returns_true_when_flag_root_is_true_on_UserDto_no_matter_if_user_has_project_permission_for_given_uuid() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto file = db.components().insertComponent(newFileDto(project));
-
- UserSession underTest = newUserSession(root);
-
- assertThat(underTest.hasComponentUuidPermission(USER, file.uuid())).isTrue();
- assertThat(underTest.hasComponentUuidPermission(CODEVIEWER, file.uuid())).isTrue();
- assertThat(underTest.hasComponentUuidPermission(ADMIN, file.uuid())).isTrue();
- assertThat(underTest.hasComponentUuidPermission("whatever", "who cares?")).isTrue();
- }
-
- @Test
- public void checkComponentUuidPermission_succeeds_if_user_has_permission_for_specified_uuid_in_db() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto file = db.components().insertComponent(newFileDto(project));
-
- UserSession underTest = newUserSession(root);
-
- assertThat(underTest.checkComponentUuidPermission(USER, file.uuid())).isSameAs(underTest);
- assertThat(underTest.checkComponentUuidPermission("whatever", "who cares?")).isSameAs(underTest);
- }
-
@Test
public void checkComponentUuidPermission_fails_with_FE_when_user_has_not_permission_for_specified_uuid_in_db() {
UserDto user = db.users().insertUser();
assertThatForbiddenExceptionIsThrown(() -> session.checkComponentUuidPermission(USER, "another-uuid"));
}
- @Test
- public void checkChildProjectsPermission_succeeds_if_user_is_root() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto application = db.components().insertPrivateApplication();
- db.components().addApplicationProject(application, project);
-
- UserSession underTest = newUserSession(root);
-
- assertThat(underTest.checkChildProjectsPermission(USER, application)).isSameAs(underTest);
- }
-
@Test
public void checkChildProjectsPermission_succeeds_if_user_has_permissions_on_all_application_child_projects() {
UserDto user = db.users().insertUser();
@Test
public void checkPermission_succeeds_when_user_has_the_specified_permission() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- db.users().insertPermissionOnUser(root, PROVISIONING);
+ UserDto adminUser = db.users().insertAdminByUserPermission();
+ db.users().insertPermissionOnUser(adminUser, PROVISIONING);
- newUserSession(root).checkPermission(PROVISION_PROJECTS);
- }
-
- @Test
- public void checkPermission_succeeds_when_user_is_root() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
-
- newUserSession(root).checkPermission(PROVISION_PROJECTS);
+ newUserSession(adminUser).checkPermission(PROVISION_PROJECTS);
}
@Test
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", project)).isFalse();
}
- @Test
- public void hasComponentPermissionByDtoOrUuid_returns_true_for_any_project_or_permission_for_root_user() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- ComponentDto publicProject = db.components().insertPublicProject();
-
- ServerUserSession underTest = newUserSession(root);
-
- assertThat(hasComponentPermissionByDtoOrUuid(underTest, "does not matter", publicProject)).isTrue();
- }
-
@Test
public void hasComponentPermissionByDtoOrUuid_keeps_cache_of_permissions_of_logged_in_user() {
UserDto user = db.users().insertUser();
.containsExactly(copyProject1, copyProject2, copyProject4, copyProject5);
}
- @Test
- public void keepAuthorizedComponents_returns_all_specified_components_if_root() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
- UserSession underTest = newUserSession(root);
-
- ComponentDto project1 = db.components().insertPublicProject();
- ComponentDto project2 = db.components().insertPrivateProject();
- ComponentDto project3 = db.components().insertPrivateProject();
- ComponentDto project4 = db.components().insertPrivateProject();
- ComponentDto project5 = db.components().insertPrivateProject();
- ComponentDto project6 = db.components().insertPrivateProject();
-
- ComponentDto portfolio = db.components().insertPrivatePortfolio();
-
- ComponentDto subPortfolio = db.components().insertComponent(newSubPortfolio(portfolio));
-
- ComponentDto app = db.components().insertPrivateApplication();
-
- ComponentDto app2 = db.components().insertPrivateApplication();
-
- // Add public project1 to private portfolio
- db.components().addPortfolioProject(portfolio, project1);
- db.components().insertComponent(newProjectCopy(project1, portfolio));
-
- // Add private project2 to private portfolio
- db.components().addPortfolioProject(portfolio, project2);
- db.components().insertComponent(newProjectCopy(project2, portfolio));
-
- // Add private project4 to sub-portfolio
- db.components().addPortfolioProject(subPortfolio, project4);
- db.components().insertComponent(newProjectCopy(project4, subPortfolio));
- db.components().addPortfolioReference(portfolio, subPortfolio.uuid());
-
- // Add private project3 without permissions to private portfolio
- db.components().addPortfolioProject(portfolio, project3);
- db.components().insertComponent(newProjectCopy(project3, portfolio));
-
- // Add private project5 to app
- db.components().addApplicationProject(app, project5);
- db.components().insertComponent(newProjectCopy(project5, app));
- db.components().addPortfolioReference(portfolio, app.uuid());
-
- // Add private project6 to private app2
- db.components().addApplicationProject(app2, project6);
- db.components().insertComponent(newProjectCopy(project6, app2));
- db.components().addPortfolioReference(portfolio, app2.uuid());
-
- assertThat(underTest.keepAuthorizedComponents(ADMIN, Arrays.asList(portfolio))).hasSize(1);
- assertThat(underTest.keepAuthorizedComponents(ADMIN, Arrays.asList(portfolio))).containsExactly(portfolio);
-
- assertThat(underTest.keepAuthorizedComponents(ADMIN, Arrays.asList(app, subPortfolio, app2))).hasSize(3);
- assertThat(underTest.keepAuthorizedComponents(ADMIN, Arrays.asList(app, subPortfolio, app2))).containsExactly(app, subPortfolio, app2);
-
- assertThat(underTest.keepAuthorizedComponents(ADMIN, Arrays.asList(project1, project2, project3, project4, project5, project6))).hasSize(6);
- assertThat(underTest.keepAuthorizedComponents(ADMIN, Arrays.asList(project1, project2, project3, project4, project5, project6))).containsExactly(project1, project2, project3, project4, project5, project6);
- }
-
- @Test
- public void isSystemAdministrator_returns_true_if_org_feature_is_enabled_and_user_is_root() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
-
- UserSession session = newUserSession(root);
-
- assertThat(session.isSystemAdministrator()).isTrue();
- }
-
@Test
public void isSystemAdministrator_returns_false_if_org_feature_is_enabled_and_user_is_not_root() {
UserDto user = db.users().insertUser();
session.checkIsSystemAdministrator();
}
- @Test
- public void checkIsSystemAdministrator_succeeds_if_system_administrator() {
- UserDto root = db.users().insertUser();
- root = db.users().makeRoot(root);
-
- UserSession session = newUserSession(root);
-
- session.checkIsSystemAdministrator();
- }
-
@Test
public void checkIsSystemAdministrator_throws_ForbiddenException_if_not_system_administrator() {
UserDto user = db.users().insertUser();
assertThat(threadLocalUserSession.hasProjectPermission(USER, new ProjectDto().getUuid())).isFalse();
}
- @Test
- public void get_session_for_root_user() {
- GroupDto group = GroupTesting.newGroupDto();
- MockUserSession expected = new MockUserSession("root")
- .setUuid("root-uuid")
- .setResetPassword(true)
- .setLastSonarlintConnectionDate(1000L)
- .setGroups(group);
- expected.setRoot(true);
- threadLocalUserSession.set(expected);
-
- UserSession session = threadLocalUserSession.get();
- assertThat(session).isSameAs(expected);
- assertThat(threadLocalUserSession.getLastSonarlintConnectionDate()).isEqualTo(1000L);
- assertThat(threadLocalUserSession.getLogin()).isEqualTo("root");
- assertThat(threadLocalUserSession.getUuid()).isEqualTo("root-uuid");
- assertThat(threadLocalUserSession.isLoggedIn()).isTrue();
- assertThat(threadLocalUserSession.shouldResetPassword()).isTrue();
- assertThat(threadLocalUserSession.getGroups()).extracting(GroupDto::getUuid).containsOnly(group.getUuid());
- assertThat(threadLocalUserSession.hasChildProjectsPermission(USER, new ComponentDto())).isTrue();
- assertThat(threadLocalUserSession.hasChildProjectsPermission(USER, new ProjectDto())).isTrue();
- assertThat(threadLocalUserSession.hasPortfolioChildProjectsPermission(USER, new ComponentDto())).isTrue();
- assertThat(threadLocalUserSession.hasProjectPermission(USER, new ProjectDto().getUuid())).isTrue();
- }
-
@Test
public void get_session_for_anonymous() {
AnonymousMockUserSession expected = new AnonymousMockUserSession();
@Override
public boolean isSystemAdministrator() {
- return isRoot() || systemAdministrator;
+ return systemAdministrator;
}
public T setResetPassword(boolean b) {
super(AnonymousMockUserSession.class);
}
- @Override
- public boolean isRoot() {
- return false;
- }
-
@Override
public boolean isActive() {
return false;
public class MockUserSession extends AbstractMockUserSession<MockUserSession> {
private final String login;
private String uuid;
- private boolean root = false;
private String name;
private List<GroupDto> groups = new ArrayList<>();
private UserSession.IdentityProvider identityProvider;
return true;
}
- @Override
- public boolean isRoot() {
- return root;
- }
-
@Override
public boolean isActive() {
return true;
}
- public void setRoot(boolean root) {
- this.root = root;
- }
-
@Override
public String getLogin() {
return this.login;
return this;
}
- public UserSessionRule setRoot() {
- ensureMockUserSession().setRoot(true);
- return this;
- }
-
- public UserSessionRule setNonRoot() {
- ensureMockUserSession().setRoot(false);
- return this;
- }
-
public UserSessionRule setSystemAdministrator() {
ensureMockUserSession().setSystemAdministrator(true);
return this;
return currentUserSession.isLoggedIn();
}
- @Override
- public boolean isRoot() {
- return currentUserSession.isRoot();
- }
-
- @Override
- public UserSession checkIsRoot() {
- return currentUserSession.checkIsRoot();
- }
-
@Override
public UserSession checkLoggedIn() {
currentUserSession.checkLoggedIn();
return user != null;
}
- @Override
- public boolean isRoot() {
- throw notImplemented();
- }
-
@Override
protected boolean hasPermissionImpl(GlobalPermission permission) {
throw notImplemented();
* user has read access.
*/
public QueryBuilder createQueryFilter() {
- if (userSession.isRoot()) {
- return QueryBuilders.matchAllQuery();
- }
-
BoolQueryBuilder filter = boolQuery();
// anyone
assertSearchResults("sonarqube", project);
}
- @Test
- public void do_not_check_permissions_when_logged_in_user_is_root() {
- userSession.logIn().setRoot();
- ComponentDto project = newProject("sonarqube", "Quality Product");
- indexer.index(project);
- // do not give any permissions to that project
-
- assertSearchResults("sonarqube", project);
- }
}
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchIdResult;
import org.sonar.server.es.SearchOptions;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT;
public class ComponentIndexSearchTest {
@Rule
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public ComponentTextSearchFeatureRule features = new ComponentTextSearchFeatureRule();
assertThat(result.getUuids()).containsExactlyInAnyOrder(projects.get(3).uuid(), projects.get(4).uuid(), projects.get(5).uuid());
}
- @Test
- public void returns_correct_total_number_if_default_index_window_exceeded() {
- userSession.logIn().setRoot();
-
- index(IntStream.range(0, 12_000)
- .mapToObj(i -> newDoc(ComponentTesting.newPrivateProjectDto()))
- .toArray(ComponentDoc[]::new));
-
- SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions().setPage(2, 3));
- assertThat(result.getTotal()).isEqualTo(12_000);
- }
-
@Test
public void filter_unauthorized_components() {
ComponentDto unauthorizedProject = db.components().insertPrivateProject();
indexer.indexAll();
Arrays.stream(components).forEach(authorizationIndexerTester::allowOnlyAnyone);
}
-
- private void index(ComponentDoc... componentDocs) {
- es.putDocuments(TYPE_COMPONENT.getMainType(), componentDocs);
- }
-
- private ComponentDoc newDoc(ComponentDto componentDoc) {
- return new ComponentDoc()
- .setId(componentDoc.uuid())
- .setKey(componentDoc.getKey())
- .setName(componentDoc.name())
- .setProjectUuid(componentDoc.projectUuid())
- .setQualifier(componentDoc.qualifier());
- }
}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.component.index;
+
+import java.util.stream.IntStream;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.api.utils.System2;
+import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ComponentTesting;
+import org.sonar.server.es.EsTester;
+import org.sonar.server.es.SearchIdResult;
+import org.sonar.server.es.SearchOptions;
+import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT;
+
+public class ComponentIndexSearchWindowExceededTest {
+ @Rule
+ public EsTester es = EsTester.create();
+
+ private final WebAuthorizationTypeSupport authorizationTypeSupport = mock(WebAuthorizationTypeSupport.class);
+ private final ComponentIndex underTest = new ComponentIndex(es.client(), authorizationTypeSupport, System2.INSTANCE);
+
+ @Test
+ public void returns_correct_total_number_if_default_index_window_exceeded() {
+ // bypassing the permission check, to have easily 12_000 elements searcheable without having to inserting them + permission.
+ when(authorizationTypeSupport.createQueryFilter()).thenReturn(QueryBuilders.matchAllQuery());
+
+ index(IntStream.range(0, 12_000)
+ .mapToObj(i -> newDoc(ComponentTesting.newPublicProjectDto()))
+ .toArray(ComponentDoc[]::new));
+
+ SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions().setPage(2, 3));
+ assertThat(result.getTotal()).isEqualTo(12_000);
+ }
+
+ private void index(ComponentDoc... componentDocs) {
+ es.putDocuments(TYPE_COMPONENT.getMainType(), componentDocs);
+ }
+
+ private ComponentDoc newDoc(ComponentDto componentDoc) {
+ return new ComponentDoc()
+ .setId(componentDoc.uuid())
+ .setKey(componentDoc.getKey())
+ .setName(componentDoc.name())
+ .setProjectUuid(componentDoc.projectUuid())
+ .setQualifier(componentDoc.qualifier());
+ }
+}
userSessionRule.logIn().setGroups(group1, group2);
assertThatSearchReturnsEmpty(IssueQuery.builder().projectUuids(singletonList(project3.uuid())));
-
- userSessionRule.setRoot();
- assertThatSearchReturnsOnly(IssueQuery.builder(), "I1", "I2", "I3");
}
@Test
// another user
userSessionRule.logIn(newUserDto());
assertThatSearchReturnsEmpty(IssueQuery.builder());
-
- userSessionRule.setRoot();
- assertThatSearchReturnsOnly(IssueQuery.builder(), "I1", "I2", "I3");
- }
-
- @Test
- public void root_user_is_authorized_to_access_all_issues() {
- ComponentDto project = newPrivateProjectDto();
- indexIssue(newDoc("I1", project));
- userSessionRule.logIn().setRoot();
-
- assertThatSearchReturnsOnly(IssueQuery.builder(), "I1");
}
@Test
assertResults(new ProjectMeasuresQuery(), APP1, PROJECT1);
}
- @Test
- public void root_user_can_access_all_projects_and_applications() {
- indexForUser(USER1, newDoc(PROJECT1), newDoc(APP1));
- // connecting with a root but not USER1
- userSession.logIn().setRoot();
-
- assertResults(new ProjectMeasuresQuery(), APP1, PROJECT1);
- }
-
@Test
public void return_all_projects_and_applications_when_setIgnoreAuthorization_is_true() {
indexForUser(USER1, newDoc(PROJECT1), newDoc(PROJECT2), newDoc(APP1), newDoc(APP2));
private WebAuthorizationTypeSupport underTest = new WebAuthorizationTypeSupport(userSession);
- @Test
- public void createQueryFilter_does_not_include_permission_filters_if_user_is_flagged_as_root() {
- userSession.logIn().setRoot();
-
- QueryBuilder filter = underTest.createQueryFilter();
-
- assertThat(filter).isInstanceOf(MatchAllQueryBuilder.class);
- }
-
@Test
public void createQueryFilter_sets_filter_on_anyone_group_if_user_is_anonymous() {
userSession.anonymous();
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
-import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter;
import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
+import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
}
private List<ProjectQgateAssociationDto> keepAuthorizedProjects(DbSession dbSession, List<ProjectQgateAssociationDto> projects) {
- if (userSession.isRoot()) {
- // the method AuthorizationDao#keepAuthorizedProjectIds() should be replaced by
- // a call to UserSession, which would transparently support roots.
- // Meanwhile root is explicitly handled.
- return projects;
- }
List<String> projectUuids = projects.stream().map(ProjectQgateAssociationDto::getUuid).collect(MoreCollectors.toList());
Collection<String> authorizedProjectIds = dbClient.authorizationDao().keepAuthorizedProjectUuids(dbSession, projectUuids, userSession.getUuid(), UserRole.USER);
return projects.stream().filter(project -> authorizedProjectIds.contains(project.getUuid())).collect(MoreCollectors.toList());
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.sonar.core.platform.Module;
-
-public class RootWsModule extends Module {
- @Override
- protected void configureModule() {
- add(RootsWs.class,
- SetRootAction.class,
- UnsetRootAction.class,
- SearchAction.class);
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.sonar.api.server.ws.WebService;
-
-public class RootsWs implements WebService {
- private final RootsWsAction[] actions;
-
- public RootsWs(RootsWsAction... actions) {
- this.actions = actions;
- }
-
- @Override
- public void define(Context context) {
- NewController controller = context.createController("api/roots")
- .setSince("6.2")
- .setDescription("Manage root users");
-
- for (RootsWsAction action : actions) {
- action.define(controller);
- }
-
- controller.done();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.sonar.server.ws.WsAction;
-
-public interface RootsWsAction extends WsAction {
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import java.util.List;
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.user.UserQuery;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.user.UserDto;
-import org.sonar.server.user.UserSession;
-import org.sonarqube.ws.Roots;
-
-import static org.sonar.server.ws.WsUtils.writeProtobuf;
-
-public class SearchAction implements RootsWsAction {
- private final UserSession userSession;
- private final DbClient dbClient;
-
- public SearchAction(UserSession userSession, DbClient dbClient) {
- this.userSession = userSession;
- this.dbClient = dbClient;
- }
-
- @Override
- public void define(WebService.NewController controller) {
- controller.createAction("search")
- .setInternal(true)
- .setPost(false)
- .setDescription("Search for root users.<br/>" +
- "Requires to be root.")
- .setSince("6.2")
- .setResponseExample(getClass().getResource("search-example.json"))
- .setHandler(this);
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
-
- try (DbSession dbSession = dbClient.openSession(false)) {
- List<UserDto> userDtos = dbClient.userDao().selectUsers(
- dbSession,
- UserQuery.builder()
- .mustBeRoot()
- .build());
-
- writeResponse(request, response, userDtos);
- }
- }
-
- private static void writeResponse(Request request, Response response, List<UserDto> dtos) {
- Roots.SearchResponse.Builder responseBuilder = Roots.SearchResponse.newBuilder();
- Roots.RootContent.Builder rootBuilder = Roots.RootContent.newBuilder();
- dtos.forEach(dto -> responseBuilder.addRoots(toRoot(rootBuilder, dto)));
- writeProtobuf(responseBuilder.build(), request, response);
- }
-
- private static Roots.RootContent toRoot(Roots.RootContent.Builder builder, UserDto dto) {
- builder.clear();
- builder.setLogin(dto.getLogin());
- if (dto.getName() != null) {
- builder.setName(dto.getName());
- }
- if (dto.getEmail() != null) {
- builder.setEmail(dto.getEmail());
- }
- return builder.build();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.user.UserDto;
-import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.user.UserSession;
-
-import static java.lang.String.format;
-
-public class SetRootAction implements RootsWsAction {
- private static final String PARAM_LOGIN = "login";
-
- private final UserSession userSession;
- private final DbClient dbClient;
-
- public SetRootAction(UserSession userSession, DbClient dbClient) {
- this.userSession = userSession;
- this.dbClient = dbClient;
- }
-
- @Override
- public void define(WebService.NewController controller) {
- WebService.NewAction action = controller.createAction("set_root")
- .setInternal(true)
- .setPost(true)
- .setDescription("Make the specified user root.<br/>" +
- "Requires to be root.")
- .setSince("6.2")
- .setHandler(this);
-
- action.createParam(PARAM_LOGIN)
- .setDescription("A user login")
- .setExampleValue("admin")
- .setRequired(true)
- .setSince("6.2");
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
-
- String login = request.mandatoryParam(PARAM_LOGIN);
- try (DbSession dbSession = dbClient.openSession(false)) {
- UserDto userDto = dbClient.userDao().selectByLogin(dbSession, login);
- if (userDto == null || !userDto.isActive()) {
- throw new NotFoundException(format("User with login '%s' not found", login));
- }
-
- if (!userDto.isRoot()) {
- dbClient.userDao().setRoot(dbSession, login, true);
- dbSession.commit();
- }
- }
- response.noContent();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.user.UserDto;
-import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.user.UserSession;
-
-import static java.lang.String.format;
-import static org.sonar.server.exceptions.BadRequestException.checkRequest;
-
-public class UnsetRootAction implements RootsWsAction {
- private static final String PARAM_LOGIN = "login";
-
- private final UserSession userSession;
- private final DbClient dbClient;
-
- public UnsetRootAction(UserSession userSession, DbClient dbClient) {
- this.userSession = userSession;
- this.dbClient = dbClient;
- }
-
- @Override
- public void define(WebService.NewController controller) {
- WebService.NewAction action = controller.createAction("unset_root")
- .setInternal(true)
- .setPost(true)
- .setDescription("Make the specified user not root.<br/>" +
- "Requires to be root.")
- .setSince("6.2")
- .setHandler(this);
-
- action.createParam(PARAM_LOGIN)
- .setDescription("A user login")
- .setExampleValue("admin")
- .setRequired(true)
- .setSince("6.2");
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
-
- String login = request.mandatoryParam(PARAM_LOGIN);
- try (DbSession dbSession = dbClient.openSession(false)) {
- UserDto userDto = dbClient.userDao().selectByLogin(dbSession, login);
- if (userDto == null || !userDto.isActive()) {
- throw new NotFoundException(format("User with login '%s' not found", login));
- }
- checkRequest(dbClient.userDao().countRootUsersButLogin(dbSession, login) > 0, "Last root can't be unset");
- if (userDto.isRoot()) {
- dbClient.userDao().setRoot(dbSession, login, false);
- dbSession.commit();
- }
- }
- response.noContent();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-@ParametersAreNonnullByDefault
-package org.sonar.server.root.ws;
-
-import javax.annotation.ParametersAreNonnullByDefault;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.sonar.api.web.UserRole.ADMIN;
+import static org.sonar.api.web.UserRole.SCAN;
import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY;
import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY;
import static org.sonar.db.component.BranchType.BRANCH;
-import static org.sonar.db.permission.GlobalPermission.SCAN;
public class TaskActionTest {
@Before
public void setUp() {
privateProject = db.components().insertPrivateProject();
+ userSession.logIn().addProjectPermission(ADMIN, privateProject);
publicProject = db.components().insertPublicProject();
}
@Test
public void task_is_in_queue() {
UserDto user = db.users().insertUser();
- userSession.logIn(user).setRoot();
+ userSession.addProjectPermission(SCAN, privateProject);
CeQueueDto queueDto = new CeQueueDto();
queueDto.setTaskType(CeTaskTypes.REPORT);
@Test
public void no_warning_detail_on_task_in_queue() {
UserDto user = db.users().insertUser();
- userSession.logIn(user).setRoot();
+ userSession.logIn(user).setSystemAdministrator();
CeQueueDto queueDto = createAndPersistQueueTask(null, user);
IntStream.range(0, 1 + new Random().nextInt(5))
.forEach(i -> db.getDbClient().ceTaskMessageDao().insert(db.getSession(),
@Test
public void task_is_archived() {
UserDto user = db.users().insertUser();
- userSession.logIn(user).setRoot();
+ userSession.logIn(user).addProjectPermission(SCAN, privateProject);
CeActivityDto activityDto = createActivityDto(SOME_TASK_UUID);
persist(activityDto);
@Test
public void branch_in_past_activity() {
- logInAsRoot();
+ logInAsSystemAdministrator();
ComponentDto project = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH));
@Test
public void branch_in_queue_analysis() {
UserDto user = db.users().insertUser();
- userSession.logIn(user).setRoot();
+ userSession.logIn(user).setSystemAdministrator();
+ ;
String branch = "my_branch";
CeQueueDto queueDto = createAndPersistQueueTask(null, user);
insertCharacteristic(queueDto, BRANCH_KEY, branch);
@Test
public void return_stacktrace_of_failed_activity_with_stacktrace_when_additionalField_is_set() {
- logInAsRoot();
+ logInAsSystemAdministrator();
CeActivityDto activityDto = createActivityDto(SOME_TASK_UUID)
.setErrorMessage("error msg")
@Test
public void do_not_return_stacktrace_of_failed_activity_with_stacktrace_when_additionalField_is_not_set() {
- logInAsRoot();
+ logInAsSystemAdministrator();
CeActivityDto activityDto = createActivityDto(SOME_TASK_UUID)
.setErrorMessage("error msg")
@Test
public void return_scannerContext_of_activity_with_scannerContext_when_additionalField_is_set() {
- logInAsRoot();
+ logInAsSystemAdministrator();
String scannerContext = "this is some scanner context, yeah!";
persist(createActivityDto(SOME_TASK_UUID));
@Test
public void do_not_return_scannerContext_of_activity_with_scannerContext_when_additionalField_is_not_set() {
- logInAsRoot();
+ logInAsSystemAdministrator();
String scannerContext = "this is some scanner context, yeah!";
persist(createActivityDto(SOME_TASK_UUID));
@Test
public void do_not_return_stacktrace_of_failed_activity_without_stacktrace() {
- logInAsRoot();
+ logInAsSystemAdministrator();
CeActivityDto activityDto = createActivityDto(SOME_TASK_UUID)
.setErrorMessage("error msg");
@Test
public void throw_NotFoundException_if_id_does_not_exist() {
- logInAsRoot();
+ logInAsSystemAdministrator();
TestRequest request = ws.newRequest()
.setParam("id", "DOES_NOT_EXIST");
@Test
public void get_project_queue_task_with_scan_permission_but_not_on_project() {
UserDto user = db.users().insertUser();
- userSession.logIn(user).addPermission(SCAN);
+ userSession.logIn(user).addPermission(GlobalPermission.SCAN);
CeQueueDto task = createAndPersistQueueTask(privateProject, user);
call(task.getUuid());
@Test
public void get_project_archived_task_with_scan_permission_but_not_on_project() {
- userSession.logIn().addPermission(SCAN);
+ userSession.logIn().addPermission(GlobalPermission.SCAN);
CeActivityDto task = createAndPersistArchivedTask(privateProject);
call(task.getUuid());
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
- }
-
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ userSession.addPermission(GlobalPermission.ADMINISTER);
}
private void call(String taskUuid) {
public class ShowActionTest {
@Rule
- public final UserSessionRule userSession = UserSessionRule.standalone();
+ public final UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public final DbTester db = DbTester.create(System2.INSTANCE);
@Test
public void json_example() {
- userSession.logIn().setRoot();
insertJsonExampleComponentsAndSnapshots();
String response = ws.newRequest()
@Test
public void tags_displayed_only_for_project() {
- userSession.logIn().setRoot();
insertJsonExampleComponentsAndSnapshots();
String response = ws.newRequest()
public void show_with_browse_permission() {
ComponentDto project = newPrivateProjectDto("project-uuid");
db.components().insertProjectAndSnapshot(project);
- userSession.logIn().addProjectPermission(USER, project);
+ userSession.addProjectPermission(USER, project);
ShowWsResponse response = newRequest(project.getDbKey());
@Test
public void should_return_visibility_for_private_project() {
- userSession.logIn().setRoot();
ComponentDto privateProject = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, privateProject);
ShowWsResponse result = newRequest(privateProject.getDbKey());
assertThat(result.getComponent().hasVisibility()).isTrue();
@Test
public void should_return_visibility_for_public_project() {
- userSession.logIn().setRoot();
ComponentDto publicProject = db.components().insertPublicProject();
+ userSession.registerComponents(publicProject);
ShowWsResponse result = newRequest(publicProject.getDbKey());
assertThat(result.getComponent().hasVisibility()).isTrue();
@Test
public void should_return_visibility_for_portfolio() {
- userSession.logIn().setRoot();
ComponentDto view = db.components().insertPrivatePortfolio();
+ userSession.addProjectPermission(USER, view);
ShowWsResponse result = newRequest(view.getDbKey());
assertThat(result.getComponent().hasVisibility()).isTrue();
@Test
public void should_not_return_visibility_for_module() {
- userSession.logIn().setRoot();
ComponentDto privateProject = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, privateProject);
ComponentDto module = db.components().insertComponent(newModuleDto(privateProject));
ShowWsResponse result = newRequest(module.getDbKey());
@Test
public void throw_ForbiddenException_if_user_doesnt_have_browse_permission_on_project() {
- userSession.logIn();
-
ComponentDto componentDto = newPrivateProjectDto("project-uuid");
db.components().insertProjectAndSnapshot(componentDto);
@Test
public void fail_if_component_is_removed() {
- userSession.logIn().setRoot();
- ComponentDto project = db.components().insertComponent(newPrivateProjectDto());
+ ComponentDto privateProjectDto = newPrivateProjectDto();
+ ComponentDto project = db.components().insertComponent(privateProjectDto);
+ userSession.addProjectPermission(USER, project);
db.components().insertComponent(newFileDto(project).setDbKey("file-key").setEnabled(false));
assertThatThrownBy(() -> newRequest("file-key"))
.setDescription("Java Markdown Project")
.setQualifier(Qualifiers.PROJECT),
p -> p.setTagsString("language, plugin"));
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project, snapshot -> snapshot
.setProjectVersion("1.1")
.setCreatedAt(parseDateTime("2017-03-01T11:39:03+0100").getTime())
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.formatDateTime;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.server.developers.ws.SearchEventsAction.PARAM_FROM;
import static org.sonar.server.developers.ws.SearchEventsAction.PARAM_PROJECTS;
@Test
public void issue_event() {
- userSession.logIn().setRoot();
+ userSession.logIn();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, 1_500_000_000_000L);
insertIssue(project, analysis);
insertIssue(project, analysis);
@Test
public void many_issues_events() {
- userSession.logIn().setRoot();
+ userSession.logIn();
long from = 1_500_000_000_000L;
ComponentDto project = db.components().insertPrivateProject(p -> p.setName("SonarQube"));
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, from);
insertIssue(project, analysis);
insertIssue(project, analysis);
@Test
public void does_not_return_old_issue() {
- userSession.logIn().setRoot();
+ userSession.logIn();
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, 1_500_000_000_000L);
db.issues().insert(db.rules().insert(), project, project, i -> i.setIssueCreationDate(new Date(analysis.getCreatedAt() - 10_000L)));
issueIndexer.indexAllIssues();
@Test
public void return_link_to_issue_search_for_new_issues_event() {
- userSession.logIn("my_login").setRoot();
+ userSession.logIn("my_login");
ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("my_project"));
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, 1_400_000_000_000L);
insertIssue(project, analysis);
issueIndexer.indexAllIssues();
@Test
public void branch_issues_events() {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto branch1 = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey("branch1"));
SnapshotDto branch1Analysis = insertAnalysis(branch1, 1_500_000_000_000L);
insertIssue(branch1, branch1Analysis);
@Test
public void pull_request_issues_events() {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto nonMainBranch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey("nonMain"));
SnapshotDto nonMainBranchAnalysis = insertAnalysis(nonMainBranch, 1_500_000_000_000L);
insertIssue(nonMainBranch, nonMainBranchAnalysis);
@Test
public void encode_link() {
- userSession.logIn("rågnar").setRoot();
+ userSession.logIn("rågnar").setSystemAdministrator();
long from = 1_500_000_000_000L;
ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("M&M's"));
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, from);
insertIssue(project, analysis);
issueIndexer.indexAllIssues();
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.formatDateTime;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.event.EventTesting.newEvent;
@Rule
public EsTester es = EsTester.create();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn();
private Server server = mock(Server.class);
- private IssueIndex issueIndex = new IssueIndex(es.client(), null, null, null);
+ private IssueIndex issueIndex = new IssueIndex(es.client(), null, userSession, null);
private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
private WsActionTester ws = new WsActionTester(new SearchEventsAction(db.getDbClient(), userSession, server, issueIndex,
issueIndexSyncProgressChecker));
@Test
public void quality_gate_events() {
- userSession.logIn().setRoot();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto projectAnalysis = insertSuccessfulActivity(project, 1_500_000_000_000L);
db.events().insertEvent(newQualityGateEvent(projectAnalysis).setDate(projectAnalysis.getCreatedAt()).setName("Failed"));
@Test
public void branch_quality_gate_events() {
- userSession.logIn().setRoot();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH));
SnapshotDto projectAnalysis = insertSuccessfulActivity(project, 1_500_000_000_000L);
SnapshotDto branchAnalysis = insertSuccessfulActivity(branch, 1_500_000_000_000L);
@Test
public void does_not_return_quality_gate_events_on_pull_request() {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
@Test
public void return_only_latest_quality_gate_event() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject(p -> p.setName("My Project"));
+ userSession.addProjectPermission(USER, project);
SnapshotDto a1 = insertSuccessfulActivity(project, 1_500_000_000_000L);
EventDto e1 = db.events().insertEvent(newQualityGateEvent(a1).setName("Failed").setDate(a1.getCreatedAt()));
SnapshotDto a2 = insertSuccessfulActivity(project, 1_500_000_000_001L);
@Test
public void return_link_to_dashboard_for_quality_gate_event() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertSuccessfulActivity(project, 1_500_000_000_000L);
EventDto e1 = db.events().insertEvent(newQualityGateEvent(analysis).setName("Failed").setDate(analysis.getCreatedAt()));
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
@Test
public void encode_link() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("M&M's"));
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertSuccessfulActivity(project, 1_500_000_000_000L);
EventDto event = db.events().insertEvent(newQualityGateEvent(analysis).setName("Failed").setDate(analysis.getCreatedAt()));
when(server.getPublicRootUrl()).thenReturn("http://sonarcloud.io");
@Test
public void filter_quality_gate_event() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertSuccessfulActivity(project, 1_500_000_000_000L);
EventDto qualityGateEvent = db.events().insertEvent(newQualityGateEvent(analysis).setDate(analysis.getCreatedAt()));
EventDto versionEvent = db.events().insertEvent(newEvent(analysis).setCategory(EventCategory.VERSION.getLabel()).setDate(analysis.getCreatedAt()));
@Test
public void filter_by_from_date_inclusive() {
- userSession.logIn().setRoot();
ComponentDto project1 = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project1);
ComponentDto project2 = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project2);
ComponentDto project3 = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project3);
long from1 = 1_500_000_000_000L;
long from2 = 1_400_000_000_000L;
long from3 = 1_300_000_000_000L;
@Test
public void return_one_quality_gate_change_per_project() {
- userSession.logIn().setRoot();
ComponentDto project1 = db.components().insertPrivateProject(p -> p.setName("p1"));
+ userSession.addProjectPermission(USER, project1);
ComponentDto project2 = db.components().insertPrivateProject(p -> p.setName("p2"));
+ userSession.addProjectPermission(USER, project2);
long from = 1_500_000_000_000L;
SnapshotDto a11 = insertSuccessfulActivity(project1, from);
SnapshotDto a12 = insertSuccessfulActivity(project1, from + 1L);
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.formatDateTime;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.event.EventTesting.newEvent;
import static org.sonar.server.developers.ws.SearchEventsAction.PARAM_FROM;
import static org.sonar.server.developers.ws.SearchEventsAction.PARAM_PROJECTS;
@Rule
public EsTester es = EsTester.create();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn();
private Server server = mock(Server.class);
private IssueIndex issueIndex = new IssueIndex(es.client(), null, null, null);
private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
@Test
public void json_example() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject(p -> p.setName("My Project").setDbKey(KeyExamples.KEY_PROJECT_EXAMPLE_001));
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, 1_500_000_000_000L);
EventDto e1 = db.events().insertEvent(newQualityGateEvent(analysis).setName("Failed").setDate(analysis.getCreatedAt()));
IntStream.range(0, 15).forEach(x -> insertIssue(project, analysis));
@Test
public void events() {
- userSession.logIn().setRoot();
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
SnapshotDto projectAnalysis = insertAnalysis(project, 1_500_000_000_000L);
db.events().insertEvent(newQualityGateEvent(projectAnalysis).setDate(projectAnalysis.getCreatedAt()).setName("Passed"));
@Test
public void does_not_return_old_events() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = insertAnalysis(project, 1_500_000_000_000L);
insertIssue(project, analysis);
db.events().insertEvent(newQualityGateEvent(analysis).setDate(analysis.getCreatedAt()).setName("Passed"));
@Test
public void empty_response_for_empty_list_of_projects() {
- userSession.logIn().setRoot();
-
SearchEventsWsResponse result = ws.newRequest()
.setParam(PARAM_PROJECTS, "")
.setParam(PARAM_FROM, "")
@Test
public void does_not_return_events_of_project_for_which_the_current_user_has_no_browse_permission() {
- userSession.logIn();
-
ComponentDto project1 = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.CODEVIEWER, project1);
userSession.addProjectPermission(UserRole.ISSUE_ADMIN, project1);
ComponentDto project2 = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project2);
+ userSession.addProjectPermission(USER, project2);
SnapshotDto a1 = insertAnalysis(project1, 1_500_000_000_000L);
EventDto e1 = db.events().insertEvent(newQualityGateEvent(a1).setDate(a1.getCreatedAt()));
@Test
public void empty_response_if_project_key_is_unknown() {
- userSession.logIn().setRoot();
-
long from = 1_500_000_000_000L;
SearchEventsWsResponse result = ws.newRequest()
.setParam(PARAM_PROJECTS, "unknown")
@Test
public void fail_if_date_format_is_not_valid() {
- userSession.logIn().setRoot();
-
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_PROJECTS, "foo")
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
-import org.sonar.api.web.UserRole;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
@Test
public void provided_project() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
ComponentWsResponse response = newRequest(project.getKey(), metric.getKey());
@Test
public void without_additional_fields() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
@Test
public void branch() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void pull_request() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void new_issue_count_measures_are_transformed_in_pr() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void new_issue_count_measures_are_not_transformed_if_they_dont_exist_in_pr() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void reference_key_in_the_response() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto view = db.components().insertPrivatePortfolio();
+ userSession.addProjectPermission(USER, view);
db.components().insertSnapshot(view);
ComponentDto projectCopy = db.components().insertComponent(newProjectCopy("project-uuid-copy", project, view));
MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
@Test
public void use_deprecated_component_id_parameter() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
userSession.addProjectPermission(USER, project);
MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
@Test
public void metric_without_a_domain() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
MetricDto metricWithoutDomain = db.measures().insertMetric(m -> m
.setValueType("INT")
.setDomain(null));
public void use_best_values() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
MetricDto metric = db.measures().insertMetric(m -> m
.setValueType("INT")
.setBestValue(7.0d)
@Test
public void fail_when_a_metric_is_not_found() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
db.measures().insertMetric(m -> m.setKey("ncloc").setValueType("INT"));
db.measures().insertMetric(m -> m.setKey("complexity").setValueType("INT"));
@Test
public void fail_when_empty_metric_keys_parameter() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
assertThatThrownBy(() -> newRequest(project.getKey(), ""))
@Test
public void fail_when_component_is_removed() {
ComponentDto project = db.components().insertPrivateProject(p -> p.setEnabled(false));
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
userSession.addProjectPermission(USER, project);
MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
public void fail_if_branch_does_not_exist() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
assertThatThrownBy(() -> {
@Test
public void fail_when_using_branch_db_key() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
@Test
public void json_example() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = db.components().insertSnapshot(project,
s -> s.setPeriodDate(parseDateTime("2016-01-11T10:49:50+0100").getTime())
.setPeriodMode("previous_version")
import org.sonar.api.measures.Metric;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
-import org.sonar.api.web.UserRole;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE;
import static org.sonar.api.server.ws.WebService.Param.SORT;
import static org.sonar.api.utils.DateUtils.parseDateTime;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentDbTester.toProjectDto;
import static org.sonar.db.component.ComponentTesting.newDirectory;
public class ComponentTreeActionTest {
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
public void json_example() {
ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("MY_PROJECT")
.setName("My Project"));
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = db.components().insertSnapshot(project, s -> s.setPeriodDate(parseDateTime("2016-01-11T10:49:50+0100").getTime())
.setPeriodMode("previous_version")
.setPeriodParam("1.0-SNAPSHOT"));
@Test
public void empty_response() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentTreeWsResponse response = ws.newRequest()
.setParam(PARAM_COMPONENT, project.getKey())
.setPeriodDate(System.currentTimeMillis())
.setPeriodMode("last_version")
.setPeriodDate(System.currentTimeMillis()));
- userSession.anonymous().addProjectPermission(UserRole.USER, project);
+ userSession.anonymous().addProjectPermission(USER, project);
ComponentDto directory = newDirectory(project, "directory-uuid", "path/to/directory").setName("directory-1");
db.components().insertComponent(directory);
ComponentDto file = newFileDto(directory, null, "file-uuid").setName("file-1");
public void load_measures_with_best_value() {
ComponentDto project = db.components().insertPrivateProject();
SnapshotDto projectSnapshot = db.components().insertSnapshot(project);
- userSession.anonymous().addProjectPermission(UserRole.USER, project);
+ userSession.anonymous().addProjectPermission(USER, project);
ComponentDto directory = newDirectory(project, "directory-uuid", "path/to/directory").setName("directory-1");
db.components().insertComponent(directory);
ComponentDto file = newFileDto(directory, null, "file-uuid").setName("file-1");
public void return_is_best_value_on_leak_measures() {
ComponentDto project = db.components().insertPrivateProject();
db.components().insertSnapshot(project);
- userSession.anonymous().addProjectPermission(UserRole.USER, project);
+ userSession.anonymous().addProjectPermission(USER, project);
ComponentDto file = newFileDto(project, null);
db.components().insertComponent(file);
@Test
public void use_best_value_for_rating() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.anonymous().addProjectPermission(UserRole.USER, project);
+ userSession.anonymous().addProjectPermission(USER, project);
SnapshotDto projectSnapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(project)
.setPeriodDate(parseDateTime("2016-01-11T10:49:50+0100").getTime())
.setPeriodMode("previous_version")
@Test
public void load_measures_multi_sort_with_metric_key_and_paginated() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto projectSnapshot = db.components().insertSnapshot(project);
ComponentDto file9 = db.components().insertComponent(newFileDto(project, null, "file-uuid-9").setName("file-1").setDbKey("file-9-key"));
ComponentDto file8 = db.components().insertComponent(newFileDto(project, null, "file-uuid-8").setName("file-1").setDbKey("file-8-key"));
@Test
public void sort_by_metric_value() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto projectSnapshot = db.components().insertSnapshot(project);
ComponentDto file4 = db.components().insertComponent(newFileDto(project, null, "file-uuid-4").setDbKey("file-4-key"));
ComponentDto file3 = db.components().insertComponent(newFileDto(project, null, "file-uuid-3").setDbKey("file-3-key"));
@Test
public void remove_components_without_measure_on_the_metric_sort() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto projectSnapshot = db.components().insertSnapshot(project);
ComponentDto file1 = newFileDto(project, null, "file-uuid-1").setDbKey("file-1-key");
ComponentDto file2 = newFileDto(project, null, "file-uuid-2").setDbKey("file-2-key");
@Test
public void sort_by_metric_period() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto projectSnapshot = db.components().insertSnapshot(project);
ComponentDto file3 = db.components().insertComponent(newFileDto(project, null, "file-uuid-3").setDbKey("file-3-key"));
ComponentDto file1 = db.components().insertComponent(newFileDto(project, null, "file-uuid-1").setDbKey("file-1-key"));
@Test
public void remove_components_without_measure_on_the_metric_period_sort() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto projectSnapshot = db.components().insertSnapshot(project);
ComponentDto file4 = db.components().insertComponent(newFileDto(project, null, "file-uuid-4").setDbKey("file-4-key"));
ComponentDto file3 = db.components().insertComponent(newFileDto(project, null, "file-uuid-3").setDbKey("file-3-key"));
public void load_measures_when_no_leave_qualifier() {
resourceTypes.setLeavesQualifiers();
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
db.components().insertComponent(newFileDto(project, null));
insertNclocMetric();
@Test
public void branch() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void pull_request() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void fix_pull_request_new_issue_count_metrics() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
SnapshotDto analysis = db.components().insertSnapshot(branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void new_issue_count_measures_are_not_transformed_if_they_dont_exist_in_pr() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setKey("pr").setBranchType(PULL_REQUEST));
SnapshotDto analysis = db.components().insertSnapshot(pr);
ComponentDto file = db.components().insertComponent(newFileDto(pr));
@Test
public void metric_without_a_domain() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
SnapshotDto analysis = db.getDbClient().snapshotDao().insert(dbSession, newAnalysis(project));
MetricDto metricWithoutDomain = db.measures().insertMetric(m -> m
.setValueType(Metric.ValueType.INT.name())
@Test
public void project_reference_from_portfolio() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
ComponentDto view = db.components().insertPrivatePortfolio();
+ userSession.addProjectPermission(USER, view);
SnapshotDto viewAnalysis = db.components().insertSnapshot(view);
ComponentDto projectCopy = db.components().insertComponent(newProjectCopy(project, view));
MetricDto ncloc = insertNclocMetric();
@Test
public void portfolio_local_reference_in_portfolio() {
- ComponentDto view = db.components().insertComponent(ComponentTesting.newPortfolio("VIEW1-UUID").setDbKey("Apache-Projects").setName("Apache Projects"));
+ ComponentDto view = db.components().insertComponent(ComponentTesting.newPortfolio("VIEW1-UUID")
+ .setDbKey("Apache-Projects").setName("Apache Projects"));
+ userSession.registerComponents(view);
ComponentDto view2 = db.components().insertPrivatePortfolio();
+ userSession.addProjectPermission(USER, view2);
ComponentDto localView = db.components().insertComponent(
ComponentTesting.newSubPortfolio(view, "SUB-VIEW-UUID", "All-Projects").setName("All projects").setCopyComponentUuid(view2.uuid()));
db.components().insertSnapshot(view);
@Test
public void application_local_reference_in_portfolio() {
- ComponentDto view = db.components().insertComponent(ComponentTesting.newPortfolio("VIEW1-UUID").setDbKey("Apache-Projects").setName("Apache Projects"));
+ ComponentDto apache_projects = ComponentTesting.newPortfolio("VIEW1-UUID")
+ .setDbKey("Apache-Projects").setName("Apache Projects").setPrivate(true);
+ userSession.addProjectPermission(USER, apache_projects);
+ ComponentDto view = db.components().insertComponent(apache_projects);
ComponentDto application = db.components().insertPrivateApplication();
+ userSession.addProjectPermission(USER, application);
ComponentDto localView = db.components().insertComponent(
ComponentTesting.newSubPortfolio(view, "SUB-VIEW-UUID", "All-Projects").setName("All projects").setCopyComponentUuid(application.uuid()));
db.components().insertSnapshot(view);
public void project_branch_reference_from_application_branch() {
MetricDto ncloc = insertNclocMetric();
ComponentDto application = db.components().insertPublicProject(c -> c.setQualifier(APP).setDbKey("app-key"));
- ComponentDto applicationBranch = db.components().insertProjectBranch(application, a -> a.setKey("app-branch"));
+ userSession.registerApplication(application);
+ ComponentDto applicationBranch = db.components().insertProjectBranch(application, a -> a.setKey("app-branch"), a -> a.setUuid("custom-uuid"));
ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("project-key"));
ComponentDto projectBranch = db.components().insertProjectBranch(project, b -> b.setKey("project-branch"));
ComponentDto techProjectBranch = db.components().insertComponent(newProjectCopy(projectBranch, applicationBranch)
@Test
public void fail_when_a_metric_is_not_found() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
insertNclocMetric();
insertNewViolationsMetric();
@Test
public void fail_when_using_DISTRIB_metrics() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("distrib1").setValueType(DISTRIB.name()));
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("distrib2").setValueType(DISTRIB.name()));
@Test
public void fail_when_using_DATA_metrics() {
ComponentDto project = db.components().insertPrivateProject();
+ userSession.addProjectPermission(USER, project);
db.components().insertSnapshot(project);
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("data1").setValueType(DISTRIB.name()));
toProjectDto(project1, 1L),
toProjectDto(project2, 1L));
- userSession.addProjectPermission(UserRole.USER, app, project1);
+ userSession.addProjectPermission(USER, app, project1);
var request = ws.newRequest()
.setParam(PARAM_COMPONENT, app.getKey())
ComponentDto project = db.components().insertPrivateProject();
db.components().insertSnapshot(project);
ComponentDto file = db.components().insertComponent(newFileDto(project).setDbKey("file-key").setEnabled(false));
- userSession.anonymous().addProjectPermission(UserRole.USER, project);
+ userSession.anonymous().addProjectPermission(USER, project);
insertNclocMetric();
assertThatThrownBy(() -> {
public void fail_if_branch_does_not_exist() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- userSession.addProjectPermission(UserRole.USER, project);
+ userSession.addProjectPermission(USER, project);
db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
assertThatThrownBy(() -> {
@Test
public void fail_when_using_branch_db_key() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
insertNclocMetric();
assertThat(result.getMeasuresList()).extracting(Measure::getComponent).containsOnly(project1.getDbKey());
}
- @Test
- public void do_not_verify_permissions_if_user_is_root() {
- MetricDto metric = db.measures().insertMetric(m -> m.setValueType(FLOAT.name()));
- ComponentDto project1 = db.components().insertPrivateProject();
- db.measures().insertLiveMeasure(project1, metric, m -> m.setValue(15.5d));
-
- userSession.setNonRoot();
- SearchWsResponse result = call(singletonList(project1.getDbKey()), singletonList(metric.getKey()));
- assertThat(result.getMeasuresCount()).isZero();
-
- userSession.setRoot();
- result = call(singletonList(project1.getDbKey()), singletonList(metric.getKey()));
- assertThat(result.getMeasuresCount()).isOne();
- }
-
@Test
public void does_not_return_branch_when_using_db_key() {
MetricDto coverage = db.measures().insertMetric(m -> m.setValueType(FLOAT.name()));
@Test
public void fail_when_user_does_not_have_USER_permission_on_private_project() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().setNonRoot().setNonSystemAdministrator();
+ userSession.logIn().setNonSystemAdministrator();
when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES));
when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES));
@Rule
public final DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public final UserSessionRule userSession = UserSessionRule.standalone();
+ public final UserSessionRule userSession = UserSessionRule.standalone().logIn();
private final ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class);
private final DbClient dbClient = db.getDbClient();
@Test
public void delete_projects() {
- userSession.logIn().setRoot();
+ userSession.addPermission(ADMINISTER);
ComponentDto project1ToDelete = db.components().insertPrivateProject();
ComponentDto project2ToDelete = db.components().insertPrivateProject();
ComponentDto toKeep = db.components().insertPrivateProject();
@Test
public void delete_projects_by_keys() {
- userSession.logIn().setRoot();
+ userSession.addPermission(ADMINISTER);
ComponentDto toDeleteInOrg1 = db.components().insertPrivateProject();
ComponentDto toDeleteInOrg2 = db.components().insertPrivateProject();
ComponentDto toKeep = db.components().insertPrivateProject();
@Test
public void throw_IllegalArgumentException_if_request_without_any_parameters() {
- userSession.logIn().setRoot();
- db.components().insertPrivateProject();
+ userSession.addPermission(ADMINISTER);
+ ComponentDto project = db.components().insertPrivateProject();
try {
TestRequest request = ws.newRequest();
@Test
public void projects_that_dont_exist_are_ignored_and_dont_break_bulk_deletion() {
- userSession.logIn().setRoot();
+ userSession.addPermission(ADMINISTER);
ComponentDto toDelete1 = db.components().insertPrivateProject();
ComponentDto toDelete2 = db.components().insertPrivateProject();
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
+ userSession.anonymous();
TestRequest request = ws.newRequest().setParam("ids", "whatever-the-uuid");
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class)
@Test
public void fail_when_analysis_not_found() {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
assertThatThrownBy(() -> call("A42"))
.isInstanceOf(NotFoundException.class)
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
-import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
+import static org.sonar.api.web.UserRole.ADMIN;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY;
import static org.sonar.test.JsonAssert.assertJson;
ComponentDto project2 = db.components().insertPrivateProject();
ProjectLinkDto link1 = db.componentLinks().insertCustomLink(project1);
ProjectLinkDto link2 = db.componentLinks().insertCustomLink(project2);
- userSession.logIn().setRoot();
+ userSession.addProjectPermission(USER, project1);
+ userSession.addProjectPermission(USER, project2);
SearchWsResponse response = callByKey(project1.getKey());
public void project_administrator_can_search_for_links() {
ComponentDto project = db.components().insertPrivateProject();
ProjectLinkDto link = db.componentLinks().insertCustomLink(project);
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
+ logInAsProjectAdministrator(project);
SearchWsResponse response = callByKey(project.getKey());
public void project_user_can_search_for_links() {
ComponentDto project = db.components().insertPrivateProject();
ProjectLinkDto link = db.componentLinks().insertCustomLink(project);
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
SearchWsResponse response = callByKey(project.getKey());
@Test
public void fail_when_using_branch_db_key() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
assertThatThrownBy(() -> ws.newRequest()
@Test
public void fail_when_using_branch_db_uuid() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
assertThatThrownBy(() -> ws.newRequest()
}
private void logInAsProjectAdministrator(ComponentDto project) {
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
+ userSession.logIn().addProjectPermission(ADMIN, project);
}
private void failIfNotAProjectWithKey(ComponentDto root, ComponentDto component) {
- userSession.logIn().addProjectPermission(UserRole.ADMIN, root);
+ userSession.logIn().addProjectPermission(USER, root);
assertThatThrownBy(() -> ws.newRequest()
.setParam(PARAM_PROJECT_KEY, component.getDbKey())
}
private void failIfNotAProjectWithUuid(ComponentDto root, ComponentDto component) {
- userSession.logIn().addProjectPermission(UserRole.ADMIN, root);
+ userSession.logIn().addProjectPermission(USER, root);
assertThatThrownBy(() -> ws.newRequest()
.setParam(PARAM_PROJECT_ID, component.uuid())
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
-import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import static java.util.Optional.ofNullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.sonar.api.web.UserRole.ADMIN;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newModuleDto;
public class SetActionTest {
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public DbTester db = DbTester.create();
@Before
public void setUp() {
project = db.components().insertPrivateProjectDto();
+ userSession.addProjectPermission(ADMIN, project);
}
@Test
public void reset_tags() {
project = db.components().insertPrivateProjectDto(c -> {
}, p -> p.setTagsString("platform,scanner"));
+ userSession.addProjectPermission(ADMIN, project);
call(project.getKey(), "");
public void override_existing_tags() {
project = db.components().insertPrivateProjectDto(c -> {
}, p -> p.setTagsString("marketing,languages"));
+ userSession.addProjectPermission(ADMIN, project);
call(project.getKey(), "finance,offshore,platform");
@Test
public void set_tags_as_project_admin() {
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
+ userSession.logIn().addProjectPermission(ADMIN, project);
call(project.getKey(), "platform, lambda");
@Test
public void fail_if_not_project_admin() {
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
String projectKey = project.getKey();
assertThatThrownBy(() -> call(projectKey, "platform"))
@Test
public void fail_when_using_branch_db_key() {
ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
+ userSession.logIn().addProjectPermission(USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
String branchDbKey = branch.getDbKey();
.doesNotContain(project2.name());
}
- @Test
- public void root_user() {
- QualityGateDto qualityGate = db.qualityGates().insertQualityGate();
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().setRoot();
-
- SearchResponse response = ws.newRequest()
- .setParam(PARAM_GATE_ID, valueOf(qualityGate.getUuid()))
- .setParam(PARAM_SELECTED, ALL.value())
- .executeProtobuf(SearchResponse.class);
-
- assertThat(response.getResultsList())
- .extracting(Result::getName)
- .containsExactlyInAnyOrder(project.name());
- }
-
@Test
public void test_paging() {
QualityGateDto qualityGate = db.qualityGates().insertQualityGate();
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.Optional;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
+import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.QProfileDto;
public class QProfilesWsMediumTest {
@Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone()
- .logIn().setRoot();
+ public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn();
@Rule
public EsTester es = EsTester.create();
@Rule
private final WsActionTester wsActivateRule = new WsActionTester(new ActivateRuleAction(dbClient, qProfileRules, userSessionRule, qProfileWsSupport));
private final WsActionTester wsActivateRules = new WsActionTester(new ActivateRulesAction(ruleQueryFactory, userSessionRule, qProfileRules, qProfileWsSupport, dbClient));
+ @Before
+ public void before(){
+ userSessionRule.logIn().setSystemAdministrator();
+ userSessionRule.addPermission(GlobalPermission.ADMINISTER);
+ userSessionRule.addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
+ }
+
@Test
public void deactivate_rule() {
QProfileDto profile = createProfile("java");
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.junit.Test;
-import org.sonar.core.platform.ListContainer;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class RootsWsModuleTest {
- private RootWsModule underTest = new RootWsModule();
-
- @Test
- public void verify_number_of_components_added_by_module() {
- ListContainer container = new ListContainer();
- underTest.configure(container);
- assertThat(container.getAddedObjects()).hasSize(4);
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import org.junit.Test;
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class RootsWsTest {
- private RootsWs underTest = new RootsWs(new DummyRootsWsAction());
-
- @Test
- public void verify_definition() {
- WebService.Context context = new WebService.Context();
-
- underTest.define(context);
-
- assertThat(context.controllers()).hasSize(1);
- WebService.Controller controller = context.controller("api/roots");
- assertThat(controller.description()).isEqualTo("Manage root users");
- assertThat(controller.since()).isEqualTo("6.2");
- }
-
- private static class DummyRootsWsAction implements RootsWsAction {
- @Override
- public void define(WebService.NewController context) {
- context.createAction("ooo").setHandler(this);
- }
-
- @Override
- public void handle(Request request, Response response) {
-
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import java.util.List;
-import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.user.UserDao;
-import org.sonar.db.user.UserDto;
-import org.sonar.db.user.UserTesting;
-import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.ws.TestResponse;
-import org.sonar.server.ws.WsActionTester;
-import org.sonarqube.ws.MediaTypes;
-import org.sonarqube.ws.Roots;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.sonar.test.JsonAssert.assertJson;
-
-public class SearchActionTest {
-
- @Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
-
- private UserDao userDao = dbTester.getDbClient().userDao();
- private DbSession dbSession = dbTester.getSession();
- private SearchAction underTest = new SearchAction(userSessionRule, dbTester.getDbClient());
- private WsActionTester wsTester = new WsActionTester(underTest);
-
- @Test
- public void verify_definition() {
- WebService.Action action = wsTester.getDef();
- assertThat(action.key()).isEqualTo("search");
- assertThat(action.isInternal()).isTrue();
- assertThat(action.isPost()).isFalse();
- assertThat(action.since()).isEqualTo("6.2");
- assertThat(action.description()).isEqualTo("Search for root users.<br/>" +
- "Requires to be root.");
- assertThat(action.responseExample()).isNotNull();
- assertThat(action.deprecatedKey()).isNull();
- assertThat(action.deprecatedSince()).isNull();
- assertThat(action.handler()).isSameAs(underTest);
- assertThat(action.params()).isEmpty();
- }
-
- @Test
- public void execute_fails_with_ForbiddenException_when_user_is_not_logged_in() {
- expectInsufficientPrivilegesForbiddenException(() -> executeRequest());
- }
-
- @Test
- public void execute_fails_with_ForbiddenException_when_user_is_not_root() {
- userSessionRule.logIn().setNonRoot();
-
- expectInsufficientPrivilegesForbiddenException(() -> executeRequest());
- }
-
- @Test
- public void execute_returns_empty_list_of_root_when_DB_is_empty() {
- logInAsRoot();
-
- assertThat(executeRequest()).isEmpty();
- }
-
- @Test
- public void test_response_example() {
- logInAsRoot();
- UserDto user = UserTesting.newUserDto().setLogin("daniel").setName("Daniel").setEmail("daniel@corp.com");
- UserDto rootDto = userDao.insert(dbSession, user);
- userDao.setRoot(dbSession, rootDto.getLogin(), true);
- dbSession.commit();
-
- TestResponse response = wsTester.newRequest().setMediaType(MediaTypes.JSON).execute();
- assertJson(response.getInput()).isSimilarTo(wsTester.getDef().responseExampleAsString());
- }
-
- @Test
- public void execute_succeeds_when_root_user_has_neither_email_nor_name() {
- logInAsRoot();
- UserDto rootDto = userDao.insert(dbSession, UserTesting.newUserDto().setName(null).setEmail(null));
- userDao.setRoot(dbSession, rootDto.getLogin(), true);
- dbSession.commit();
-
- List<Roots.RootContent> roots = executeRequest();
- assertThat(roots).hasSize(1);
- Roots.RootContent root = roots.iterator().next();
- assertThat(root.getLogin()).isEqualTo(rootDto.getLogin());
- assertThat(root.hasName()).isFalse();
- assertThat(root.hasEmail()).isFalse();
- }
-
- @Test
- public void execute_returns_root_users_sorted_by_name() {
- logInAsRoot();
- userDao.insert(dbSession, UserTesting.newUserDto().setName("ddd"));
- UserDto root1 = userDao.insert(dbSession, UserTesting.newUserDto().setName("ccc"));
- userDao.setRoot(dbSession, root1.getLogin(), true);
- UserDto root2 = userDao.insert(dbSession, UserTesting.newUserDto().setName("bbb"));
- userDao.setRoot(dbSession, root2.getLogin(), true);
- userDao.insert(dbSession, UserTesting.newUserDto().setName("aaa"));
- dbSession.commit();
-
- assertThat(executeRequest())
- .extracting(Roots.RootContent::getName)
- .containsExactly("bbb", "ccc");
- }
-
- private UserSessionRule logInAsRoot() {
- return userSessionRule.logIn().setRoot();
- }
-
- private List<Roots.RootContent> executeRequest() {
- return wsTester.newRequest()
- .executeProtobuf(Roots.SearchResponse.class)
- .getRootsList();
- }
-
- private void expectInsufficientPrivilegesForbiddenException(ThrowingCallable callback) {
- assertThatThrownBy(callback)
- .isInstanceOf(ForbiddenException.class)
- .hasMessage("Insufficient privileges");
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import javax.annotation.Nullable;
-import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.user.UserDao;
-import org.sonar.db.user.UserDto;
-import org.sonar.db.user.UserTesting;
-import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.ws.TestRequest;
-import org.sonar.server.ws.WsActionTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-public class SetRootActionTest {
- private static final String SOME_LOGIN = "johndoe";
-
- @Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
-
- private UserDao userDao = dbTester.getDbClient().userDao();
- private DbSession dbSession = dbTester.getSession();
- private SetRootAction underTest = new SetRootAction(userSessionRule, dbTester.getDbClient());
- private WsActionTester wsTester = new WsActionTester(underTest);
-
- @Test
- public void verify_definition() {
- WebService.Action action = wsTester.getDef();
- assertThat(action.key()).isEqualTo("set_root");
- assertThat(action.isInternal()).isTrue();
- assertThat(action.isPost()).isTrue();
- assertThat(action.since()).isEqualTo("6.2");
- assertThat(action.description()).isEqualTo("Make the specified user root.<br/>" +
- "Requires to be root.");
- assertThat(action.responseExample()).isNull();
- assertThat(action.deprecatedKey()).isNull();
- assertThat(action.deprecatedSince()).isNull();
- assertThat(action.handler()).isSameAs(underTest);
- assertThat(action.params()).hasSize(1);
-
- WebService.Param param = action.param("login");
- assertThat(param.isRequired()).isTrue();
- assertThat(param.description()).isEqualTo("A user login");
- assertThat(param.defaultValue()).isNull();
- assertThat(param.deprecatedSince()).isNull();
- assertThat(param.deprecatedKey()).isNull();
- assertThat(param.exampleValue()).isEqualTo("admin");
- }
-
- @Test
- public void execute_fails_with_ForbiddenException_when_user_is_not_logged_in() {
- expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN));
- }
-
- @Test
- public void execute_fails_with_ForbiddenException_when_user_is_not_root() {
- userSessionRule.logIn().setNonRoot();
-
- expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN));
- }
-
- @Test
- public void execute_fails_with_IAE_when_login_param_is_not_provided() {
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest(null))
- .isInstanceOf(IllegalArgumentException.class)
- .hasMessage("The 'login' parameter is missing");
- }
-
- @Test
- public void execute_makes_user_with_specified_login_root_when_it_is_not() {
- UserDto otherUser = UserTesting.newUserDto();
- userDao.insert(dbSession, otherUser);
- userDao.insert(dbSession, UserTesting.newUserDto(SOME_LOGIN, "name", "email"));
- dbSession.commit();
- logInAsRoot();
-
- executeRequest(SOME_LOGIN);
-
- assertThat(userDao.selectByLogin(dbSession, SOME_LOGIN).isRoot()).isTrue();
- assertThat(userDao.selectByLogin(dbSession, otherUser.getLogin()).isRoot()).isFalse();
- }
-
- @Test
- public void execute_has_no_effect_when_user_is_already_root() {
- UserDto otherUser = UserTesting.newUserDto();
- userDao.insert(dbSession, otherUser);
- userDao.insert(dbSession, UserTesting.newUserDto(SOME_LOGIN, "name", "email"));
- userDao.setRoot(dbSession, SOME_LOGIN, true);
- dbSession.commit();
- logInAsRoot();
-
- executeRequest(SOME_LOGIN);
-
- assertThat(userDao.selectByLogin(dbSession, SOME_LOGIN).isRoot()).isTrue();
- assertThat(userDao.selectByLogin(dbSession, otherUser.getLogin()).isRoot()).isFalse();
- }
-
- @Test
- public void execute_fails_with_NotFoundException_when_user_for_specified_login_does_not_exist() {
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest("foo_bar"))
- .isInstanceOf(NotFoundException.class)
- .hasMessage("User with login 'foo_bar' not found");
- }
-
- @Test
- public void execute_fails_with_NotFoundException_when_user_for_specified_login_is_not_active() {
- UserDto userDto = UserTesting.newUserDto().setActive(false);
- userDao.insert(dbSession, userDto);
- dbSession.commit();
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest(userDto.getLogin()))
- .isInstanceOf(NotFoundException.class)
- .hasMessage("User with login '" + userDto.getLogin() + "' not found");
- }
-
- private void logInAsRoot() {
- userSessionRule.logIn().setRoot();
- }
-
- private void expectInsufficientPrivilegesForbiddenException(ThrowingCallable callback) {
- assertThatThrownBy(callback)
- .isInstanceOf(ForbiddenException.class)
- .hasMessage("Insufficient privileges");
- }
-
- private int executeRequest(@Nullable String login) {
- TestRequest request = wsTester.newRequest();
- if (login != null) {
- request.setParam("login", login);
- }
- return request
- .execute()
- .getStatus();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.root.ws;
-
-import javax.annotation.Nullable;
-import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.user.UserDao;
-import org.sonar.db.user.UserDto;
-import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.ws.TestRequest;
-import org.sonar.server.ws.WsActionTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.sonar.db.user.UserTesting.newUserDto;
-
-public class UnsetRootActionTest {
- private static final String SOME_LOGIN = "johndoe";
-
- @Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
-
- private UserDao userDao = dbTester.getDbClient().userDao();
- private DbSession dbSession = dbTester.getSession();
- private UnsetRootAction underTest = new UnsetRootAction(userSessionRule, dbTester.getDbClient());
- private WsActionTester wsTester = new WsActionTester(underTest);
-
- @Test
- public void verify_definition() {
- WebService.Action action = wsTester.getDef();
- assertThat(action.key()).isEqualTo("unset_root");
- assertThat(action.isInternal()).isTrue();
- assertThat(action.isPost()).isTrue();
- assertThat(action.since()).isEqualTo("6.2");
- assertThat(action.description()).isEqualTo("Make the specified user not root.<br/>" +
- "Requires to be root.");
- assertThat(action.responseExample()).isNull();
- assertThat(action.deprecatedKey()).isNull();
- assertThat(action.deprecatedSince()).isNull();
- assertThat(action.handler()).isSameAs(underTest);
- assertThat(action.params()).hasSize(1);
-
- WebService.Param param = action.param("login");
- assertThat(param.isRequired()).isTrue();
- assertThat(param.description()).isEqualTo("A user login");
- assertThat(param.defaultValue()).isNull();
- assertThat(param.deprecatedSince()).isNull();
- assertThat(param.deprecatedKey()).isNull();
- assertThat(param.exampleValue()).isEqualTo("admin");
- }
-
- @Test
- public void execute_fails_with_ForbiddenException_when_user_is_not_logged_in() {
- expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN));
- }
-
- @Test
- public void execute_fails_with_ForbiddenException_when_user_is_not_root() {
- userSessionRule.logIn().setNonRoot();
-
- expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN));
- }
-
- @Test
- public void execute_fails_with_IAE_when_login_param_is_not_provided() {
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest(null))
- .isInstanceOf(IllegalArgumentException.class)
- .hasMessage("The 'login' parameter is missing");
- }
-
- @Test
- public void execute_makes_user_with_specified_login_not_root_when_it_is() {
- UserDto otherUser = insertRootUser(newUserDto());
- insertRootUser(newUserDto(SOME_LOGIN, "name", "email"));
- logInAsRoot();
-
- executeRequest(SOME_LOGIN);
-
- assertThat(userDao.selectByLogin(dbSession, SOME_LOGIN).isRoot()).isFalse();
- assertThat(userDao.selectByLogin(dbSession, otherUser.getLogin()).isRoot()).isTrue();
- }
-
- @Test
- public void execute_has_no_effect_when_user_is_already_not_root() {
- UserDto otherUser = insertRootUser(newUserDto());
- insertNonRootUser(newUserDto(SOME_LOGIN, "name", "email"));
- logInAsRoot();
-
- executeRequest(SOME_LOGIN);
-
- assertThat(userDao.selectByLogin(dbSession, SOME_LOGIN).isRoot()).isFalse();
- assertThat(userDao.selectByLogin(dbSession, otherUser.getLogin()).isRoot()).isTrue();
- }
-
- @Test
- public void execute_fails_with_BadRequestException_when_attempting_to_unset_root_on_last_root_user() {
- insertRootUser(newUserDto(SOME_LOGIN, "name", "email"));
- insertNonRootUser(newUserDto());
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest(SOME_LOGIN))
- .isInstanceOf(BadRequestException.class)
- .hasMessage("Last root can't be unset");
- }
-
- @Test
- public void execute_fails_with_BadRequestException_when_attempting_to_unset_non_root_and_there_is_no_root_at_all() {
- UserDto userDto1 = newUserDto(SOME_LOGIN, "name", "email");
- insertNonRootUser(userDto1);
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest(userDto1.getLogin()))
- .isInstanceOf(BadRequestException.class)
- .hasMessage("Last root can't be unset");
- }
-
- @Test
- public void execute_fails_with_NotFoundException_when_user_for_specified_login_does_not_exist() {
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest("bar_foo"))
- .isInstanceOf(NotFoundException.class)
- .hasMessage("User with login 'bar_foo' not found");
- }
-
- @Test
- public void execute_fails_with_NotFoundException_when_user_for_specified_login_is_inactive() {
- UserDto userDto = insertRootUser(newUserDto().setActive(false));
- logInAsRoot();
-
- assertThatThrownBy(() -> executeRequest(userDto.getLogin()))
- .isInstanceOf(NotFoundException.class)
- .hasMessage("User with login '" + userDto.getLogin() + "' not found");
- }
-
- private UserDto insertNonRootUser(UserDto dto) {
- userDao.insert(dbSession, dto);
- dbSession.commit();
- return dto;
- }
-
- private UserDto insertRootUser(UserDto dto) {
- insertNonRootUser(dto);
- userDao.setRoot(dbSession, dto.getLogin(), true);
- dbSession.commit();
- return dto;
- }
-
- private void logInAsRoot() {
- userSessionRule.logIn().setRoot();
- }
-
- private void expectInsufficientPrivilegesForbiddenException(ThrowingCallable callback) {
- assertThatThrownBy(callback)
- .isInstanceOf(ForbiddenException.class)
- .hasMessage("Insufficient privileges");
-
- }
-
- private int executeRequest(@Nullable String login) {
- TestRequest request = wsTester.newRequest();
- if (login != null) {
- request.setParam("login", login);
- }
- return request
- .execute()
- .getStatus();
- }
-
-}
@Test
public void fail_when_qualifier_not_included() {
- userSession.logIn().setRoot();
+ userSession.logIn().addProjectPermission(ADMIN, project);
definitions.addComponent(PropertyDefinition.builder("foo")
.onQualifiers(VIEW)
.build());
@Test
public void fail_to_reset_setting_component_when_setting_is_global() {
- userSession.logIn().setRoot();
+ userSession.logIn().addProjectPermission(ADMIN, project);
definitions.addComponent(PropertyDefinition.builder("foo").build());
i18n.put("qualifier." + PROJECT, "project");
assertJson(call()).isSimilarTo("{\"needIssueSync\": false}");
}
- @Test
- public void can_admin_on_global_level() {
- init();
- userSession.logIn().setRoot();
-
- assertJson(call()).isSimilarTo("{\"canAdmin\":true}");
- }
-
@Test
public void regulatory_report_feature_enabled_ee_dce() {
init();
@Test
public void standalone_flag() {
init();
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
when(webServer.isStandalone()).thenReturn(true);
assertJson(call()).isSimilarTo("{\"standalone\":true}");
@Test
public void not_standalone_flag() {
init();
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
when(webServer.isStandalone()).thenReturn(false);
assertJson(call()).isSimilarTo("{\"standalone\":false}");
// exists in db
Optional<UserDto> dbUser = db.users().selectUserByLogin("john");
assertThat(dbUser).isPresent();
- assertThat(dbUser.get().isRoot()).isFalse();
// member of default group
assertThat(db.users().selectGroupUuidsOfUser(dbUser.get())).containsOnly(defaultGroup.getUuid());
.build());
assertThat(db.users().selectUserByLogin("john").get())
- .extracting(UserDto::isLocal, UserDto::getExternalIdentityProvider, UserDto::getExternalLogin, UserDto::isRoot)
- .containsOnly(true, "sonarqube", "john", false);
+ .extracting(UserDto::isLocal, UserDto::getExternalIdentityProvider, UserDto::getExternalLogin)
+ .containsOnly(true, "sonarqube", "john");
}
@Test
.build());
assertThat(db.users().selectUserByLogin("john").get())
- .extracting(UserDto::isLocal, UserDto::getExternalIdentityProvider, UserDto::getExternalLogin, UserDto::isRoot)
- .containsOnly(false, "sonarqube", "john", false);
+ .extracting(UserDto::isLocal, UserDto::getExternalIdentityProvider, UserDto::getExternalLogin)
+ .containsOnly(false, "sonarqube", "john");
}
@Test
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.db.DbTester;
+import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
private static final String USER_LOGIN = "john";
-
@Rule
public DbTester db = DbTester.create();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn().addPermission(GlobalPermission.ADMINISTER);
private WsActionTester ws = new WsActionTester(new GroupsAction(db.getDbClient(), userSession,
new DefaultGroupFinder(db.getDbClient())));
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.qualityprofile.ws.QProfilesWsModule;
-import org.sonar.server.root.ws.RootWsModule;
import org.sonar.server.rule.CommonRuleDefinitionsImpl;
import org.sonar.server.rule.RuleCreator;
import org.sonar.server.rule.RuleDefinitionsLoader;
// UI
new NavigationWsModule(),
- // root
- new RootWsModule(),
-
// webhooks
WebhookQGChangeEventListener.class,
new WebhookModule(),