throw notImplemented();
}
- @Override
- public UserSession checkIsRoot() {
- throw notImplemented();
- }
-
@Override
public UserSession checkLoggedIn() {
throw notImplemented();
userSession.checkLoggedIn();
if (request.getComponentId() == null) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
} else {
userSession.checkComponentUuidPermission(UserRole.ADMIN, request.getComponentId());
}
if (component.isPresent()) {
userSession.checkComponentPermission(UserRole.ADMIN, component.get());
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
}
}
@Override
public void handle(Request wsRequest, Response wsResponse) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
String taskId = wsRequest.mandatoryParam(PARAM_TASK_ID);
queue.cancel(taskId);
wsResponse.noContent();
@Override
public void handle(Request wsRequest, Response wsResponse) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
queue.cancelAll();
wsResponse.noContent();
}
}
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
}
}
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
try {
emailNotificationChannel.sendTestEmail(request.mandatoryParam(PARAM_TO), request.param(PARAM_SUBJECT), request.mandatoryParam(PARAM_MESSAGE));
} catch (EmailException emailException) {
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
try (DbSession dbSession = dbClient.openSession(true)) {
writeProtobuf(doHandle(dbSession), request, response);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
String key = request.mandatoryParam(PARAM_KEY);
try (DbSession dbSession = dbClient.openSession(false)) {
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
try (DbSession dbSession = dbClient.openSession(false)) {
List<Integer> ids = loadIds(dbSession, request);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
int id = request.mandatoryParamAsInt(PARAM_ID);
try (DbSession dbSession = dbClient.openSession(false)) {
if (settings.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_ANYONE_CAN_CREATE)) {
userSession.checkLoggedIn();
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
}
String name = wsSupport.getAndCheckMandatoryName(request);
key);
if (organizationDto.isGuarded()) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
} else {
userSession.checkOrganizationPermission(organizationDto.getUuid(), SYSTEM_ADMIN);
}
ComponentDto project = wsSupport.getRootComponentOrModule(dbSession, projectRef.get());
PermissionPrivilegeChecker.checkProjectAdmin(userSession, project.getOrganizationUuid(), Optional.of(new ProjectId(project)));
} else {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
}
}
@Override
public void handle(Request wsRequest, Response wsResponse) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
LoggerLevel level = LoggerLevel.valueOf(wsRequest.mandatoryParam(PARAM_LEVEL));
db.enableSqlLogging(level.equals(LoggerLevel.TRACE));
@Override
public void handle(Request request, Response response) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
JsonWriter json = response.newJsonWriter();
writeJson(json);
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
String processKey = wsRequest.mandatoryParam(PROCESS_PROPERTY);
ProcessId processId = ProcessId.fromKey(processKey);
restartFlagHolder.unset();
}
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
LOGGER.info("SonarQube restart requested by {}", userSession.getLogin());
restartFlagHolder.set();
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
JsonWriter jsonWriter = response.newJsonWriter();
jsonWriter.beginObject();
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
pluginDownloader.cancelDownloads();
pluginRepository.cancelUninstalls();
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
String key = request.mandatoryParam(PARAM_KEY);
PluginUpdate pluginUpdate = findAvailablePluginByKey(key);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
Collection<PluginInfo> pluginInfoList = searchPluginInfoList();
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
ImmutableMap<String, Plugin> compatiblePluginsByKey = compatiblePluginsByKey(updateCenterMatrixFactory);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
String key = request.mandatoryParam(PARAM_KEY);
ensurePluginIsInstalled(key);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
String key = request.mandatoryParam(PARAM_KEY);
PluginUpdate pluginUpdate = findPluginUpdateByKey(key);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
JsonWriter jsonWriter = response.newJsonWriter();
jsonWriter.beginObject();
private Optional<OrganizationDto> loadOrganizationByKey(DbSession dbSession, @Nullable String orgKey) {
if (orgKey == null) {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
return Optional.empty();
}
OrganizationDto org = support.getOrganization(dbSession, orgKey);
}
public QualityGateDto rename(long idToRename, String name) {
- checkRoot();
+ checkIsSystemAdministrator();
QualityGateDto toRename = getNonNullQgate(idToRename);
validateQualityGate(idToRename, name);
toRename.setName(name);
}
public QualityGateDto copy(long sourceId, String destinationName) {
- checkRoot();
+ checkIsSystemAdministrator();
getNonNullQgate(sourceId);
validateQualityGate(null, destinationName);
QualityGateDto destinationGate = new QualityGateDto().setName(destinationName);
}
public void delete(long idToDelete) {
- checkRoot();
+ checkIsSystemAdministrator();
QualityGateDto qGate = getNonNullQgate(idToDelete);
DbSession session = dbClient.openSession(false);
try {
}
public void setDefault(DbSession dbSession, @Nullable Long idToUseAsDefault) {
- checkRoot();
+ checkIsSystemAdministrator();
if (idToUseAsDefault == null) {
propertiesDao.deleteGlobalProperty(SONAR_QUALITYGATE_PROPERTY, dbSession);
} else {
}
public void deleteCondition(Long condId) {
- checkRoot();
+ checkIsSystemAdministrator();
conditionDao.delete(getNonNullCondition(condId));
}
errors.check(isModifyingCurrentQgate || existingQgate == null, Validation.IS_ALREADY_USED_MESSAGE, "Name");
}
- private void checkRoot() {
- userSession.checkIsRoot();
+ private void checkIsSystemAdministrator() {
+ userSession.checkIsSystemAdministrator();
}
private void checkProjectAdmin(ComponentDto project) {
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.WsRoot;
+import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchAction implements RootsWsAction {
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ checkIsRoot();
try (DbSession dbSession = dbClient.openSession(false)) {
List<UserDto> userDtos = dbClient.userDao().selectUsers(
}
return builder.build();
}
+
+ private void checkIsRoot() {
+ if (!userSession.isRoot()) {
+ throw insufficientPrivilegesException();
+ }
+ }
+
+
}
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
+import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
public class SetRootAction implements RootsWsAction {
private static final String PARAM_LOGIN = "login";
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ checkIsRoot();
String login = request.mandatoryParam(PARAM_LOGIN);
try (DbSession dbSession = dbClient.openSession(false)) {
}
response.noContent();
}
+
+ private void checkIsRoot() {
+ if (!userSession.isRoot()) {
+ throw insufficientPrivilegesException();
+ }
+ }
}
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
+import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
public class UnsetRootAction implements RootsWsAction {
private static final String PARAM_LOGIN = "login";
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ checkIsRoot();
String login = request.mandatoryParam(PARAM_LOGIN);
try (DbSession dbSession = dbClient.openSession(false)) {
}
response.noContent();
}
+
+ private void checkIsRoot() {
+ if (!userSession.isRoot()) {
+ throw insufficientPrivilegesException();
+ }
+ }
}
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
try (DbSession dbSession = dbClient.openSession(true)) {
writeProtobuf(doHandle(dbSession, toGenerateRequest(request)), request, response);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
try (DbSession dbSession = dbClient.openSession(true)) {
Map<String, PropertyDto> properties = dbClient.propertiesDao().selectGlobalPropertiesByKeys(dbSession, SETTINGS_KEYS).stream()
.collect(Collectors.uniqueIndex(PropertyDto::getKey, Function.identity()));
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
writeProtobuf(CheckSecretKeyWsResponse.newBuilder().setSecretKeyAvailable(settings.getEncryption().hasSecretKey()).build(), request, response);
}
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
String value = request.mandatoryParam(PARAM_VALUE);
checkRequest(!value.isEmpty(), "Parameter '%s' must not be empty", PARAM_VALUE);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
writeProtobuf(GenerateSecretKeyWsResponse.newBuilder().setSecretKey(settings.getEncryption().generateRandomSecretKey()).build(), request, response);
}
if (component.isPresent()) {
userSession.checkComponentPermission(UserRole.ADMIN, component.get());
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
}
}
}
if (component.isPresent()) {
userSession.checkComponentPermission(UserRole.ADMIN, component.get());
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
}
}
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
Part part = request.mandatoryParamAsPart(PARAM_FILE);
String fileName = part.getFileName();
return this;
}
- @Override
- public final UserSession checkIsRoot() {
- if (!isRoot()) {
- throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE);
- }
- return this;
- }
-
@Override
public final boolean hasOrganizationPermission(String organizationUuid, String permission) {
return isRoot() || hasOrganizationPermissionImpl(organizationUuid, permission);
return get().isRoot();
}
- @Override
- public UserSession checkIsRoot() {
- get().checkIsRoot();
- return this;
- }
-
@Override
public UserSession checkLoggedIn() {
get().checkLoggedIn();
boolean isLoggedIn();
/**
- * Whether the user has root privileges when organizations are enabled.
- * Always returns {@code false} when organizations are disabled.
+ * Whether the user has root privileges. If {@code true}, then user automatically
+ * benefits from all the permissions on all organizations and projects.
*/
boolean isRoot();
- /**
- * Ensures that user is root otherwise throws {@link org.sonar.server.exceptions.ForbiddenException}.
- */
- UserSession checkIsRoot();
-
/**
* Ensures that user is logged in otherwise throws {@link org.sonar.server.exceptions.UnauthorizedException}.
*/
UserSession checkComponentUuidPermission(String permission, String componentUuid);
/**
- * Whether user can administrate system, for example to use cross-organizations services
+ * Whether user can administrate system, for example for using cross-organizations services
* like update center, system info or management of users.
*
* Returns {@code true} if:
String previousPassword = request.mandatoryParam(PARAM_PREVIOUS_PASSWORD);
checkCurrentPassword(dbSession, login, previousPassword);
} else {
- userSession.checkIsRoot();
+ userSession.checkIsSystemAdministrator();
}
String password = request.mandatoryParam(PARAM_PASSWORD);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
writeProtobuf(doHandle(toWsRequest(request)), request, response);
}
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
String login = request.mandatoryParam(PARAM_LOGIN);
checkRequest(!login.equals(userSession.getLogin()), "Self-deactivation is not possible");
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
String login = request.mandatoryParam(PARAM_LOGIN);
int pageSize = request.mandatoryParamAsInt(Param.PAGE_SIZE);
@Override
public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsRoot();
+ userSession.checkLoggedIn().checkIsSystemAdministrator();
UpdateRequest updateRequest = toWsRequest(request);
try (DbSession dbSession = dbClient.openSession(false)) {
doHandle(dbSession, toWsRequest(request));
@Test
public void get_all_past_activity() {
- logInAsRoot();
+ logInAsSystemAdministrator();
OrganizationDto org1 = dbTester.organizations().insert();
dbTester.components().insertProject(org1, "PROJECT_1");
OrganizationDto org2 = dbTester.organizations().insert();
@Test
public void filter_by_status() {
- logInAsRoot();
+ logInAsSystemAdministrator();
dbTester.components().insertProject(dbTester.getDefaultOrganization(), "PROJECT_1");
dbTester.components().insertProject(dbTester.getDefaultOrganization(), "PROJECT_2");
insertActivity("T1", "PROJECT_1", CeActivityDto.Status.SUCCESS);
@Test
public void filter_by_max_executed_at_exclude() {
- logInAsRoot();
+ logInAsSystemAdministrator();
insertActivity("T1", "PROJECT_1", CeActivityDto.Status.SUCCESS);
insertActivity("T2", "PROJECT_2", CeActivityDto.Status.FAILED);
insertQueue("T3", "PROJECT_1", CeQueueDto.Status.IN_PROGRESS);
@Test
public void filter_by_min_submitted_and_max_executed_at_include_day() {
- logInAsRoot();
+ logInAsSystemAdministrator();
OrganizationDto organizationDto = dbTester.organizations().insert();
dbTester.components().insertProject(organizationDto, "PROJECT_1");
insertActivity("T1", "PROJECT_1", CeActivityDto.Status.SUCCESS);
@Test
public void filter_on_current_activities() {
dbTester.components().insertProject(dbTester.organizations().insert(), "PROJECT_1");
- logInAsRoot();
+ logInAsSystemAdministrator();
// T2 is the current activity (the most recent one)
insertActivity("T1", "PROJECT_1", CeActivityDto.Status.SUCCESS);
insertActivity("T2", "PROJECT_1", CeActivityDto.Status.FAILED);
@Test
public void limit_results() {
- logInAsRoot();
+ logInAsSystemAdministrator();
OrganizationDto organizationDto = dbTester.organizations().insert();
dbTester.components().insertProject(organizationDto, "PROJECT_1");
dbTester.components().insertProject(organizationDto, "PROJECT_2");
dbTester.components().insertProjectAndSnapshot(struts);
dbTester.components().insertProjectAndSnapshot(zookeeper);
dbTester.components().insertProjectAndSnapshot(eclipse);
- logInAsRoot();
+ logInAsSystemAdministrator();
insertActivity("T1", "P1", CeActivityDto.Status.SUCCESS);
insertActivity("T2", "P2", CeActivityDto.Status.SUCCESS);
insertActivity("T3", "P3", CeActivityDto.Status.SUCCESS);
ComponentDto developer = newDeveloper(organizationDto, "Apache Developer").setUuid("D1").setProjectUuid("D1");
dbTester.components().insertDeveloperAndSnapshot(developer);
dbTester.components().insertViewAndSnapshot(apacheView);
- logInAsRoot();
+ logInAsSystemAdministrator();
insertActivity("T1", "D1", CeActivityDto.Status.SUCCESS);
insertActivity("T2", "V1", CeActivityDto.Status.SUCCESS);
@Test
public void search_task_id_in_queue_ignoring_other_parameters() throws IOException {
- logInAsRoot();
+ logInAsSystemAdministrator();
dbTester.components().insertProject(dbTester.getDefaultOrganization(), "PROJECT_1");
insertQueue("T1", "PROJECT_1", CeQueueDto.Status.IN_PROGRESS);
@Test
public void search_task_id_in_activity() {
- logInAsRoot();
+ logInAsSystemAdministrator();
dbTester.components().insertProject(dbTester.getDefaultOrganization(), "PROJECT_1");
insertActivity("T1", "PROJECT_1", CeActivityDto.Status.SUCCESS);
@Test
public void search_task_by_component_id() {
- dbTester.components().insertProject(dbTester.getDefaultOrganization(), "PROJECT_1");
+ ComponentDto project = dbTester.components().insertProject(dbTester.getDefaultOrganization(), "PROJECT_1");
insertQueue("T1", "PROJECT_1", CeQueueDto.Status.IN_PROGRESS);
insertActivity("T1", "PROJECT_1", CeActivityDto.Status.SUCCESS);
- logInAsRoot();
+ userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
ActivityResponse result = call(ws.newRequest()
.setParam(PARAM_COMPONENT_ID, "PROJECT_1")
@Test
public void fail_if_date_is_not_well_formatted() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Date 'ill-formatted-date' cannot be parsed as either a date or date+time");
@Test
public void support_json_response() {
- logInAsRoot();
+ logInAsSystemAdministrator();
TestResponse wsResponse = ws.newRequest()
.setMediaType(MediaTypes.JSON)
.execute();
JsonAssert.assertJson(wsResponse.getInput()).isSimilarTo("{\"tasks\":[]}");
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private CeQueueDto insertQueue(String taskUuid, String componentUuid, CeQueueDto.Status status) {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Test
public void cancel_pending_task() {
- userSession.logIn().setRoot();
+ logInAsSystemAdministrator();
tester.newRequest()
.setParam("id", "T1")
@Test
public void throw_IllegalArgumentException_if_missing_id() {
- userSession.logIn().setRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'id' parameter is missing");
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
verifyZeroInteractions(queue);
}
+
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
+ }
}
@Test
public void cancel_all_pending_tasks() {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
call();
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
}
@Test
- public void getting_global_queue_task_requires_root_permission() {
- userSession.logIn().setRoot();
+ public void getting_global_queue_task_requires_to_be_system_administrator() {
+ logInAsSystemAdministrator();
CeQueueDto task = createAndPersistQueueTask(null);
call(task.getUuid());
}
@Test
- public void getting_global_queue_throws_ForbiddenException_if_not_root() {
- userSession.logIn().setNonRoot();
+ public void getting_global_queue_throws_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
CeQueueDto task = createAndPersistQueueTask(null);
expectedException.expect(ForbiddenException.class);
}
@Test
- public void getting_global_archived_task_requires_root_permission() {
- userSession.logIn().setRoot();
+ public void getting_global_archived_task_requires_to_be_system_administrator() {
+ logInAsSystemAdministrator();
CeActivityDto task = createAndPersistArchivedTask(null);
call(task.getUuid());
}
@Test
- public void getting_global_archived_throws_ForbiddenException_if_not_root() {
- userSession.logIn().setNonRoot();
+ public void getting_global_archived_throws_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
CeActivityDto task = createAndPersistArchivedTask(null);
expectedException.expect(ForbiddenException.class);
dbTester.commit();
}
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
+ }
+
private void logInAsRoot() {
userSession.logIn().setRoot();
}
dbSession.commit();
- userSession.logIn("john").addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
underTest.updateKey(dbSession, project, "sample2:root");
dbSession.commit();
ComponentDto file = ComponentTesting.newFileDto(module, null).setKey("sample:root:module:src/File.xoo");
dbClient.componentDao().insert(dbSession, file);
dbSession.commit();
- userSession.logIn("john").addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
underTest.updateKey(dbSession, module, "sample:root2:module");
dbSession.commit();
dbSession.commit();
- userSession.logIn("john").addProjectUuidPermissions(UserRole.ADMIN, provisionedProject.uuid());
+ logInAsProjectAdministrator(provisionedProject);
underTest.updateKey(dbSession, provisionedProject, "provisionedProject2");
dbSession.commit();
@Test
public void fail_if_old_key_and_new_key_are_the_same() {
- logInAsRoot();
ComponentDto project = insertSampleRootProject();
ComponentDto anotherProject = componentDb.insertProject();
+ logInAsProjectAdministrator(project);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Impossible to update key: a component with key \"" + anotherProject.key() + "\" already exists.");
@Test
public void fail_if_new_key_is_empty() {
- logInAsRoot();
ComponentDto project = insertSampleRootProject();
+ logInAsProjectAdministrator(project);
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Malformed key for ''. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
@Test
public void fail_if_new_key_is_not_formatted_correctly() {
- logInAsRoot();
ComponentDto project = insertSampleRootProject();
+ logInAsProjectAdministrator(project);
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Malformed key for 'sample?root'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
@Test
public void fail_if_update_is_not_on_module_or_project() {
- logInAsRoot();
ComponentDto project = insertSampleRootProject();
ComponentDto file = componentDb.insertComponent(newFileDto(project, null));
+ logInAsProjectAdministrator(project);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Component updated must be a module or a key");
assertThat(dbClient.componentDao().selectByKey(dbSession, key)).isPresent();
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
- }
-
private ComponentDto insertSampleRootProject() {
return insertProject("sample:root");
}
assertThat(dbClient.componentDao().selectByKey(dbSession, oldKey)).isAbsent();
assertThat(dbClient.componentDao().selectByKey(dbSession, newKey)).isPresent();
}
+
+ private void logInAsProjectAdministrator(ComponentDto provisionedProject) {
+ userSession.logIn("john").addProjectUuidPermissions(UserRole.ADMIN, provisionedProject.uuid());
+ }
}
}
@Test
- public void throw_ForbiddenException_if_not_root_administrator() {
- userSession.anonymous();
+ public void throw_ForbiddenException_if_not_project_administrator() {
+ userSession.logIn();
ComponentDto project = insertMyProject();
expectedException.expect(ForbiddenException.class);
-
callDryRunByUuid(project.uuid(), FROM, TO);
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Test
public void json_example() throws IOException {
+ userSession.logIn().setRoot();
insertJsonExampleComponentsAndSnapshots();
String response = ws.newRequest()
@Test
public void show_provided_project() {
+ userSession.logIn().setRoot();
componentDb.insertComponent(newProjectDto(db.organizations().insert(), "project-uuid").setEnabled(false));
ShowWsResponse response = newRequest("project-uuid", null);
}
@Test
- public void fail_if_not_enough_privilege() {
- userSession.anonymous();
+ public void throw_ForbiddenException_if_user_doesnt_have_browse_permission_on_project() {
+ userSession.logIn();
expectedException.expect(ForbiddenException.class);
componentDb.insertProjectAndSnapshot(newProjectDto(db.organizations().insert(), "project-uuid"));
@Before
public void setUp() {
- userSession.logIn().setRoot();
ws = new WsActionTester(new TreeAction(dbClient, new ComponentFinder(dbClient), resourceTypes, userSession, Mockito.mock(I18n.class)));
resourceTypes.setChildrenQualifiers(Qualifiers.MODULE, Qualifiers.FILE, Qualifiers.DIRECTORY);
resourceTypes.setLeavesQualifiers(Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE);
@Test
public void json_example() throws IOException {
ComponentDto project = initJsonExampleComponents();
- userSession.logIn().addProjectUuidPermissions(UserRole.USER, project.uuid());
+ logInWithBrowsePermission(project);
String response = ws.newRequest()
.setParam(PARAM_BASE_COMPONENT_ID, project.uuid())
componentDb.insertComponent(directory);
componentDb.insertComponent(newFileDto(module, directory, 10));
db.commit();
+ logInWithBrowsePermission(project);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_STRATEGY, "children")
componentDb.insertComponent(directory);
componentDb.insertComponent(newFileDto(module, directory, 1));
db.commit();
+ logInWithBrowsePermission(project);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_STRATEGY, "all")
componentDb.insertComponent(newFileDto(project, 2));
componentDb.insertComponent(newModuleDto("module-uuid-1", project));
db.commit();
+ logInWithBrowsePermission(project);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_STRATEGY, "all")
componentDb.insertComponent(directory);
componentDb.insertComponent(newFileDto(module, directory, 3));
db.commit();
+ logInWithBrowsePermission(project);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_STRATEGY, "leaves")
componentDb.insertComponent(module);
componentDb.insertComponent(newDirectory(project, "path/directory/", "directory-uuid-1"));
db.commit();
+ logInWithBrowsePermission(project);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_STRATEGY, "all")
componentDb.insertComponent(newProjectCopy("project-uuid-1-copy", project, view));
componentDb.insertComponent(newSubView(view, "sub-view-uuid", "sub-view-key").setName("sub-view-name"));
db.commit();
+ logInWithBrowsePermission(view);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_STRATEGY, "children")
@Test
public void response_is_empty_on_provisioned_projects() {
- componentDb.insertComponent(newProjectDto(db.getDefaultOrganization(), "project-uuid"));
+ ComponentDto project = componentDb.insertComponent(newProjectDto(db.getDefaultOrganization(), "project-uuid"));
+ logInWithBrowsePermission(project);
TreeWsResponse response = call(ws.newRequest()
.setParam(PARAM_BASE_COMPONENT_ID, "project-uuid"));
componentDb.insertDeveloperAndSnapshot(developer);
componentDb.insertComponent(newDevProjectCopy("project-copy-uuid", project, developer));
db.commit();
+ logInWithBrowsePermission(developer);
TreeWsResponse response = call(ws.newRequest().setParam(PARAM_BASE_COMPONENT_ID, developer.uuid()));
ComponentDto view = newView(db.getDefaultOrganization(), "view-uuid");
componentDb.insertViewAndSnapshot(view);
componentDb.insertComponent(newProjectCopy("project-copy-uuid", project, view));
+ logInWithBrowsePermission(view);
TreeWsResponse response = call(ws.newRequest().setParam(PARAM_BASE_COMPONENT_ID, view.uuid()));
@Test
public void fail_when_not_enough_privileges() {
- expectedException.expect(ForbiddenException.class);
- userSession.anonymous().logIn()
+ userSession.logIn()
.addProjectUuidPermissions(UserRole.CODEVIEWER, "project-uuid");
componentDb.insertComponent(newProjectDto(db.organizations().insert(), "project-uuid"));
db.commit();
+ expectedException.expect(ForbiddenException.class);
+
ws.newRequest()
.setParam(PARAM_BASE_COMPONENT_ID, "project-uuid")
.execute();
JsonElement jsonElement = jsonObject.get(field);
return jsonElement == null ? null : jsonElement.getAsString();
}
+
+ private void logInWithBrowsePermission(ComponentDto project) {
+ userSession.logIn().addProjectUuidPermissions(UserRole.USER, project.uuid());
+ }
}
@Test
public void send_test_email() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
executeRequest("john@doo.com", "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000");
@Test
public void does_not_fail_when_subject_param_is_missing() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
executeRequest("john@doo.com", null, "This is a test message from SonarQube at http://localhost:9000");
@Test
public void fail_when_to_param_is_missing() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_when_message_param_is_missing() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void fail_with_BadRequestException_when_EmailException_is_generated() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
IllegalArgumentException exception1 = new IllegalArgumentException("root cause");
IllegalArgumentException exception2 = new IllegalArgumentException("parent cause", exception1);
IllegalArgumentException exception3 = new IllegalArgumentException("child cause", exception2);
request.execute();
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
}
private void setAnyoneProjectPermission(ComponentDto project, String permission) {
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
// TODO correctly feed default organization. Not a problem as long as issues search does not support "anyone"
// for each organization
GroupPermissionChange permissionChange = new GroupPermissionChange(PermissionChange.Operation.ADD, permission, new ProjectId(project), GroupIdOrAnyone.forAnyone(project.getOrganizationUuid()));
@Test
public void return_licenses() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings("12345");
String data = createBase64License("SonarSource", "governance", "12345", "2099-01-01", "PRODUCTION", ImmutableMap.of("other", "value"));
addLicenseSetting("sonar.governance.license.secured", "Governance", data);
@Test
public void return_licenses_even_if_no_value_set_in_database() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings("12345");
definitions.addComponent(PropertyDefinition.builder("sonar.governance.license.secured").type(LICENSE).build());
@Test
public void return_information_when_no_licence_set() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings(SERVER_ID_SAMPLE);
addLicenseSetting(LICENSE_KEY_SAMPLE, null, toBase64(""));
@Test
public void return_license_with_bad_product() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings(SERVER_ID_SAMPLE);
addLicenseSetting(LICENSE_KEY_SAMPLE, LICENSE_NAME_SAMPLE,
createBase64License(ORGANIZATION_SAMPLE, "Other", SERVER_ID_SAMPLE, EXPIRATION_SAMPLE, TYPE_SAMPLE, Collections.emptyMap()));
@Test
public void return_license_with_bad_server_id() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings(SERVER_ID_SAMPLE);
addLicenseSetting(LICENSE_KEY_SAMPLE, LICENSE_NAME_SAMPLE,
createBase64License(ORGANIZATION_SAMPLE, PRODUCT_SAMPLE, "Other", EXPIRATION_SAMPLE, TYPE_SAMPLE, Collections.emptyMap()));
@Test
public void return_bad_server_id_when_server_has_no_server_id() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addLicenseSetting(LICENSE_KEY_SAMPLE, LICENSE_NAME_SAMPLE,
createBase64License(ORGANIZATION_SAMPLE, PRODUCT_SAMPLE, SERVER_ID_SAMPLE, EXPIRATION_SAMPLE, TYPE_SAMPLE, Collections.emptyMap()));
@Test
public void does_not_return_invalid_server_id_when_all_servers_accepted_and_no_server_id_setting() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addLicenseSetting(LICENSE_KEY_SAMPLE, LICENSE_NAME_SAMPLE,
createBase64License(ORGANIZATION_SAMPLE, PRODUCT_SAMPLE, "*", EXPIRATION_SAMPLE, TYPE_SAMPLE, Collections.emptyMap()));
@Test
public void return_license_when_all_servers_are_accepted() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings(SERVER_ID_SAMPLE);
addLicenseSetting(LICENSE_KEY_SAMPLE, LICENSE_NAME_SAMPLE,
createBase64License(ORGANIZATION_SAMPLE, PRODUCT_SAMPLE, "*", EXPIRATION_SAMPLE, TYPE_SAMPLE, Collections.emptyMap()));
@Test
public void return_license_when_expired() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
addServerIdSettings(SERVER_ID_SAMPLE);
addLicenseSetting(LICENSE_KEY_SAMPLE, LICENSE_NAME_SAMPLE,
createBase64License(ORGANIZATION_SAMPLE, PRODUCT_SAMPLE, SERVER_ID_SAMPLE, "2010-01-01", TYPE_SAMPLE, Collections.emptyMap()));
@Test
public void none_license_type_settings_are_not_returned() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").build());
propertyDb.insertProperties(newGlobalPropertyDto().setKey("foo").setValue("value"));
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
}
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private void addLicenseSetting(String key, @Nullable String name, String value) {
import java.util.List;
import org.assertj.core.data.Offset;
-import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public void setUp() {
ws = new WsTester(new CustomMeasuresWs(new CreateAction(dbClient, userSession, System2.INSTANCE, new CustomMeasureValidator(newFullTypeValidations()),
new CustomMeasureJsonWriter(new UserJsonWriter(userSession)), new ComponentFinder(dbClient))));
- userSession.logIn("login").setRoot();
db.getDbClient().userDao().insert(dbSession, new UserDto()
.setLogin("login")
.setName("Login")
.setEmail("login@login.com")
- .setActive(true)
- );
+ .setActive(true));
dbSession.commit();
- }
- @After
- public void tearDown() {
- dbSession.close();
+ userSession.logIn("login").addProjectUuidPermissions(UserRole.ADMIN, DEFAULT_PROJECT_UUID);
}
@Test
dbClient.componentDao().insert(dbSession, ComponentTesting.newView(db.organizations().insert(), viewUuid));
dbSession.commit();
MetricDto metric = insertMetric(BOOL);
+ userSession.logIn("login").addProjectUuidPermissions(UserRole.ADMIN, viewUuid);
newRequest()
.setParam(CreateAction.PARAM_PROJECT_ID, viewUuid)
dbClient.componentDao().insert(dbSession, ComponentTesting.newSubView(view, subViewUuid, "SUB_VIEW_KEY"));
dbSession.commit();
MetricDto metric = insertMetric(BOOL);
+ userSession.logIn("login").addProjectUuidPermissions(UserRole.ADMIN, view.uuid());
newRequest()
.setParam(CreateAction.PARAM_PROJECT_ID, subViewUuid)
}
@Test
- public void fail_when_not_enough_permission() throws Exception {
- expectedException.expect(ForbiddenException.class);
- userSession.logIn("login");
+ public void fail_when_not_project_administrator() throws Exception {
+ userSession.logIn();
insertProject(DEFAULT_PROJECT_UUID);
MetricDto metric = insertMetric(STRING);
+ expectedException.expect(ForbiddenException.class);
+
newRequest()
.setParam(CreateAction.PARAM_PROJECT_ID, DEFAULT_PROJECT_UUID)
.setParam(CreateAction.PARAM_METRIC_ID, metric.getId().toString())
ws = new WsTester(new CustomMeasuresWs(new DeleteAction(dbClient, userSession)));
}
- @Test
- public void root_users_can_delete_custom_measures() throws Exception {
- userSession.logIn().setRoot();
- ComponentDto project = db.components().insertProject();
-
- long id = insertCustomMeasure(project);
- long anotherId = insertCustomMeasure(project);
-
- WsTester.Result response = newRequest().setParam(PARAM_ID, valueOf(id)).execute();
-
- assertThat(dbClient.customMeasureDao().selectById(dbSession, id)).isNull();
- assertThat(dbClient.customMeasureDao().selectById(dbSession, anotherId)).isNotNull();
- response.assertNoContent();
- }
-
@Test
public void project_administrator_can_delete_custom_measures() throws Exception {
ComponentDto project = db.components().insertProject();
}
@Test
- public void throw_ForbiddenException_if_not_administrator() throws Exception {
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
ComponentDto project = db.components().insertProject();
long id = insertCustomMeasure(project);
- userSession.logIn().setNonRoot();
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
newRequest().setParam(PARAM_ID, valueOf(id)).execute();
}
@Test
- public void throw_UnauthorizedException_if_not_administrator() throws Exception {
+ public void throw_UnauthorizedException_if_not_logged_in() throws Exception {
ComponentDto project = db.components().insertProject();
long id = insertCustomMeasure(project);
userSession.anonymous();
import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.Metric.ValueType;
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;
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
- DbClient dbClient = db.getDbClient();
- DbSession dbSession = db.getSession();
- System2 system = mock(System2.class);
- WsTester ws;
+
+ private DbClient dbClient = db.getDbClient();
+ private DbSession dbSession = db.getSession();
+ private System2 system = mock(System2.class);
+ private WsTester ws;
@Before
public void setUp() {
CustomMeasureValidator validator = new CustomMeasureValidator(newFullTypeValidations());
ws = new WsTester(new CustomMeasuresWs(new UpdateAction(dbClient, userSessionRule, system, validator, new CustomMeasureJsonWriter(new UserJsonWriter(userSessionRule)))));
- userSessionRule.logIn("login").setRoot();
db.getDbClient().userDao().insert(dbSession, new UserDto()
.setLogin("login")
dbClient.customMeasureDao().insert(dbSession, customMeasure);
dbSession.commit();
when(system.now()).thenReturn(123_456_789L);
+ logInAsProjectAdministrator(component);
ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
.setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
.setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
.setParam(PARAM_VALUE, "new-text-measure-value")
.execute();
+ logInAsProjectAdministrator(component);
CustomMeasureDto updatedCustomMeasure = dbClient.customMeasureDao().selectOrFail(dbSession, customMeasure.getId());
assertThat(updatedCustomMeasure.getTextValue()).isEqualTo("new-text-measure-value");
.setValue(42d);
dbClient.customMeasureDao().insert(dbSession, customMeasure);
dbSession.commit();
+ logInAsProjectAdministrator(component);
ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
.setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
dbClient.customMeasureDao().insert(dbSession, customMeasure);
dbSession.commit();
when(system.now()).thenReturn(123_456_789L);
+ logInAsProjectAdministrator(component);
WsTester.Result response = ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
.setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
dbClient.customMeasureDao().insert(dbSession, customMeasure);
dbSession.commit();
when(system.now()).thenReturn(123_456_789L);
+ logInAsProjectAdministrator(component);
ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
.setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
.setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
.execute();
+ logInAsProjectAdministrator(component);
CustomMeasureDto updatedCustomMeasure = dbClient.customMeasureDao().selectOrFail(dbSession, customMeasure.getId());
assertThat(updatedCustomMeasure.getTextValue()).isEqualTo("text-measure-value");
dbClient.customMeasureDao().insert(dbSession, customMeasure);
dbSession.commit();
when(system.now()).thenReturn(123_456_789L);
+ logInAsProjectAdministrator(component);
ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
.setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
@Test
public void fail_if_insufficient_privileges() throws Exception {
userSessionRule.logIn();
- expectedException.expect(ForbiddenException.class);
MetricDto metric = MetricTesting.newMetricDto().setEnabled(true).setValueType(ValueType.STRING.name());
dbClient.metricDao().insert(dbSession, metric);
ComponentDto component = ComponentTesting.newProjectDto(db.getDefaultOrganization(), "project-uuid");
dbClient.customMeasureDao().insert(dbSession, customMeasure);
dbSession.commit();
+ expectedException.expect(ForbiddenException.class);
+
ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
.setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
.setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
.setComponentUuid(project.uuid())
.setCreatedAt(system.now());
}
+
+ private void logInAsProjectAdministrator(ComponentDto component) {
+ userSessionRule.logIn("login").addProjectUuidPermissions(UserRole.ADMIN, component.uuid());
+ }
}
@Before
public void setUp() {
ws = new WsTester(new MetricsWs(new CreateAction(dbClient, userSessionRule)));
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
}
@Test
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSessionRule.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Before
public void setUp() {
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
ws = new WsTester(new MetricsWs(new DeleteAction(dbClient, userSessionRule)));
metricDao = dbClient.metricDao();
}
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSessionRule.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
insertCustomEnabledMetrics(1);
expectedException.expect(ForbiddenException.class);
@Before
public void setUp() {
ws = new WsTester(new MetricsWs(new UpdateAction(dbClient, userSessionRule)));
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
}
@Test
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSessionRule.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void verify_response_example() throws URISyntaxException, IOException {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(Uuids.UUID_EXAMPLE_01, SOME_DATE);
String response = executeJsonRequest("Foo Company", "foo-company", "The Foo company produces quality software for Bar.", "https://www.foo.com", "https://www.foo.com/foo.png");
}
@Test
- public void request_fails_if_user_is_not_root_and_logged_in_users_cannot_create_organizations() {
+ public void request_fails_if_user_is_not_system_administrator_and_logged_in_users_cannot_create_organizations() {
userSession.logIn();
expectedException.expect(ForbiddenException.class);
}
@Test
- public void request_succeeds_if_user_is_root_and_logged_in_users_cannot_create_organizations() {
- logInAsRoot();
+ public void request_succeeds_if_user_is_system_administrator_and_logged_in_users_cannot_create_organizations() {
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
verifyResponseAndDb(executeRequest("foo"), SOME_UUID, "foo", "foo", SOME_DATE);
}
@Test
- public void request_succeeds_if_user_is_root_and_logged_in_users_can_create_organizations() {
- logInAsRoot();
+ public void request_succeeds_if_user_is_system_administrator_and_logged_in_users_can_create_organizations() {
+ logInAsSystemAdministrator();
settings.setProperty(ORGANIZATIONS_ANYONE_CAN_CREATE, true);
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
}
@Test
- public void request_succeeds_if_user_is_not_root_and_logged_in_users_can_create_organizations() {
+ public void request_succeeds_if_user_is_not_system_administrator_and_logged_in_users_can_create_organizations() {
userSession.logIn();
settings.setProperty(ORGANIZATIONS_ANYONE_CAN_CREATE, true);
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
@Test
public void request_fails_if_name_param_is_missing() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'name' parameter is missing");
@Test
public void request_fails_if_name_is_one_char_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Name 'a' must be at least 2 chars long");
@Test
public void request_succeeds_if_name_is_two_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
verifyResponseAndDb(executeRequest("ab"), SOME_UUID, "ab", "ab", SOME_DATE);
@Test
public void request_fails_if_name_is_65_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Name '" + STRING_65_CHARS_LONG + "' must be at most 64 chars long");
@Test
public void request_succeeds_if_name_is_64_char_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String name = STRING_65_CHARS_LONG.substring(0, 64);
@Test
public void request_fails_if_key_one_char_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Key 'a' must be at least 2 chars long");
@Test
public void request_fails_if_key_is_33_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
String key = STRING_65_CHARS_LONG.substring(0, 33);
@Test
public void request_succeeds_if_key_is_2_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
verifyResponseAndDb(executeRequest("foo", "ab"), SOME_UUID, "foo", "ab", SOME_DATE);
@Test
public void requests_succeeds_if_key_is_32_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String key = STRING_65_CHARS_LONG.substring(0, 32);
@Test
public void requests_fails_if_key_contains_non_ascii_chars_but_dash() {
- logInAsRoot();
+ logInAsSystemAdministrator();
requestFailsWithInvalidCharInKey("ab@");
}
@Test
public void request_fails_if_key_starts_with_a_dash() {
- logInAsRoot();
+ logInAsSystemAdministrator();
requestFailsWithInvalidCharInKey("-ab");
}
@Test
public void request_fails_if_key_ends_with_a_dash() {
- logInAsRoot();
+ logInAsSystemAdministrator();
requestFailsWithInvalidCharInKey("ab-");
}
@Test
public void request_fails_if_key_contains_space() {
- logInAsRoot();
+ logInAsSystemAdministrator();
requestFailsWithInvalidCharInKey("a b");
}
@Test
public void request_fails_if_key_is_specified_and_already_exists_in_DB() {
- logInAsRoot();
+ logInAsSystemAdministrator();
OrganizationDto org = insertOrganization("the-key");
expectedException.expect(IllegalArgumentException.class);
@Test
public void request_fails_if_key_computed_from_name_already_exists_in_DB() {
- logInAsRoot();
+ logInAsSystemAdministrator();
String key = STRING_65_CHARS_LONG.substring(0, 32);
insertOrganization(key);
@Test
public void request_succeeds_if_description_url_and_avatar_are_not_specified() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
CreateWsResponse response = executeRequest("foo", "bar", null, null, null);
@Test
public void request_succeeds_if_description_url_and_avatar_are_specified() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
CreateWsResponse response = executeRequest("foo", "bar", "moo", "doo", "boo");
@Test
public void request_succeeds_to_generate_key_from_name_more_then_32_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String name = STRING_65_CHARS_LONG.substring(0, 33);
@Test
public void request_generates_key_ignoring_multiple_following_spaces() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String name = "ab cd";
@Test
public void request_fails_if_description_is_257_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Description '" + STRING_257_CHARS_LONG + "' must be at most 256 chars long");
@Test
public void request_succeeds_if_description_is_256_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String description = STRING_257_CHARS_LONG.substring(0, 256);
@Test
public void request_fails_if_url_is_257_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Url '" + STRING_257_CHARS_LONG + "' must be at most 256 chars long");
@Test
public void request_succeeds_if_url_is_256_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String url = STRING_257_CHARS_LONG.substring(0, 256);
@Test
public void request_fails_if_avatar_is_257_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Avatar '" + STRING_257_CHARS_LONG + "' must be at most 256 chars long");
@Test
public void request_succeeds_if_avatar_is_256_chars_long() {
- logInAsRoot();
+ logInAsSystemAdministrator();
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
String avatar = STRING_257_CHARS_LONG.substring(0, 256);
@Test
public void request_creates_owners_group_with_all_permissions_for_new_organization_and_add_current_user_to_it() {
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
- UserDto user = dbTester.users().makeRoot(dbTester.users().insertUser());
- userSession.logIn(user).setRoot();
+ UserDto user = dbTester.users().insertUser();
+ userSession.logIn(user).setSystemAdministrator();
executeRequest("orgFoo");
@Test
public void request_creates_default_template_for_owner_group_and_anyone() {
mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
- UserDto user = dbTester.users().makeRoot(dbTester.users().insertUser());
- userSession.logIn(user).setRoot();
+ UserDto user = dbTester.users().insertUser();
+ userSession.logIn(user).setSystemAdministrator();
executeRequest("orgFoo");
}
@Test
- public void request_fails_with_IllegalStateException_if_organization_feature_is_disabled() {
+ public void request_fails_with_IllegalStateException_if_organization_support_is_disabled() {
organizationFlags.setEnabled(false);
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Organization support is disabled");
return dto;
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
}
@Test
- public void request_fails_with_IllegalStateException_if_organization_feature_is_disabled() {
+ public void request_fails_with_IllegalStateException_if_organization_support_is_disabled() {
organizationFlags.setEnabled(false);
userSession.logIn();
@Test
public void request_fails_with_IAE_if_key_param_is_missing() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'key' parameter is missing");
@Test
public void request_fails_with_IAE_if_key_is_the_one_of_default_organization() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Default Organization can't be deleted");
@Test
public void request_fails_with_NotFoundException_if_organization_with_specified_key_does_not_exist() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Organization with key 'foo' not found");
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root_and_is_not_administrator_of_specified_organization() {
+ public void request_fails_with_ForbiddenException_when_user_is_not_administrator_of_specified_organization() {
OrganizationDto organization = dbTester.organizations().insert();
userSession.logIn();
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root_and_is_administrator_of_other_organization() {
+ public void request_fails_with_ForbiddenException_when_user_is_system_administrator() {
+ OrganizationDto organization = dbTester.organizations().insert();
+ userSession.logIn().setSystemAdministrator();
+
+ expectedException.expect(ForbiddenException.class);
+ expectedException.expectMessage("Insufficient privileges");
+
+ sendRequest(organization);
+ }
+
+ @Test
+ public void request_fails_with_ForbiddenException_when_user_is_administrator_of_other_organization() {
OrganizationDto organization = dbTester.organizations().insert();
logInAsAdministrator(dbTester.getDefaultOrganization());
}
@Test
- public void request_deletes_specified_organization_if_exists_and_user_is_root() {
+ public void request_deletes_specified_organization_if_exists_and_user_is_organization_administrator() {
OrganizationDto organization = dbTester.organizations().insert();
- userSession.logIn().setRoot();
+ logInAsAdministrator(organization);
sendRequest(organization);
}
@Test
- public void request_deletes_specified_guarded_organization_if_exists_and_user_is_root() {
+ public void request_deletes_specified_guarded_organization_if_exists_and_user_is_system_administrator() {
OrganizationDto organization = dbTester.organizations().insert(dto -> dto.setGuarded(true));
- userSession.logIn().setRoot();
+ logInAsSystemAdministrator();
sendRequest(organization);
@Test
public void request_also_deletes_components_of_specified_organization() {
- logInAsRoot();
-
OrganizationDto organization = dbTester.organizations().insert();
ComponentDto project = dbTester.components().insertProject(organization);
ComponentDto module = dbTester.components().insertComponent(ComponentTesting.newModuleDto(project));
ComponentDto subview1 = dbTester.components().insertComponent(ComponentTesting.newSubView(view, "v1", "ksv1"));
ComponentDto subview2 = dbTester.components().insertComponent(ComponentTesting.newSubView(subview1, "v2", "ksv2"));
ComponentDto projectCopy = dbTester.components().insertComponent(ComponentTesting.newProjectCopy("pc1", project, subview1));
+ logInAsAdministrator(organization);
sendRequest(organization);
@Test
public void request_also_deletes_permissions_templates_and_permissions_and_groups_of_specified_organization() {
- logInAsRoot();
-
OrganizationDto org = dbTester.organizations().insert();
OrganizationDto otherOrg = dbTester.organizations().insert();
PermissionTemplateDto templateDto = dbTester.permissionTemplates().insertTemplate(org);
PermissionTemplateDto otherTemplateDto = dbTester.permissionTemplates().insertTemplate(otherOrg);
+ logInAsAdministrator(org);
sendRequest(org);
.execute();
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private void logInAsAdministrator(OrganizationDto organization) {
}
@Test
- public void request_fails_with_IllegalStateException_if_organization_feature_is_disabled() {
+ public void request_fails_with_IllegalStateException_if_organization_support_is_disabled() {
organizationFlags.setEnabled(false);
userSession.logIn();
}
@Test
- public void request_succeeds_if_user_is_root() {
- logInAsRoot();
+ public void request_succeeds_if_user_is_organization_administrator() {
OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(dto);
verifyResponseAndDb(executeKeyRequest(dto.getKey(), "ab"), dto, "ab", DATE_2);
}
}
@Test
- public void request_fails_if_user_is_not_root_and_is_not_organization_administrator() {
+ public void request_fails_if_user_is_not_system_administrator_and_is_not_organization_administrator() {
OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
userSession.logIn();
@Test
public void request_fails_if_key_is_missing() {
- logInAsRoot();
+ userSession.logIn();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'key' parameter is missing");
@Test
public void request_with_only_key_param_succeeds_and_updates_only_updateAt_field() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(org);
- verifyResponseAndDb(executeKeyRequest(dto.getKey(), null), dto, dto.getName(), DATE_2);
+ verifyResponseAndDb(executeKeyRequest(org.getKey(), null), org, org.getName(), DATE_2);
}
@Test
public void request_fails_if_name_is_one_char_long() {
- logInAsRoot();
+ userSession.logIn();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Name 'a' must be at least 2 chars long");
@Test
public void request_succeeds_if_name_is_two_chars_long() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(org);
- verifyResponseAndDb(executeKeyRequest(dto.getKey(), "ab"), dto, "ab", DATE_2);
+ verifyResponseAndDb(executeKeyRequest(org.getKey(), "ab"), org, "ab", DATE_2);
}
@Test
public void request_fails_if_name_is_65_chars_long() {
- logInAsRoot();
+ userSession.logIn();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Name '" + STRING_65_CHARS_LONG + "' must be at most 64 chars long");
@Test
public void request_succeeds_if_name_is_64_char_long() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(org);
String name = STRING_65_CHARS_LONG.substring(0, 64);
- verifyResponseAndDb(executeKeyRequest(dto.getKey(), name), dto, name, DATE_2);
+ verifyResponseAndDb(executeKeyRequest(org.getKey(), name), org, name, DATE_2);
}
@Test
public void request_succeeds_if_description_url_and_avatar_are_not_specified() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(org);
- Organizations.UpdateWsResponse response = executeKeyRequest(dto.getKey(), "bar", null, null, null);
- verifyResponseAndDb(response, dto, "bar", DATE_2);
+ Organizations.UpdateWsResponse response = executeKeyRequest(org.getKey(), "bar", null, null, null);
+ verifyResponseAndDb(response, org, "bar", DATE_2);
}
@Test
public void request_succeeds_if_description_url_and_avatar_are_specified() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(org);
- Organizations.UpdateWsResponse response = executeKeyRequest(dto.getKey(), "bar", "moo", "doo", "boo");
- verifyResponseAndDb(response, dto, "bar", "moo", "doo", "boo", DATE_2);
+ Organizations.UpdateWsResponse response = executeKeyRequest(org.getKey(), "bar", "moo", "doo", "boo");
+ verifyResponseAndDb(response, org, "bar", "moo", "doo", "boo", DATE_2);
}
@Test
public void request_fails_if_description_is_257_chars_long() {
- logInAsRoot();
+ userSession.logIn();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Description '" + STRING_257_CHARS_LONG + "' must be at most 256 chars long");
@Test
public void request_succeeds_if_description_is_256_chars_long() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
String description = STRING_257_CHARS_LONG.substring(0, 256);
+ logInAsAdministrator(org);
- Organizations.UpdateWsResponse response = executeKeyRequest(dto.getKey(), "bar", description, null, null);
- verifyResponseAndDb(response, dto, "bar", description, dto.getUrl(), dto.getAvatarUrl(), DATE_2);
+ Organizations.UpdateWsResponse response = executeKeyRequest(org.getKey(), "bar", description, null, null);
+ verifyResponseAndDb(response, org, "bar", description, org.getUrl(), org.getAvatarUrl(), DATE_2);
}
@Test
public void request_fails_if_url_is_257_chars_long() {
- logInAsRoot();
+ userSession.logIn();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Url '" + STRING_257_CHARS_LONG + "' must be at most 256 chars long");
@Test
public void request_succeeds_if_url_is_256_chars_long() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
String url = STRING_257_CHARS_LONG.substring(0, 256);
+ logInAsAdministrator(org);
- Organizations.UpdateWsResponse response = executeKeyRequest(dto.getKey(), "bar", null, url, null);
- verifyResponseAndDb(response, dto, "bar", dto.getDescription(), url, dto.getAvatarUrl(), DATE_2);
+ Organizations.UpdateWsResponse response = executeKeyRequest(org.getKey(), "bar", null, url, null);
+ verifyResponseAndDb(response, org, "bar", org.getDescription(), url, org.getAvatarUrl(), DATE_2);
}
@Test
public void request_fails_if_avatar_is_257_chars_long() {
- logInAsRoot();
+ userSession.logIn();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Avatar '" + STRING_257_CHARS_LONG + "' must be at most 256 chars long");
@Test
public void request_succeeds_if_avatar_is_256_chars_long() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
String avatar = STRING_257_CHARS_LONG.substring(0, 256);
+ logInAsAdministrator(org);
- Organizations.UpdateWsResponse response = executeKeyRequest(dto.getKey(), "bar", null, null, avatar);
- verifyResponseAndDb(response, dto, "bar", dto.getDescription(), dto.getUrl(), avatar, DATE_2);
+ Organizations.UpdateWsResponse response = executeKeyRequest(org.getKey(), "bar", null, null, avatar);
+ verifyResponseAndDb(response, org, "bar", org.getDescription(), org.getUrl(), avatar, DATE_2);
}
@Test
public void request_removes_optional_parameters_when_associated_parameter_are_empty() {
- logInAsRoot();
- OrganizationDto dto = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ OrganizationDto org = mockForSuccessfulUpdate(DATE_1, DATE_2);
+ logInAsAdministrator(org);
- Organizations.UpdateWsResponse response = executeKeyRequest(dto.getKey(), "bla", "", "", "");
- verifyResponseAndDb(response, dto, "bla", null, null, null, DATE_2);
+ Organizations.UpdateWsResponse response = executeKeyRequest(org.getKey(), "bla", "", "", "");
+ verifyResponseAndDb(response, org, "bla", null, null, null, DATE_2);
}
private OrganizationDto mockForSuccessfulUpdate(long createdAt, long nextNow) {
assertThat(newDto.getUpdatedAt()).isEqualTo(updateAt);
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
- }
-
private void logInAsAdministrator(OrganizationDto organizationDto) {
userSession.logIn().addOrganizationPermission(organizationDto.getUuid(), SYSTEM_ADMIN);
}
@Before
public void setUp() {
i18n.setProjectPermissions();
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
}
@Override
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() {
- userSession.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void enable_debug_logs() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
actionTester.newRequest()
.setParam("level", "DEBUG")
@Test
public void enable_trace_logs() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
actionTester.newRequest()
.setParam("level", "TRACE")
@Test
public void fail_if_unsupported_level() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_if_missing_level() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
.execute();
}
- private void makeAuthenticatedUserRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() {
- userSessionRule.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void write_json() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
Map<String, Object> attributes1 = new LinkedHashMap<>();
attributes1.put("foo", "bar");
assertThat(response.getInput()).isEqualTo("{\"Monitor One\":{\"foo\":\"bar\"},\"Monitor Two\":{\"one\":1,\"two\":2}}");
}
- private void makeAuthenticatedUserRoot() {
- userSessionRule.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSessionRule.logIn().setSystemAdministrator();
}
}
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() {
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSession.logIn();
expectedException.expect(ForbiddenException.class);
@Test
public void get_app_logs_by_default() throws IOException {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
createAllLogsFiles();
@Test
public void return_404_not_found_if_file_does_not_exist() throws IOException {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
createLogsDir();
@Test
public void get_ce_logs() throws IOException {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
createAllLogsFiles();
@Test
public void get_es_logs() throws IOException {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
createAllLogsFiles();
@Test
public void get_web_logs() throws IOException {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
createAllLogsFiles();
@Test
public void do_not_return_rotated_files() throws IOException {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
File dir = createLogsDir();
FileUtils.write(new File(dir, "sonar.1.log"), "{old}");
return dir;
}
- private void makeAuthenticatedUserRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
}
@Test
- public void request_fails_in_production_mode_with_ForbiddenException_when_user_is_not_root() {
- userSessionRule.logIn();
+ public void request_fails_in_production_mode_with_ForbiddenException_when_user_is_not_system_administrator() {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void calls_ProcessCommandWrapper_requestForSQRestart_in_production_mode() throws Exception {
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
actionTester.newRequest().execute();
@Test
public void logs_login_of_authenticated_user_requesting_the_restart_in_production_mode() throws Exception {
String login = "BigBother";
- userSessionRule.logIn(login).setRoot();
+ userSessionRule.logIn(login).setSystemAdministrator();
actionTester.newRequest().execute();
@Test
public void action_available_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSession.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void empty_array_is_returned_when_there_is_no_plugin_available() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
underTest.handle(request, response);
assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
@Test
public void empty_array_is_returned_when_update_center_is_not_accessible() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.<UpdateCenter>absent());
underTest.handle(request, response);
@Test
public void verify_properties_displayed_in_json_per_plugin() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(FULL_PROPERTIES_PLUGIN_RELEASE, COMPATIBLE)));
@Test
public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
checkStatusDisplayedInJson(COMPATIBLE, "COMPATIBLE");
}
@Test
public void status_INCOMPATIBLE_is_displayed_INCOMPATIBLE_in_JSON() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
checkStatusDisplayedInJson(INCOMPATIBLE, "INCOMPATIBLE");
}
@Test
public void status_REQUIRE_SONAR_UPGRADE_is_displayed_REQUIRES_SYSTEM_UPGRADE_in_JSON() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
checkStatusDisplayedInJson(REQUIRE_SONAR_UPGRADE, "REQUIRES_SYSTEM_UPGRADE");
}
@Test
public void status_DEPENDENCIES_REQUIRE_SONAR_UPGRADE_is_displayed_DEPS_REQUIRE_SYSTEM_UPGRADE_in_JSON() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
checkStatusDisplayedInJson(DEPENDENCIES_REQUIRE_SONAR_UPGRADE, "DEPS_REQUIRE_SYSTEM_UPGRADE");
}
"}");
}
- private void makeAuthenticatedUserRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSessionRule.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void triggers_cancel_for_downloads_and_uninstalls() throws Exception {
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
underTest.handle(request, response);
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSessionRule.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void action_install_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
@Test
public void IAE_is_raised_when_key_param_is_not_provided() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
invalidRequest.execute();
@Test
public void IAE_is_raised_when_there_is_no_available_plugin_for_the_key() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("No plugin with key 'pluginKey'");
@Test
public void IAE_is_raised_when_update_center_is_unavailable() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.<UpdateCenter>absent());
expectedException.expect(IllegalArgumentException.class);
@Test
public void if_plugin_is_found_available_download_is_triggered_with_latest_version_from_updatecenter() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
Version version = Version.create("1.0");
when(updateCenter.findAvailablePlugins()).thenReturn(ImmutableList.of(
PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), PluginUpdate.Status.COMPATIBLE)
result.assertNoContent();
}
- private void makeAuthenticatedUserRoot() {
- userSessionRule.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSessionRule.logIn().setSystemAdministrator();
}
}
@Test
public void action_installed_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSession.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void empty_array_is_returned_when_there_is_not_plugin_installed() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
underTest.handle(request, response);
assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
@Test
public void empty_array_when_update_center_is_unavailable() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.<UpdateCenter>absent());
underTest.handle(request, response);
@Test
public void empty_fields_are_not_serialized_to_json() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(pluginRepository.getPluginInfos()).thenReturn(
of(new PluginInfo("").setName("")));
@Test
public void verify_properties_displayed_in_json_per_plugin() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
String jarFilename = getClass().getSimpleName() + "/" + "some.jar";
when(pluginRepository.getPluginInfos()).thenReturn(of(
new PluginInfo("plugKey")
@Test
public void category_is_returned_when_in_additional_fields() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
String jarFilename = getClass().getSimpleName() + "/" + "some.jar";
when(pluginRepository.getPluginInfos()).thenReturn(of(
new PluginInfo("plugKey")
@Test
public void plugins_are_sorted_by_name_then_key_and_only_one_plugin_can_have_a_specific_name() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(pluginRepository.getPluginInfos()).thenReturn(
of(
plugin("A", "name2"),
@Test
public void only_one_plugin_can_have_a_specific_name_and_key() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(pluginRepository.getPluginInfos()).thenReturn(
of(
plugin("A", "name2"),
return new PluginInfo(key).setName(name).setVersion(Version.create("1.0"));
}
- private void makeAuthenticatedUserRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
@Test
public void action_pending_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSession.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void empty_arrays_are_returned_when_there_nothing_pending() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
underTest.handle(request, response);
assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(
@Test
public void empty_arrays_are_returned_when_update_center_is_unavailable() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.<UpdateCenter>absent());
underTest.handle(request, response);
@Test
public void verify_properties_displayed_in_json_per_installing_plugin() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
newUpdateCenter("scmgit");
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newScmGitPluginInfo()));
@Test
public void verify_properties_displayed_in_json_per_removing_plugin() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(serverPluginRepository.getUninstalledPlugins()).thenReturn(of(newScmGitPluginInfo()));
underTest.handle(request, response);
@Test
public void verify_properties_displayed_in_json_per_updating_plugin() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
newUpdateCenter("scmgit");
when(serverPluginRepository.getPluginInfos()).thenReturn(of(newScmGitPluginInfo()));
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newScmGitPluginInfo()));
@Test
public void verify_properties_displayed_in_json_per_installing_removing_and_updating_plugins() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
PluginInfo installed = newPluginInfo("java");
PluginInfo removedPlugin = newPluginInfo("js");
PluginInfo newPlugin = newPluginInfo("php");
@Test
public void installing_plugins_are_sorted_by_name_then_key_and_are_unique() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(
newPluginInfo(0).setName("Foo"),
newPluginInfo(3).setName("Bar"),
@Test
public void removing_plugins_are_sorted_and_unique() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(serverPluginRepository.getUninstalledPlugins()).thenReturn(of(
newPluginInfo(0).setName("Foo"),
newPluginInfo(3).setName("Bar"),
return new PluginInfo("key" + id).setName("name" + id);
}
- private void makeAuthenticatedUserRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
WsTester wsTester = new WsTester(serverTester.get(PluginsWs.class));
// 1 - check what's installed, available and pending
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
wsTester.newGetRequest("api/plugins", "installed").execute().assertJson("{" +
" \"plugins\": [" +
" {" +
wsTester = restartServerTester();
// 4 - make sure plugin is installed
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
wsTester.newGetRequest("api/plugins", "installed").execute().assertJson("{" +
" \"plugins\": [" +
" {" +
wsTester = restartServerTester();
// 7 - make sure plugin has been uninstalled
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
wsTester.newGetRequest("api/plugins", "installed").execute().assertJson("{" +
" \"plugins\": [" +
" {" +
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSessionRule.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void action_uninstall_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
@Test
public void IAE_is_raised_when_key_param_is_not_provided() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void IAE_is_raised_when_plugin_is_not_installed() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Plugin [findbugs] is not installed");
@Test
public void if_plugin_is_installed_uninstallation_is_triggered() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(pluginRepository.hasPlugin(PLUGIN_KEY)).thenReturn(true);
underTest.handle(validRequest, response);
assertThat(response.outputAsString()).isEmpty();
}
- private void makeAuthenticatedUserRoot() {
- userSessionRule.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSessionRule.logIn().setSystemAdministrator();
}
}
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
- userSessionRule.logIn();
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void action_update_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
@Test
public void IAE_is_raised_when_key_param_is_not_provided() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void IAE_is_raised_when_there_is_no_plugin_update_for_the_key() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("No plugin with key 'pluginKey'");
@Test
public void IAE_is_raised_when_update_center_is_unavailable() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.<UpdateCenter>absent());
expectedException.expect(IllegalArgumentException.class);
@Test
public void if_plugin_has_an_update_download_is_triggered_with_latest_version_from_updatecenter() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
Version version = Version.create("1.0");
when(updateCenter.findPluginUpdates()).thenReturn(ImmutableList.of(
PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), Status.COMPATIBLE)
assertThat(response.outputAsString()).isEmpty();
}
- private void makeAuthenticatedUserRoot() {
- userSessionRule.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSessionRule.logIn().setSystemAdministrator();
}
}
@Test
public void action_updatable_is_defined() {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void request_fails_with_ForbiddenException_when_user_is_not_root() throws Exception {
+ public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
userSession.logIn();
expectedException.expect(ForbiddenException.class);
@Test
public void empty_array_is_returned_when_there_is_no_plugin_available() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
underTest.handle(request, response);
@Test
public void verify_response_against_example() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenter.findPluginUpdates()).thenReturn(of(
pluginUpdate(ABAP_32, COMPATIBLE),
pluginUpdate(ABAP_31, INCOMPATIBLE),
@Test
public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenter.findPluginUpdates()).thenReturn(of(
pluginUpdate(release(PLUGIN_1, "1.0.0"), COMPATIBLE)));
@Test
public void plugins_are_sorted_by_name_and_made_unique() throws Exception {
- makeAuthenticatedUserRoot();
+ logInAsSystemAdministrator();
when(updateCenter.findPluginUpdates()).thenReturn(of(
pluginUpdate("key2", "name2"),
pluginUpdate("key2", "name2"),
"}");
}
- private void makeAuthenticatedUserRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
}
@Test
- public void root_deletes_projects_by_uuids_in_all_organizations() throws Exception {
- userSession.logIn().setRoot();
+ public void system_administrator_deletes_projects_by_uuids_in_all_organizations() throws Exception {
+ userSession.logIn().setSystemAdministrator();
ComponentDto toDeleteInOrg1 = db.components().insertProject(org1);
ComponentDto toDeleteInOrg2 = db.components().insertProject(org2);
ComponentDto toKeep = db.components().insertProject(org2);
}
@Test
- public void root_deletes_projects_by_keys_in_all_organizations() throws Exception {
- userSession.logIn().setRoot();
+ public void system_administrator_deletes_projects_by_keys_in_all_organizations() throws Exception {
+ userSession.logIn().setSystemAdministrator();
ComponentDto toDeleteInOrg1 = db.components().insertProject(org1);
ComponentDto toDeleteInOrg2 = db.components().insertProject(org2);
ComponentDto toKeep = db.components().insertProject(org2);
@Test
public void projects_that_dont_exist_are_ignored_and_dont_break_bulk_deletion() throws Exception {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
ComponentDto toDelete1 = db.components().insertProject(org1);
ComponentDto toDelete2 = db.components().insertProject(org1);
}
@Test
- public void throw_ForbiddenException_if_param_organization_is_not_set_and_not_root() throws Exception {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_param_organization_is_not_set_and_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN;
import static org.sonar.server.project.ws.DeleteAction.PARAM_ID;
import static org.sonar.server.project.ws.DeleteAction.PARAM_KEY;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.CONTROLLER;
}
@Test
- public void root_administrator_deletes_project_by_id() throws Exception {
+ public void organization_administrator_deletes_project_by_id() throws Exception {
ComponentDto project = componentDbTester.insertProject();
+ userSessionRule.logIn().addOrganizationPermission(project.getOrganizationUuid(), SYSTEM_ADMIN);
- userSessionRule.logIn().setRoot();
WsTester.TestRequest request = newRequest().setParam(PARAM_ID, project.uuid());
call(request);
}
@Test
- public void root_administrator_deletes_project_by_key() throws Exception {
+ public void organization_administrator_deletes_project_by_key() throws Exception {
ComponentDto project = componentDbTester.insertProject();
+ userSessionRule.logIn().addOrganizationPermission(project.getOrganizationUuid(), SYSTEM_ADMIN);
- userSessionRule.logIn().setRoot();
call(newRequest().setParam(PARAM_KEY, project.key()));
assertThat(verifyDeletedKey()).isEqualTo(project.key());
private WsActionTester ws = new WsActionTester(new DeleteAction(dbClient, userSession));
- @Test
- public void root_administrator_deletes_analysis() {
- ComponentDto project = db.components().insertProject();
- db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false).setStatus(STATUS_PROCESSED));
- db.components().insertSnapshot(newAnalysis(project).setUuid("A2").setLast(true).setStatus(STATUS_PROCESSED));
- userSession.logIn().setRoot();
-
- call("A1");
-
- db.commit();
- assertThat(dbClient.snapshotDao().selectByUuids(dbSession, newArrayList("A1", "A2"))).extracting(SnapshotDto::getUuid, SnapshotDto::getStatus).containsExactly(
- tuple("A1", STATUS_UNPROCESSED),
- tuple("A2", STATUS_PROCESSED));
- }
-
@Test
public void project_administrator_deletes_analysis() {
ComponentDto project = db.components().insertProject();
db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false).setStatus(STATUS_PROCESSED));
db.components().insertSnapshot(newAnalysis(project).setUuid("A2").setLast(true).setStatus(STATUS_PROCESSED));
- userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
call("A1");
public void last_analysis_cannot_be_deleted() {
ComponentDto project = db.components().insertProject();
db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(true));
- userSession.logIn().setRoot();
+ logInAsProjectAdministrator(project);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The last analysis 'A1' cannot be deleted");
@Test
public void fail_when_analysis_is_unprocessed() {
- userSession.logIn().setRoot();
ComponentDto project = db.components().insertProject();
db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false).setStatus(STATUS_UNPROCESSED));
+ logInAsProjectAdministrator(project);
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Analysis 'A1' not found");
@Test
public void fail_when_not_enough_permission() {
- userSession.logIn();
ComponentDto project = db.components().insertProject();
db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false));
+ userSession.logIn();
expectedException.expect(ForbiddenException.class);
.setParam(PARAM_ANALYSIS, analysis)
.execute();
}
+
+ private void logInAsProjectAdministrator(ComponentDto project) {
+ userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ }
}
@Test
public void fail_if_event_is_not_found() {
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Event 'E42' not found");
ComponentFinder componentFinder = new ComponentFinder(dbClient);
underTest = new CreateAction(dbClient, userSession, componentFinder);
ws = new WsActionTester(underTest);
-
- userSession.logIn().setRoot();
}
@Test
public void example_with_key() {
ComponentDto project = insertProject();
+ logInAsProjectAdministrator(project);
String result = ws.newRequest()
.setMethod("POST")
@Test
public void example_with_id() {
ComponentDto project = insertProject();
+ logInAsProjectAdministrator(project);
String result = ws.newRequest()
.setMethod("POST")
@Test
public void require_project_admin() throws IOException {
ComponentDto project = insertProject();
- userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
createAndTest(project);
}
@Test
public void with_long_name() throws IOException {
ComponentDto project = insertProject();
+ logInAsProjectAdministrator(project);
String longName = StringUtils.leftPad("", 60, "a");
String expectedType = StringUtils.leftPad("", 20, "a");
@Test
public void fail_if_no_name() {
expectedException.expect(IllegalArgumentException.class);
+
ws.newRequest()
.setParam(PARAM_PROJECT_KEY, "unknown")
.setParam(PARAM_URL, "http://example.org")
private void createAndTest(ComponentDto project) throws IOException {
createAndTest(project, "Custom", "http://example.org", "custom");
}
+
+ private void logInAsProjectAdministrator(ComponentDto project) {
+ userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ }
}
public void no_response() {
ComponentDto project = insertProject();
ComponentLinkDto link = insertCustomLink(project.uuid());
- userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
TestResponse response = deleteLink(link.getId());
ComponentDto project = insertProject();
ComponentLinkDto link = insertCustomLink(project.uuid());
long id = link.getId();
- userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
deleteLink(id);
assertLinkIsDeleted(id);
public void fail_when_delete_provided_link() {
ComponentDto project = insertProject();
ComponentLinkDto link = insertHomepageLink(project.uuid());
- userSession.logIn().setRoot();
+ logInAsProjectAdministrator(project);
expectedException.expect(BadRequestException.class);
private void assertLinkIsNotDeleted(Long id) {
assertThat(dbClient.componentLinkDao().selectById(dbSession, id)).isNotNull();
}
+
+ private void logInAsProjectAdministrator(ComponentDto project) {
+ userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ }
}
@Test
public void example() {
- logInAsRoot();
ComponentDto project = insertProject();
insertHomepageLink(project.uuid());
insertCustomLink(project.uuid());
+ logInAsProjectAdministrator(project);
String result = ws.newRequest()
.setParam(PARAM_PROJECT_KEY, PROJECT_KEY)
@Test
public void request_by_project_id() throws IOException {
- logInAsRoot();
ComponentDto project = insertProject();
insertHomepageLink(project.uuid());
+ logInAsProjectAdministrator(project);
SearchWsResponse response = callByUuid(project.uuid());
@Test
public void request_by_project_key() throws IOException {
- logInAsRoot();
ComponentDto project = insertProject();
insertHomepageLink(project.uuid());
+ logInAsProjectAdministrator(project);
SearchWsResponse response = callByKey(project.key());
@Test
public void response_fields() throws IOException {
- logInAsRoot();
ComponentDto project = insertProject();
ComponentLinkDto homepageLink = insertHomepageLink(project.uuid());
ComponentLinkDto customLink = insertCustomLink(project.uuid());
+ logInAsProjectAdministrator(project);
SearchWsResponse response = callByKey(project.key());
@Test
public void several_projects() throws IOException {
- logInAsRoot();
ComponentDto project1 = insertProject();
ComponentDto project2 = insertProject("another", "abcd");
ComponentLinkDto customLink1 = insertCustomLink(project1.uuid());
insertCustomLink(project2.uuid());
+ userSession.logIn().setRoot();
SearchWsResponse response = callByKey(project1.key());
@Test
public void request_does_not_fail_when_link_has_no_name() throws IOException {
- logInAsRoot();
ComponentDto project = db.components().insertProject();
ComponentLinkDto foo = new ComponentLinkDto().setComponentUuid(project.uuid()).setHref("foo").setType("type");
insertLink(foo);
+ logInAsProjectAdministrator(project);
callByKey(project.key());
}
@Test
public void request_does_not_fail_when_link_has_no_type() throws IOException {
- logInAsRoot();
ComponentDto project = db.components().insertProject();
ComponentLinkDto foo = new ComponentLinkDto().setComponentUuid(project.uuid()).setHref("foo").setName("name");
insertLink(foo);
+ logInAsProjectAdministrator(project);
callByKey(project.key());
}
@Test
public void fail_when_both_id_and_key_are_provided() {
ComponentDto project = insertProject();
- logInAsRoot();
+ logInAsProjectAdministrator(project);
expectedException.expect(IllegalArgumentException.class);
ws.newRequest()
assertThat(response.getLinks(0).getName()).isEqualTo("Homepage");
}
- private UserSessionRule logInAsRoot() {
- return userSession.logIn().setRoot();
+ private void logInAsProjectAdministrator(ComponentDto project) {
+ userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
}
}
@Test
public void return_secured_and_license_settings_when_system_admin() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build(),
@Test
public void return_secured_and_license_settings_in_property_set_when_system_admin() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
@Test
public void return_all_settings_when_no_component_and_no_key() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build(),
userSession.logIn().addProjectUuidPermissions(USER, project.uuid());
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private void logInAsProjectAdmin() {
underTest = new QualityGates(dbClient, metricFinder, userSession);
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
}
@Test
@Test
public void deselect_by_id() throws Exception {
- userSession.logIn().setRoot();
+ logInAsRoot();
ComponentDto anotherProject = db.components().insertProject();
String gateId = String.valueOf(gate.getId());
@Test
public void deselect_by_uuid() throws Exception {
- userSession.logIn().setRoot();
+ logInAsRoot();
String gateId = String.valueOf(gate.getId());
associateProjectToQualityGate(project.getId(), gateId);
@Test
public void deselect_by_key() throws Exception {
- userSession.logIn().setRoot();
+ logInAsRoot();
String gateId = String.valueOf(gate.getId());
associateProjectToQualityGate(project.getId(), gateId);
private void assertSelected(String qGateId, long projectId) {
assertThat(dbClient.propertiesDao().selectProjectProperty(projectId, SONAR_QUALITYGATE_PROPERTY).getValue()).isEqualTo(qGateId);
}
+
+ private void logInAsRoot() {
+ userSession.logIn().setRoot();
+ }
}
@Test
public void fail_if_no_snapshot_id_found() {
- userSession.logIn().setRoot();
+ logInAsSystemAdministrator();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Analysis with id 'task-uuid' is not found");
@Test
public void fail_if_project_id_and_ce_task_id_provided() {
- userSession.logIn().setRoot();
+ logInAsSystemAdministrator();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("One (and only one) of the following parameters must be provided 'analysisId', 'projectId', 'projectKey'");
@Test
public void fail_if_no_parameter_provided() {
- userSession.logIn().setRoot();
+ logInAsSystemAdministrator();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("One (and only one) of the following parameters must be provided 'analysisId', 'projectId', 'projectKey'");
throw Throwables.propagate(e);
}
}
+
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
+ }
}
@Test
public void select_by_id() throws Exception {
- userSession.logIn().setRoot();
+ logInAsRoot();
String gateId = String.valueOf(gate.getId());
callById(gateId, project.getId());
@Test
public void select_by_uuid() throws Exception {
- userSession.logIn().setRoot();
+ logInAsRoot();
String gateId = String.valueOf(gate.getId());
callByUuid(gateId, project.uuid());
@Test
public void select_by_key() throws Exception {
- userSession.logIn().setRoot();
+ logInAsRoot();
String gateId = String.valueOf(gate.getId());
callByKey(gateId, project.getKey());
private void assertSelected(String gateId, Long projectId) {
assertThat(dbClient.propertiesDao().selectProjectProperty(projectId, SONAR_QUALITYGATE_PROPERTY).getValue()).isEqualTo(gateId);
}
+
+ private void logInAsRoot() {
+ userSession.logIn().setRoot();
+ }
}
@Test
public void execute_returns_empty_list_of_root_when_DB_is_empty() {
- makeAuthenticatedUserRoot();
+ logInAsRoot();
assertThat(executeRequest()).isEmpty();
}
@Test
- public void execute_does_not_fail_when_root_user_has_neither_email_nor_name() {
- makeAuthenticatedUserRoot();
+ 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();
@Test
public void execute_returns_root_users_sorted_by_name() {
- makeAuthenticatedUserRoot();
+ logInAsRoot();
userDao.insert(dbSession, UserTesting.newUserDto().setName("ddd"));
UserDto root1 = userDao.insert(dbSession, UserTesting.newUserDto().setName("ccc"));
userDao.setRoot(dbSession, root1.getLogin(), true);
.containsExactly("bbb", "ccc");
}
- private UserSessionRule makeAuthenticatedUserRoot() {
+ private UserSessionRule logInAsRoot() {
return userSessionRule.logIn().setRoot();
}
@Test
public void execute_fails_with_IAE_when_login_param_is_not_provided() {
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'login' parameter is missing");
userDao.insert(dbSession, otherUser);
userDao.insert(dbSession, UserTesting.newUserDto(SOME_LOGIN, "name", "email"));
dbSession.commit();
- makeAuthenticatedUserRoot();
+ logInAsRoot();
executeRequest(SOME_LOGIN);
userDao.insert(dbSession, UserTesting.newUserDto(SOME_LOGIN, "name", "email"));
userDao.setRoot(dbSession, SOME_LOGIN, true);
dbSession.commit();
- makeAuthenticatedUserRoot();
+ logInAsRoot();
executeRequest(SOME_LOGIN);
@Test
public void execute_fails_with_NotFoundException_when_user_for_specified_login_does_not_exist() {
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("User with login 'foo_bar' not found");
UserDto userDto = UserTesting.newUserDto().setActive(false);
userDao.insert(dbSession, userDto);
dbSession.commit();
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("User with login '" + userDto.getLogin() + "' not found");
executeRequest(userDto.getLogin());
}
- private void makeAuthenticatedUserRoot() {
+ private void logInAsRoot() {
userSessionRule.logIn().setRoot();
}
@Test
public void execute_fails_with_IAE_when_login_param_is_not_provided() {
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'login' parameter is missing");
public void execute_makes_user_with_specified_login_not_root_when_it_is() {
UserDto otherUser = insertRootUser(newUserDto());
insertRootUser(newUserDto(SOME_LOGIN, "name", "email"));
- makeAuthenticatedUserRoot();
+ logInAsRoot();
executeRequest(SOME_LOGIN);
public void execute_has_no_effect_when_user_is_already_not_root() {
UserDto otherUser = insertRootUser(newUserDto());
insertNonRootUser(newUserDto(SOME_LOGIN, "name", "email"));
- makeAuthenticatedUserRoot();
+ logInAsRoot();
executeRequest(SOME_LOGIN);
public void execute_fails_with_BadRequestException_when_attempting_to_unset_root_on_last_root_user() {
insertRootUser(newUserDto(SOME_LOGIN, "name", "email"));
insertNonRootUser(newUserDto());
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Last root can't be unset");
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);
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Last root can't be unset");
@Test
public void execute_fails_with_NotFoundException_when_user_for_specified_login_does_not_exist() {
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("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));
- makeAuthenticatedUserRoot();
+ logInAsRoot();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("User with login '" + userDto.getLogin() + "' not found");
return dto;
}
- private void makeAuthenticatedUserRoot() {
+ private void logInAsRoot() {
userSessionRule.logIn().setRoot();
}
public static ServerTester tester = new ServerTester().withEsIndexes();
@Rule
- public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester).logIn().setRoot();
+ public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester).logIn().setSystemAdministrator();
WsTester wsTester;
RuleDao ruleDao;
@Test
public void persist_settings() {
- logInAsRoot();
+ logInAsSystemAdministrator();
when(generator.generate("SonarSource", "10.51.42.255")).thenReturn("server_id");
@Test
public void json_example() {
- logInAsRoot();
+ logInAsSystemAdministrator();
when(generator.generate("SonarSource", "127.0.0.1")).thenReturn("1818a1eefb26f9g");
@Test
public void log_message_when_id_generated() {
- logInAsRoot();
+ logInAsSystemAdministrator();
when(generator.generate("SonarSource", "127.0.0.1")).thenReturn("server_id");
call("SonarSource", "127.0.0.1");
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
@Test
public void fail_if_no_organization() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_if_empty_organization() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_if_no_ip() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_if_empty_ip() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
}
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
@Test
public void return_server_id_info() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
when(generator.validate("home", "127.0.0.1", "1818a1eefb26f9g")).thenReturn(true);
setAvailableIpAdresses("192.168.1.1", "127.0.0.1");
@Test
public void return_invalid_server_id() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
when(generator.validate("home", "127.0.0.1", "1818a1eefb26f9g")).thenReturn(true);
insertConfiguration("invalid", null, null);
@Test
public void return_no_server_id_info_when_no_settings_and_no_available_ips() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
ShowWsResponse response = executeRequest();
@Test
public void return_no_server_id_info_when_no_server_id_but_other_settings() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
insertConfiguration(null, "home", "127.0.0.1");
ShowWsResponse response = executeRequest();
@Test
public void return_available_ips_even_if_no_settings() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
setAvailableIpAdresses("192.168.1.1", "127.0.0.1");
ShowWsResponse response = executeRequest();
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void test_example_json_response() {
- logInAsRoot();
+ logInAsSystemAdministrator();
when(generator.validate("home", "127.0.0.1", "1818a1eefb26f9g")).thenReturn(true);
setAvailableIpAdresses("192.168.1.1", "127.0.0.1");
insertConfiguration("1818a1eefb26f9g", "home", "127.0.0.1");
}
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
@Test
public void json_example() throws IOException {
- logInAsRoot();
+ logInAsSystemAdministrator();
File secretKeyFile = temporaryFolder.newFile();
FileUtils.writeStringToFile(secretKeyFile, "fCVFf/JHRi8Qwu5KLNva7g==");
@Test
public void false_when_no_secret_key() {
- logInAsRoot();
+ logInAsSystemAdministrator();
encryption.setPathToSecretKey("unknown/path/to_secret_key.txt");
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
}
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
@Before
public void setUpSecretKey() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
File secretKeyFile = folder.newFile();
FileUtils.writeStringToFile(secretKeyFile, "fCVFf/JHRi8Qwu5KLNva7g==");
@Test
public void json_example() {
- logInAsRoot();
+ logInAsSystemAdministrator();
String result = ws.newRequest().setParam("value", "my value").execute().getInput();
@Test
public void encrypt() {
- logInAsRoot();
+ logInAsSystemAdministrator();
EncryptWsResponse result = call("my value!");
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSession.logIn().setNonRoot();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void fail_if_value_is_not_provided() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_if_value_is_empty() {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Parameter 'value' must not be empty");
@Test
public void fail_if_no_secret_key_available() {
- logInAsRoot();
+ logInAsSystemAdministrator();
encryption.setPathToSecretKey("unknown/path/to/secret/key");
}
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
@Test
public void remove_global_setting() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").build());
propertyDb.insertProperties(newGlobalPropertyDto().setKey("foo").setValue("one"));
@Test
public void remove_global_setting_even_if_not_defined() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
propertyDb.insertProperties(newGlobalPropertyDto().setKey("foo").setValue("one"));
executeRequestOnGlobalSetting("foo");
@Test
public void remove_hidden_setting() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").hidden().build());
propertyDb.insertProperties(newGlobalPropertyDto().setKey("foo").setValue("one"));
@Test
public void ignore_project_setting_when_removing_global_setting() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
propertyDb.insertProperties(newGlobalPropertyDto().setKey("foo").setValue("one"));
propertyDb.insertProperties(newComponentPropertyDto(project).setKey("foo").setValue("value"));
@Test
public void ignore_user_setting_when_removing_global_setting() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
UserDto user = dbClient.userDao().insert(dbSession, UserTesting.newUserDto());
propertyDb.insertProperties(newUserPropertyDto("foo", "one", user));
@Test
public void ignore_unknown_setting_key() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
executeRequestOnGlobalSetting("unknown");
}
@Test
public void remove_setting_by_deprecated_key() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").deprecatedKey("old").build());
propertyDb.insertProperties(newGlobalPropertyDto().setKey("foo").setValue("one"));
@Test
public void empty_204_response() {
- logInAsRoot();
+ logInAsSystemAdministrator();
TestResponse result = ws.newRequest()
.setParam("keys", "my.key")
.execute();
}
@Test
- public void throw_ForbiddenException_if_global_setting_and_not_root() throws Exception {
- userSession.logIn();
+ public void throw_ForbiddenException_if_global_setting_and_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").build());
expectedException.expect(ForbiddenException.class);
executeRequestOnComponentSetting("foo", project);
}
+ @Test
+ public void throw_ForbiddenException_if_project_setting_and_system_administrator() throws Exception {
+ logInAsSystemAdministrator();
+ definitions.addComponent(PropertyDefinition.builder("foo").build());
+
+ expectedException.expect(ForbiddenException.class);
+ expectedException.expectMessage("Insufficient privileges");
+
+ executeRequestOnComponentSetting("foo", project);
+ }
+
@Test
public void fail_when_not_global_and_no_component() {
- logInAsRoot();
+ logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo")
.onlyOnQualifiers(VIEW)
.build());
@Test
public void fail_when_qualifier_not_included() {
- logInAsRoot();
+ userSession.logIn().setRoot();
definitions.addComponent(PropertyDefinition.builder("foo")
.onQualifiers(VIEW)
.build());
@Test
public void fail_to_reset_setting_component_when_setting_is_global() {
- logInAsRoot();
+ userSession.logIn().setRoot();
+
definitions.addComponent(PropertyDefinition.builder("foo").build());
i18n.put("qualifier." + PROJECT, "project");
request.execute();
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private void logInAsProjectAdmin() {
import java.net.HttpURLConnection;
import java.util.List;
import javax.annotation.Nullable;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private WsActionTester ws = new WsActionTester(underTest);
+ @Before
+ public void setUp() {
+ // by default test doesn't care about permissions
+ userSession.logIn().setSystemAdministrator();
+ }
+
@Test
public void empty_204_response() {
TestResponse result = ws.newRequest()
public void persist_new_project_setting() {
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my global value"));
ComponentDto project = db.components().insertProject();
+ logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "my project value", project.key());
@Test
public void persist_project_property_with_project_admin_permission() {
ComponentDto project = db.components().insertProject();
- userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
+ logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "my value", project.key());
ComponentDto project = db.components().insertProject();
propertyDb.insertProperty(newComponentPropertyDto("my.key", "my project value", project));
assertComponentSetting("my.key", "my project value", project.getId());
+ logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "my new project value", project.key());
newComponentPropertyDto("my.key", "1", project),
newComponentPropertyDto("my.key.1.firstField", "componentFirstValue", project),
newComponentPropertyDto("my.key.1.firstField", "componentSecondValue", project));
+ logInAsProjectAdministrator(project);
callForComponentPropertySet("my.key", newArrayList(
GSON.toJson(ImmutableMap.of("firstField", "firstValue", "secondField", "secondValue")),
}
@Test
- public void throw_ForbiddenException_if_not_root() {
- userSession.logIn();
+ public void throw_ForbiddenException_if_not_system_administrator() {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
i18n.put("qualifier." + Qualifiers.VIEW, "View");
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Setting 'my.key' cannot be set on a View");
+ logInAsProjectAdministrator(view);
callForProjectSettingByKey("my.key", "My Value", view.key());
}
.build());
i18n.put("qualifier." + Qualifiers.PROJECT, "Project");
ComponentDto project = db.components().insertProject();
+ logInAsProjectAdministrator(project);
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Setting 'my.key' cannot be set on a Project");
}
private static class FakeSettingsNotifier extends SettingsChangeNotifier {
- private final DbClient dbClient;
+ private final DbClient dbClient;
private boolean wasCalled = false;
private FakeSettingsNotifier(DbClient dbClient) {
assertThat(property.getValue()).isEqualTo(value);
}
+
+ }
+ private void logInAsProjectAdministrator(ComponentDto project) {
+ userSession.logIn().addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
}
}
@Override
public boolean isSystemAdministrator() {
- return systemAdministrator;
+ return isRoot() || systemAdministrator;
}
}
return currentUserSession.isRoot();
}
- @Override
- public UserSession checkIsRoot() {
- currentUserSession.checkIsRoot();
- return this;
- }
-
@Override
public UserSession checkLoggedIn() {
currentUserSession.checkLoggedIn();
private WsActionTester ws;
@Test
- public void empty() throws Exception {
+ public void empty() {
init();
- userSessionRule.logIn().setRoot();
+ logInAsSystemAdministrator();
executeAndVerify("empty.json");
}
@Test
- public void with_pages() throws Exception {
+ public void returns_page_settings() {
init(createPages());
- userSessionRule.logIn().setRoot();
+ logInAsSystemAdministrator();
executeAndVerify("with_pages.json");
}
@Test
- public void with_update_center() throws Exception {
+ public void returns_update_center_settings() {
init();
settings.setProperty(WebConstants.SONAR_UPDATECENTER_ACTIVATE, true);
- userSessionRule.logIn().setRoot();
+ logInAsSystemAdministrator();
executeAndVerify("with_update_center.json");
}
@Test
- public void with_views_and_update_center_but_not_root_administrator() throws Exception {
+ public void request_succeeds_but_settings_are_not_returned_when_user_is_not_system_administrator() {
init(createPages());
settings.setProperty(WebConstants.SONAR_UPDATECENTER_ACTIVATE, true);
- userSessionRule.logIn().setNonRoot();
+ userSessionRule.logIn().setNonSystemAdministrator();
executeAndVerify("empty.json");
}
return new Page[] {firstPage, secondPage};
}
+
+ private void logInAsSystemAdministrator() {
+ userSessionRule.logIn().setSystemAdministrator();
+ }
}
@Test
public void upload_plugin() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
TestResponse response = call(newInputStream(plugin.toPath()), PLUGIN_NAME);
@Test
public void erase_existing_plugin_if_already_exists() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
File plugin1 = new File(getClass().getResource("UploadActionTest/plugin.jar").getFile());
call(newInputStream(plugin1.toPath()), PLUGIN_NAME);
@Test
public void fail_when_plugin_extension_is_not_jar() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Only jar file is allowed");
@Test
public void fail_when_no_files_param() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'file' parameter is missing");
@Test
public void input_stream_should_be_closed() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
InputStream inputStream = newInputStream(plugin.toPath());
call(inputStream, PLUGIN_NAME);
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSession.logIn();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Insufficient privileges");
.execute();
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private void assertPluginIsUploaded(String pluginName) {
assertThat(newUserSession(NON_ROOT_USER_DTO).isRoot()).isFalse();
}
- @Test
- public void checkIsRoot_fails_with_ForbiddenException_when_flag_is_false_on_UserDto() {
- expectInsufficientPrivilegesForbiddenException();
-
- newUserSession(NON_ROOT_USER_DTO).checkIsRoot();
- }
-
- @Test
- public void checkIsRoot_does_not_fails_when_flag_is_true_on_UserDto() {
- ServerUserSession underTest = newUserSession(ROOT_USER_DTO);
-
- assertThat(underTest.checkIsRoot()).isSameAs(underTest);
- }
-
@Test
public void hasComponentUuidPermission_returns_true_if_user_has_project_permission_for_given_uuid_in_db() {
addProjectPermissions(project, UserRole.USER);
@Test
public void fail_on_unknown_user() throws Exception {
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
expectedException.expect(NotFoundException.class);
}
@Test
- public void root_can_update_password_of_user() throws Exception {
- userSessionRule.logIn().setRoot();
+ public void system_administrator_can_update_password_of_user() throws Exception {
+ userSessionRule.logIn().setSystemAdministrator();
createUser();
String originalPassword = db.getDbClient().userDao().selectOrFailByLogin(db.getSession(), "john").getCryptedPassword();
@Test
public void fail_to_update_password_on_external_auth() throws Exception {
- userSessionRule.logIn().setRoot();
+ userSessionRule.logIn().setSystemAdministrator();
userUpdater.create(NewUser.builder()
.setEmail("john@email.com")
@Test
public void create_user() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
CreateWsResponse response = call(CreateRequest.builder()
.setLogin("john")
@Test
public void create_local_user() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
call(CreateRequest.builder()
.setLogin("john")
@Test
public void create_none_local_user() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
call(CreateRequest.builder()
.setLogin("john")
@Test
public void create_user_with_comma_in_scm_account() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
CreateWsResponse response = call(CreateRequest.builder()
.setLogin("john")
@Test
public void create_user_with_deprecated_scmAccounts_parameter() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
tester.newRequest()
.setParam("login", "john")
@Test
public void create_user_with_deprecated_scm_accounts_parameter() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
tester.newRequest()
.setParam("login", "john")
@Test
public void reactivate_user() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
db.users().insertUser(newUserDto("john", "John", "john@email.com"));
db.getDbClient().userDao().deactivateUserByLogin(db.getSession(), "john");
OrganizationDto otherOrganization = db.organizations().insert();
GroupDto group = db.users().insertGroup(otherOrganization);
setDefaultGroupProperty(group);
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(ServerException.class);
expectedException.expectMessage("The default group '" + group.getName() + "' for new users does not exist. " +
@Test
public void fail_when_missing_login() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Login is mandatory and must not be empty");
@Test
public void fail_when_missing_name() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Name is mandatory and must not be empty");
@Test
public void fail_when_missing_password() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Password is mandatory and must not be empty");
@Test
public void fail_when_password_is_set_on_none_local_user() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Password should only be set on local user");
}
@Test
- public void throw_ForbiddenException_if_not_root() throws Exception {
- userSessionRule.logIn();
+ public void throw_ForbiddenException_if_not_system_administrator() throws Exception {
+ userSessionRule.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("");
.build());
}
- private void logInAsRoot() {
- userSessionRule.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSessionRule.logIn().setSystemAdministrator();
}
private CreateWsResponse call(CreateRequest createRequest) {
.setEmail("ada.lovelace@noteg.com")
.setName("Ada Lovelace")
.setScmAccounts(singletonList("al")));
- logInAsRoot();
+ logInAsSystemAdministrator();
String json = deactivate(user.getLogin()).getInput();
@Test
public void cannot_deactivate_self() throws Exception {
UserDto user = createUser();
- userSession.logIn(user.getLogin()).setRoot();
+ userSession.logIn(user.getLogin()).setSystemAdministrator();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Self-deactivation is not possible");
@Test
public void fail_if_user_does_not_exist() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("User 'someone' doesn't exist");
@Test
public void fail_if_login_is_blank() throws Exception {
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("User '' doesn't exist");
public void fail_to_deactivate_last_administrator_of_default_organization() throws Exception {
UserDto admin = createUser();
db.users().insertPermissionOnUser(admin, SYSTEM_ADMIN);
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("User is last administrator, and cannot be deactivated");
db.users().insertPermissionOnUser(org3, user1, SYSTEM_ADMIN);
UserDto user2 = createUser();
db.users().insertPermissionOnUser(org3, user2, SYSTEM_ADMIN);
- logInAsRoot();
+ logInAsSystemAdministrator();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("User is last administrator of organizations [org1, org2], and cannot be deactivated");
db.users().insertPermissionOnUser(admin, SYSTEM_ADMIN);
db.users().insertPermissionOnUser(anotherAdmin, SYSTEM_ADMIN);
db.commit();
- logInAsRoot();
+ logInAsSystemAdministrator();
deactivate(admin.getLogin());
return user;
}
- private void logInAsRoot() {
- userSession.logIn().setRoot();
+ private void logInAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private TestResponse deactivate(String login) {
session.commit();
tester = new WsTester(new UsersWs(new GroupsAction(dbClient, userSession)));
- userSession.logIn().setRoot();
+ userSession.logIn().setSystemAdministrator();
}
@After
dbClient.userTokenDao().insert(dbSession, newUserToken().setLogin(fmallet.getLogin()));
db.commit();
userIndexer.index();
- loginAsRoot();
+ loginAsSystemAdministrator();
String response = ws.newGetRequest("api/users", "search").execute().outputAsString();
.doesNotContain("scmAccounts")
.doesNotContain("groups");
- loginAsRoot();
+ loginAsSystemAdministrator();
assertThat(ws.newGetRequest("api/users", "search").execute().outputAsString())
.contains("login")
@Test
public void search_with_groups() throws Exception {
- loginAsRoot();
+ loginAsSystemAdministrator();
List<UserDto> users = injectUsers(1);
GroupDto group1 = dbClient.groupDao().insert(dbSession, newGroupDto().setName("sonar-users"));
return userDtos;
}
- private void loginAsRoot() {
- userSession.logIn().setRoot();
+ private void loginAsSystemAdministrator() {
+ userSession.logIn().setSystemAdministrator();
}
private void loginAsSimpleUser() {
@Rule
public EsTester esTester = new EsTester(new UserIndexDefinition(settings));
@Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn().setRoot();
+ public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn().setSystemAdministrator();
private DbClient dbClient = dbTester.getDbClient();
private DbSession session = dbTester.getSession();