From: Simon Brandhof Date: Sun, 29 Jan 2017 18:52:26 +0000 (+0100) Subject: SONAR-8716 Use UserSession#checkComponentPermission(String,ComponentDto) X-Git-Tag: 6.3-RC1~265 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=6ff19c3990f4f127bec8cdcc5c83ef29cb4f75c4;p=sonarqube.git SONAR-8716 Use UserSession#checkComponentPermission(String,ComponentDto) --- diff --git a/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ActivityStatusAction.java b/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ActivityStatusAction.java index b8e09db8b56..0e6191e460d 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ActivityStatusAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ActivityStatusAction.java @@ -21,7 +21,6 @@ package org.sonar.server.ce.ws; import com.google.common.base.Optional; -import javax.annotation.Nullable; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -85,7 +84,7 @@ public class ActivityStatusAction implements CeWsAction { try { Optional component = searchComponent(dbSession, request); String componentUuid = component.isPresent() ? component.get().uuid() : null; - checkPermissions(componentUuid); + checkPermissions(component); int pendingCount = dbClient.ceQueueDao().countByStatusAndComponentUuid(dbSession, CeQueueDto.Status.PENDING, componentUuid); int failingCount = dbClient.ceActivityDao().countLastByStatusAndComponentUuid(dbSession, CeActivityDto.Status.FAILED, componentUuid); @@ -106,11 +105,11 @@ public class ActivityStatusAction implements CeWsAction { return Optional.fromNullable(component); } - private void checkPermissions(@Nullable String componentUuid) { - if (componentUuid == null) { - userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); + private void checkPermissions(Optional component) { + if (component.isPresent()) { + userSession.checkComponentPermission(UserRole.ADMIN, component.get()); } else { - userSession.checkComponentUuidPermission(UserRole.ADMIN, componentUuid); + userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ComponentAction.java b/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ComponentAction.java index a994c25cecb..1c871e3331b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ComponentAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/ce/ws/ComponentAction.java @@ -83,7 +83,7 @@ public class ComponentAction implements CeWsAction { DbSession dbSession = dbClient.openSession(false); try { ComponentDto component = componentFinder.getByUuidOrKey(dbSession, wsRequest.param(PARAM_COMPONENT_ID), wsRequest.param(PARAM_COMPONENT_KEY), COMPONENT_ID_AND_KEY); - userSession.checkComponentUuidPermission(UserRole.USER, component.uuid()); + userSession.checkComponentPermission(UserRole.USER, component); List queueDtos = dbClient.ceQueueDao().selectByComponentUuid(dbSession, component.uuid()); CeTaskQuery activityQuery = new CeTaskQuery() .setComponentUuid(component.uuid()) diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java b/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java index 18f973d2c1c..484024826f1 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java @@ -57,7 +57,7 @@ public class ComponentService { // TODO should be moved to ComponentUpdater public void updateKey(DbSession dbSession, ComponentDto component, String newKey) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid()); + userSession.checkComponentPermission(UserRole.ADMIN, component); checkIsProjectOrModule(component); checkProjectOrModuleKeyFormat(newKey); dbClient.componentKeyUpdaterDao().updateKey(component.uuid(), newKey); diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java b/server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java index 8b0adf82cfb..eb9dee249a1 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java @@ -100,7 +100,7 @@ public class AppAction implements RequestHandler { DbSession session = dbClient.openSession(false); try { ComponentDto component = componentFinder.getByUuid(session, componentUuid); - userSession.checkComponentUuidPermission(UserRole.USER, component.uuid()); + userSession.checkComponentPermission(UserRole.USER, component); Map measuresByMetricKey = measuresByMetricKey(component, session); appendComponent(json, component, userSession, session); diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/ws/BulkUpdateKeyAction.java b/server/sonar-server/src/main/java/org/sonar/server/component/ws/BulkUpdateKeyAction.java index 76f4e4c6036..52116dbe2e1 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/ws/BulkUpdateKeyAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/ws/BulkUpdateKeyAction.java @@ -124,7 +124,7 @@ public class BulkUpdateKeyAction implements ComponentsWsAction { try { ComponentDto projectOrModule = componentFinder.getByUuidOrKey(dbSession, request.getId(), request.getKey(), ParamNames.ID_AND_KEY); checkIsProjectOrModule(projectOrModule); - userSession.checkComponentUuidPermission(UserRole.ADMIN, projectOrModule.uuid()); + userSession.checkComponentPermission(UserRole.ADMIN, projectOrModule); Map newKeysByOldKeys = componentKeyUpdater.simulateBulkUpdateKey(dbSession, projectOrModule.uuid(), request.getFrom(), request.getTo()); Map newKeysWithDuplicateMap = componentKeyUpdater.checkComponentKeys(dbSession, ImmutableList.copyOf(newKeysByOldKeys.values())); diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/queue/ReportSubmitter.java b/server/sonar-server/src/main/java/org/sonar/server/computation/queue/ReportSubmitter.java index fe3170cfc73..a3c345a1f68 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/queue/ReportSubmitter.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/queue/ReportSubmitter.java @@ -76,7 +76,7 @@ public class ReportSubmitter { Optional opt = dbClient.componentDao().selectByKey(dbSession, effectiveProjectKey); ensureOrganizationIsConsistent(opt, organizationDto); ComponentDto project = opt.or(() -> createProject(dbSession, organizationDto.getUuid(), projectKey, projectBranch, projectName)); - userSession.checkComponentUuidPermission(SCAN_EXECUTION, project.uuid()); + userSession.checkComponentPermission(SCAN_EXECUTION, project); return submitReport(dbSession, reportInput, project); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java b/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java index b052a8a8068..3f0aa8f9ade 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java @@ -33,7 +33,6 @@ import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; -import org.sonar.db.measure.MeasureDao; import org.sonar.db.measure.MeasureDto; import org.sonar.db.measure.MeasureQuery; import org.sonar.server.component.ComponentFinder; @@ -44,16 +43,14 @@ import static org.sonar.server.component.ComponentFinder.ParamNames.UUID_AND_KEY public class ShowAction implements RequestHandler { private final DbClient dbClient; - private final MeasureDao measureDao; private final DuplicationsParser parser; private final DuplicationsJsonWriter duplicationsJsonWriter; private final UserSession userSession; private final ComponentFinder componentFinder; - public ShowAction(DbClient dbClient, MeasureDao measureDao, DuplicationsParser parser, - DuplicationsJsonWriter duplicationsJsonWriter, UserSession userSession, ComponentFinder componentFinder) { + public ShowAction(DbClient dbClient, DuplicationsParser parser, + DuplicationsJsonWriter duplicationsJsonWriter, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; - this.measureDao = measureDao; this.parser = parser; this.duplicationsJsonWriter = duplicationsJsonWriter; this.userSession = userSession; @@ -83,7 +80,7 @@ public class ShowAction implements RequestHandler { DbSession dbSession = dbClient.openSession(false); try { ComponentDto component = componentFinder.getByUuidOrKey(dbSession, request.param("uuid"), request.param("key"), UUID_AND_KEY); - userSession.checkComponentPermission(UserRole.CODEVIEWER, component.key()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, component); JsonWriter json = response.newJsonWriter().beginObject(); String duplications = findDataFromComponent(dbSession, component); List blocks = parser.parse(component, duplications, dbSession); @@ -100,7 +97,7 @@ public class ShowAction implements RequestHandler { .setComponentUuid(component.uuid()) .setMetricKey(CoreMetrics.DUPLICATIONS_DATA_KEY) .build(); - Optional measure = measureDao.selectSingle(dbSession, query); + Optional measure = dbClient.measureDao().selectSingle(dbSession, query); return measure.isPresent() ? measure.get().getData() : null; } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/favorite/ws/AddAction.java b/server/sonar-server/src/main/java/org/sonar/server/favorite/ws/AddAction.java index 94919aa1cff..6689fe62f64 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/favorite/ws/AddAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/favorite/ws/AddAction.java @@ -75,7 +75,7 @@ public class AddAction implements FavoritesWsAction { ComponentDto componentDto = componentFinder.getByKey(dbSession, request.mandatoryParam(PARAM_COMPONENT)); userSession .checkLoggedIn() - .checkComponentUuidPermission(UserRole.USER, componentDto.uuid()); + .checkComponentPermission(UserRole.USER, componentDto); favoriteUpdater.add(dbSession, componentDto, userSession.isLoggedIn() ? userSession.getUserId().longValue() : null); dbSession.commit(); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/CustomMeasureValidator.java b/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/CustomMeasureValidator.java index 8d215e83dc9..35afa3e91a7 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/CustomMeasureValidator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/CustomMeasureValidator.java @@ -99,6 +99,6 @@ public class CustomMeasureValidator { return; } - userSession.checkLoggedIn().checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid()); + userSession.checkLoggedIn().checkComponentPermission(UserRole.ADMIN, component); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/DeleteAction.java b/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/DeleteAction.java index 980d9552cb8..58e0a7dd55e 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/DeleteAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/DeleteAction.java @@ -81,6 +81,6 @@ public class DeleteAction implements CustomMeasuresWsAction { } ComponentDto component = dbClient.componentDao().selectOrFailByUuid(dbSession, customMeasure.getComponentUuid()); - userSession.checkLoggedIn().checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid()); + userSession.checkLoggedIn().checkComponentPermission(UserRole.ADMIN, component); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/measure/ws/SearchHistoryAction.java b/server/sonar-server/src/main/java/org/sonar/server/measure/ws/SearchHistoryAction.java index 9b9992e5ec7..2fe2c3ee121 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/measure/ws/SearchHistoryAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/measure/ws/SearchHistoryAction.java @@ -143,7 +143,7 @@ public class SearchHistoryAction implements MeasuresWsAction { private ComponentDto searchComponent(SearchHistoryRequest request, DbSession dbSession) { ComponentDto component = componentFinder.getByKey(dbSession, request.getComponent()); - userSession.checkComponentUuidPermission(UserRole.USER, component.projectUuid()); + userSession.checkComponentPermission(UserRole.USER, component); return component; } diff --git a/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/CreateEventAction.java b/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/CreateEventAction.java index 078ca3cf5a5..fbe5927ba40 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/CreateEventAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/CreateEventAction.java @@ -113,18 +113,13 @@ public class CreateEventAction implements ProjectAnalysesWsAction { private CreateEventResponse doHandle(CreateEventRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { SnapshotDto analysis = getAnalysis(dbSession, request); - checkPermissions(analysis); checkExistingDbEvents(dbSession, request, analysis); EventDto dbEvent = insertDbEvent(dbSession, request, analysis); return toCreateEventResponse(dbEvent); } } - private void checkPermissions(SnapshotDto analysis) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, analysis.getComponentUuid()); - } - - private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) { + private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) { EventDto dbEvent = dbClient.eventDao().insert(dbSession, toDbEvent(request, analysis)); if (VERSION.equals(request.getCategory())) { analysis.setVersion(request.getName()); @@ -139,6 +134,7 @@ public class CreateEventAction implements ProjectAnalysesWsAction { .orElseThrow(() -> new NotFoundException(format("Analysis '%s' is not found", request.getAnalysis()))); ComponentDto project = dbClient.componentDao().selectByUuid(dbSession, analysis.getComponentUuid()).orNull(); checkState(project != null, "Project of analysis '%s' is not found", analysis.getUuid()); + userSession.checkComponentPermission(UserRole.ADMIN, project); checkArgument(Qualifiers.PROJECT.equals(project.qualifier()) && Scopes.PROJECT.equals(project.scope()), "An event must be created on a project"); return analysis; diff --git a/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchAction.java b/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchAction.java index 39235dd8e56..d8ea7986946 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchAction.java @@ -125,7 +125,7 @@ public class SearchAction implements ProjectAnalysesWsAction { private Consumer addAnalyses() { return data -> { SnapshotQuery dbQuery = new SnapshotQuery() - .setComponentUuid(data.getProjectUuid()) + .setComponentUuid(data.getProject().uuid()) .setStatus(SnapshotDto.STATUS_PROCESSED) .setSort(BY_DATE, DESC); data.setAnalyses(dbClient.snapshotDao().selectAnalysesByQuery(data.getDbSession(), dbQuery)); @@ -140,14 +140,14 @@ public class SearchAction implements ProjectAnalysesWsAction { } private Consumer checkPermission() { - return data -> userSession.checkComponentUuidPermission(UserRole.USER, data.getProjectUuid()); + return data -> userSession.checkComponentPermission(UserRole.USER, data.getProject()); } private Consumer addProject() { return data -> { ComponentDto project = componentFinder.getByKey(data.getDbSession(), data.getRequest().getProject()); checkArgument(Scopes.PROJECT.equals(project.scope()) && Qualifiers.PROJECT.equals(project.qualifier()), "A project is required"); - data.setProjectUuid(project.uuid()); + data.setProject(project); }; } diff --git a/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchResults.java b/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchResults.java index 30d1d9afe3f..9a262ebe6b1 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchResults.java +++ b/server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchResults.java @@ -27,6 +27,7 @@ import java.util.stream.Stream; import org.sonar.api.utils.Paging; import org.sonar.core.util.stream.Collectors; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import org.sonarqube.ws.client.projectanalysis.SearchRequest; @@ -58,7 +59,7 @@ class SearchResults { static class Builder { private final DbSession dbSession; private final SearchRequest request; - private String projectUuid; + private ComponentDto project; private List analyses; private int countAnalyses; private List events; @@ -68,8 +69,8 @@ class SearchResults { this.request = request; } - Builder setProjectUuid(String projectUuid) { - this.projectUuid = projectUuid; + Builder setProject(ComponentDto project) { + this.project = project; return this; } @@ -100,8 +101,8 @@ class SearchResults { return request; } - String getProjectUuid() { - return projectUuid; + ComponentDto getProject() { + return project; } List getAnalyses() { diff --git a/server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java b/server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java index bc49aa36636..6fbf10865dd 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java @@ -106,7 +106,7 @@ public class CreateAction implements ProjectLinksWsAction { try { ComponentDto component = getComponentByUuidOrKey(dbSession, createWsRequest); - userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid()); + userSession.checkComponentPermission(UserRole.ADMIN, component); ComponentLinkDto link = new ComponentLinkDto() .setComponentUuid(component.uuid()) diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java index 4e99ea40af0..2d604e41001 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java @@ -46,7 +46,7 @@ public class QProfileProjectOperations { } public void addProject(DbSession dbSession, String profileKey, ComponentDto project) { - checkAdminOnProject(project.key()); + checkAdminOnProject(project); QualityProfileDto qualityProfile = selectProfileByKey(dbSession, profileKey); QualityProfileDto currentProfile = db.qualityProfileDao().selectByProjectAndLanguage(dbSession, project.key(), qualityProfile.getLanguage()); @@ -65,7 +65,7 @@ public class QProfileProjectOperations { } public void removeProject(DbSession dbSession, String profileKey, ComponentDto project) { - checkAdminOnProject(project.key()); + checkAdminOnProject(project); QualityProfileDto qualityProfile = selectProfileByKey(dbSession, profileKey); db.qualityProfileDao().deleteProjectProfileAssociation(project.uuid(), qualityProfile.getKey(), dbSession); @@ -77,8 +77,9 @@ public class QProfileProjectOperations { return WsUtils.checkFound(qualityProfile, "Quality profile does not exist"); } - private void checkAdminOnProject(String projectKey) { - if (!userSession.hasPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) && !userSession.hasComponentPermission(UserRole.ADMIN, projectKey)) { + private void checkAdminOnProject(ComponentDto project) { + if (!userSession.hasPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) && + !userSession.hasComponentPermission(UserRole.ADMIN, project)) { throw new ForbiddenException("Insufficient privileges"); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ListDefinitionsAction.java b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ListDefinitionsAction.java index 64c579df94b..5828bf7f105 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ListDefinitionsAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ListDefinitionsAction.java @@ -115,7 +115,7 @@ public class ListDefinitionsAction implements SettingsWsAction { return Optional.empty(); } ComponentDto component = componentFinder.getByKey(dbSession, componentKey); - userSession.checkComponentUuidPermission(USER, component.projectUuid()); + userSession.checkComponentPermission(USER, component); return Optional.of(component); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ResetAction.java b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ResetAction.java index d5bb53bbd4b..10e76bb1583 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ResetAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ResetAction.java @@ -140,7 +140,7 @@ public class ResetAction implements SettingsWsAction { private void checkPermissions(Optional component) { if (component.isPresent()) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, component.get().uuid()); + userSession.checkComponentPermission(UserRole.ADMIN, component.get()); } else { userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/SetAction.java b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/SetAction.java index 72c86c5a6a2..7ac07f678af 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/SetAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/SetAction.java @@ -271,7 +271,7 @@ public class SetAction implements SettingsWsAction { private void checkPermissions(Optional component) { if (component.isPresent()) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, component.get().uuid()); + userSession.checkComponentPermission(UserRole.ADMIN, component.get()); } else { userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ValuesAction.java b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ValuesAction.java index 0c5f07695af..175d494989d 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ValuesAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ValuesAction.java @@ -143,7 +143,7 @@ public class ValuesAction implements SettingsWsAction { return Optional.empty(); } ComponentDto component = componentFinder.getByKey(dbSession, componentKey); - userSession.checkComponentUuidPermission(USER, component.projectUuid()); + userSession.checkComponentPermission(USER, component); return Optional.of(component); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/ws/HashAction.java b/server/sonar-server/src/main/java/org/sonar/server/source/ws/HashAction.java index d68548fe9fb..4067064ffcf 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/ws/HashAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/ws/HashAction.java @@ -68,25 +68,19 @@ public class HashAction implements SourcesWsAction { @Override public void handle(Request request, Response response) throws Exception { - DbSession session = dbClient.openSession(false); - try { - final String componentKey = request.mandatoryParam("key"); - final ComponentDto component = componentFinder.getByKey(session, componentKey); - userSession.checkComponentUuidPermission(UserRole.USER, component.projectUuid()); + try (DbSession session = dbClient.openSession(false)) { + String componentKey = request.mandatoryParam("key"); + ComponentDto component = componentFinder.getByKey(session, componentKey); + userSession.checkComponentPermission(UserRole.USER, component); response.stream().setMediaType("text/plain"); - OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8); - try { + try (OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8)) { HashFunction hashFunction = new HashFunction(writer, componentKey); dbClient.fileSourceDao().readLineHashesStream(session, component.uuid(), hashFunction); if (!hashFunction.hasData()) { response.noContent(); } - } finally { - writer.close(); } - } finally { - session.close(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/ws/IndexAction.java b/server/sonar-server/src/main/java/org/sonar/server/source/ws/IndexAction.java index 3cce651eb11..3a1140f65ca 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/ws/IndexAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/ws/IndexAction.java @@ -75,12 +75,12 @@ public class IndexAction implements SourcesWsAction { @Override public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("resource"); - userSession.checkComponentPermission(UserRole.CODEVIEWER, fileKey); int from = request.mandatoryParamAsInt("from"); Integer to = request.paramAsInt("to"); try (DbSession session = dbClient.openSession(false)) { - ComponentDto componentDto = componentFinder.getByKey(session, fileKey); - Optional> lines = sourceService.getLinesAsRawText(session, componentDto.uuid(), from, to == null ? Integer.MAX_VALUE : to - 1); + ComponentDto component = componentFinder.getByKey(session, fileKey); + userSession.checkComponentPermission(UserRole.CODEVIEWER, component); + Optional> lines = sourceService.getLinesAsRawText(session, component.uuid(), from, to == null ? Integer.MAX_VALUE : to - 1); JsonWriter json = response.newJsonWriter().beginArray().beginObject(); if (lines.isPresent()) { int lineCounter = from; diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/ws/LinesAction.java b/server/sonar-server/src/main/java/org/sonar/server/source/ws/LinesAction.java index 0d24edaa0f9..fc9fa859095 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/ws/LinesAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/ws/LinesAction.java @@ -115,7 +115,7 @@ public class LinesAction implements SourcesWsAction { DbSession dbSession = dbClient.openSession(false); try { ComponentDto file = componentFinder.getByUuidOrKey(dbSession, request.param(PARAM_UUID), request.param(PARAM_KEY), UUID_AND_KEY); - userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, file); int from = request.mandatoryParamAsInt(PARAM_FROM); int to = MoreObjects.firstNonNull(request.paramAsInt(PARAM_TO), Integer.MAX_VALUE); diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/ws/RawAction.java b/server/sonar-server/src/main/java/org/sonar/server/source/ws/RawAction.java index 5ac187b8999..97b65e84f4b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/ws/RawAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/ws/RawAction.java @@ -67,10 +67,10 @@ public class RawAction implements SourcesWsAction { @Override public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("key"); - DbSession dbSession = dbClient.openSession(false); - try { + + try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto file = componentFinder.getByKey(dbSession, fileKey); - userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, file); Optional> lines = sourceService.getLinesAsRawText(dbSession, file.uuid(), 1, Integer.MAX_VALUE); response.stream().setMediaType("text/plain"); @@ -83,8 +83,6 @@ public class RawAction implements SourcesWsAction { } } catch (IOException e) { throw new IllegalStateException("Fail to write raw source of file " + fileKey, e); - } finally { - dbClient.closeSession(dbSession); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/ws/ScmAction.java b/server/sonar-server/src/main/java/org/sonar/server/source/ws/ScmAction.java index 22b9d6d9db6..e857f2e5857 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/ws/ScmAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/ws/ScmAction.java @@ -104,7 +104,7 @@ public class ScmAction implements SourcesWsAction { DbSession dbSession = dbClient.openSession(false); try { ComponentDto file = componentFinder.getByKey(dbSession, fileKey); - userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, file); Optional> sourceLines = sourceService.getLines(dbSession, file.uuid(), from, to); if (!sourceLines.isPresent()) { throw new NotFoundException(String.format("File '%s' has no sources", fileKey)); diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/ws/ShowAction.java b/server/sonar-server/src/main/java/org/sonar/server/source/ws/ShowAction.java index 9f76747a8b7..56ba7b260b1 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/ws/ShowAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/ws/ShowAction.java @@ -89,7 +89,7 @@ public class ShowAction implements SourcesWsAction { DbSession dbSession = dbClient.openSession(false); try { ComponentDto file = componentFinder.getByKey(dbSession, fileKey); - userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, file); Optional> linesHtml = sourceService.getLinesAsHtml(dbSession, file.uuid(), from, to); if (linesHtml.isPresent()) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/test/ws/ListAction.java b/server/sonar-server/src/main/java/org/sonar/server/test/ws/ListAction.java index a9f1251e82d..5c824be2651 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/test/ws/ListAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/test/ws/ListAction.java @@ -228,7 +228,7 @@ public class ListAction implements TestsWsAction { private SearchResult searchTestsByTestFileKey(DbSession dbSession, String testFileKey, SearchOptions searchOptions) { ComponentDto testFile = componentFinder.getByKey(dbSession, testFileKey); - userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, testFile.projectUuid()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, testFile); return testIndex.searchByTestFileUuid(testFile.uuid(), searchOptions); } @@ -245,7 +245,7 @@ public class ListAction implements TestsWsAction { private void checkComponentUuidPermission(DbSession dbSession, String componentUuid) { ComponentDto component = componentFinder.getByUuid(dbSession, componentUuid); - userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, component.projectUuid()); + userSession.checkComponentPermission(UserRole.CODEVIEWER, component); } private static class TestToFileUuidFunction implements Function { diff --git a/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveriesAction.java b/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveriesAction.java index 680a2e186f2..6ea749b1160 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveriesAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveriesAction.java @@ -126,7 +126,7 @@ public class WebhookDeliveriesAction implements WebhooksWsAction { void ensureAdminPermission(UserSession userSession) { if (component != null) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid()); + userSession.checkComponentPermission(UserRole.ADMIN, component); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveryAction.java b/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveryAction.java index cec10909c95..af891c9b51e 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveryAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveryAction.java @@ -98,7 +98,7 @@ public class WebhookDeliveryAction implements WebhooksWsAction { } void ensureAdminPermission(UserSession userSession) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid()); + userSession.checkComponentPermission(UserRole.ADMIN, component); } void writeTo(Request request, Response response) { diff --git a/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/DuplicationsWsTest.java b/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/DuplicationsWsTest.java index 4672e4273f7..6c21339b8ab 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/DuplicationsWsTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/DuplicationsWsTest.java @@ -23,7 +23,6 @@ import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; -import org.sonar.db.measure.MeasureDao; import org.sonar.server.component.ComponentFinder; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsTester; @@ -36,7 +35,7 @@ public class DuplicationsWsTest { public UserSessionRule userSessionRule = UserSessionRule.standalone(); WsTester tester = new WsTester(new DuplicationsWs( - new ShowAction(mock(DbClient.class), mock(MeasureDao.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class), userSessionRule, + new ShowAction(mock(DbClient.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class), userSessionRule, mock(ComponentFinder.class)))); @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java index 8e11b903df5..a89f499fea9 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java @@ -19,137 +19,121 @@ */ package org.sonar.server.duplication.ws; -import com.google.common.base.Optional; -import com.google.common.collect.Lists; -import java.util.List; +import java.util.function.Function; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.sonar.api.utils.text.JsonWriter; +import org.junit.rules.ExpectedException; +import org.sonar.api.measures.CoreMetrics; import org.sonar.api.web.UserRole; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.component.ComponentDao; +import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; -import org.sonar.db.measure.MeasureDao; -import org.sonar.db.measure.MeasureDto; -import org.sonar.db.measure.MeasureQuery; +import org.sonar.db.component.SnapshotDto; +import org.sonar.db.metric.MetricDto; import org.sonar.server.component.ComponentFinder; +import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; +import org.sonar.server.startup.RegisterMetrics; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsTester; -import static com.google.common.collect.Lists.newArrayList; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.sonar.db.component.ComponentTesting.newFileDto; +import static org.sonar.db.component.SnapshotTesting.newAnalysis; +import static org.sonar.db.measure.MeasureTesting.newMeasureDto; -@RunWith(MockitoJUnitRunner.class) public class ShowActionTest { @Rule - public UserSessionRule userSessionRule = UserSessionRule.standalone(); - - @Mock - DbSession session; - - @Mock - DbClient dbClient; + public ExpectedException expectedException = ExpectedException.none(); - @Mock - ComponentDao componentDao; - - @Mock - MeasureDao measureDao; - - @Mock - DuplicationsParser parser; + @Rule + public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Mock - DuplicationsJsonWriter duplicationsJsonWriter; + @Rule + public DbTester db = DbTester.create(); - WsTester tester; + private DuplicationsParser parser = new DuplicationsParser(db.getDbClient().componentDao()); + private DuplicationsJsonWriter duplicationsJsonWriter = new DuplicationsJsonWriter(db.getDbClient().componentDao()); + private WsTester tester; + private MetricDto dataMetric = RegisterMetrics.MetricToDto.INSTANCE.apply(CoreMetrics.DUPLICATIONS_DATA); @Before public void setUp() { - when(dbClient.openSession(false)).thenReturn(session); - when(dbClient.componentDao()).thenReturn(componentDao); - tester = new WsTester(new DuplicationsWs(new ShowAction(dbClient, measureDao, parser, duplicationsJsonWriter, userSessionRule, new ComponentFinder(dbClient)))); + tester = new WsTester(new DuplicationsWs(new ShowAction(db.getDbClient(), parser, duplicationsJsonWriter, userSessionRule, new ComponentFinder(db.getDbClient())))); + + db.getDbClient().metricDao().insert(db.getSession(), dataMetric); + db.commit(); } @Test - public void show_duplications() throws Exception { - String componentKey = "src/Foo.java"; - userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey); - - ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey); - when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.of(componentDto)); - - String data = "{duplications}"; - when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn( - java.util.Optional.of(new MeasureDto().setData("{duplications}")) - ); - - List blocks = newArrayList(new DuplicationsParser.Block(newArrayList(new DuplicationsParser.Duplication(componentDto, 1, 2)))); - when(parser.parse(componentDto, data, session)).thenReturn(blocks); - - WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey); - request.execute(); - - verify(duplicationsJsonWriter).write(eq(blocks), any(JsonWriter.class), eq(session)); + public void get_duplications_by_file_key() throws Exception { + WsTester.TestRequest request = newBaseRequest(); + verifyCallToFileWithDuplications(file -> request.setParam("key", file.key())); } @Test - public void show_duplications_by_uuid() throws Exception { - String uuid = "ABCD"; - String componentKey = "src/Foo.java"; - userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey); - - ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey); - when(componentDao.selectByUuid(session, uuid)).thenReturn(Optional.of(componentDto)); + public void get_duplications_by_file_id() throws Exception { + WsTester.TestRequest request = newBaseRequest(); + verifyCallToFileWithDuplications(file -> request.setParam("uuid", file.uuid())); + } - String data = "{duplications}"; - when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn( - java.util.Optional.of(new MeasureDto().setData("{duplications}")) - ); + @Test + public void return_file_with_missing_duplication_data() throws Exception { + ComponentDto project = db.components().insertProject(); + ComponentDto file = db.components().insertComponent(newFileDto(project).setKey("foo.js")); + db.components().insertSnapshot(newAnalysis(project)); - List blocks = newArrayList(new DuplicationsParser.Block(newArrayList(new DuplicationsParser.Duplication(componentDto, 1, 2)))); - when(parser.parse(componentDto, data, session)).thenReturn(blocks); + userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); - WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("uuid", uuid); - request.execute(); + WsTester.Result result = newBaseRequest().setParam("key", file.key()).execute(); - verify(duplicationsJsonWriter).write(eq(blocks), any(JsonWriter.class), eq(session)); + result.assertJson("{\n" + + " \"duplications\": [],\n" + + " \"files\": {}\n" + + "}"); } @Test - public void no_duplications_when_no_data() throws Exception { - String componentKey = "src/Foo.java"; - userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey); + public void return_404_if_file_does_not_exist() throws Exception { + expectedException.expect(NotFoundException.class); - ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey); - when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.of(componentDto)); + newBaseRequest().setParam("key", "missing").execute(); + } - when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn(java.util.Optional.empty()); + @Test + public void return_403_if_user_is_not_allowed_to_access_project() throws Exception { + ComponentDto project = db.components().insertProject(); + ComponentDto file = db.components().insertComponent(newFileDto(project)); - WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey); - request.execute(); + expectedException.expect(ForbiddenException.class); - verify(duplicationsJsonWriter).write(eq(Lists.newArrayList()), any(JsonWriter.class), eq(session)); + newBaseRequest().setParam("key", file.key()).execute(); } - @Test(expected = NotFoundException.class) - public void fail_when_file_not_found() throws Exception { - String componentKey = "src/Foo.java"; - - when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.absent()); - - WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey); - request.execute(); + private WsTester.TestRequest newBaseRequest() { + return tester.newGetRequest("api/duplications", "show"); } + private void verifyCallToFileWithDuplications(Function requestFactory) throws Exception { + ComponentDto project = db.components().insertProject(); + ComponentDto file = db.components().insertComponent(newFileDto(project).setKey("foo.js")); + SnapshotDto snapshot = db.components().insertSnapshot(newAnalysis(project)); + String xml = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + db.getDbClient().measureDao().insert(db.getSession(), newMeasureDto(dataMetric, file, snapshot).setData(xml)); + db.commit(); + + userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); + + WsTester.TestRequest request = requestFactory.apply(file); + WsTester.Result result = request.execute(); + + result.assertJson("{\"duplications\":[" + + "{\"blocks\":[{\"from\":20,\"size\":5,\"_ref\":\"1\"},{\"from\":31,\"size\":5,\"_ref\":\"1\"}]}]," + + "\"files\":{\"1\":{\"key\":\"foo.js\",\"uuid\":\"" + file.uuid() + "\"}}}"); + } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java index c8fcd53f8a6..36ac1420999 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java @@ -33,6 +33,7 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentLinkDto; +import org.sonar.db.component.ComponentTesting; import org.sonar.db.organization.OrganizationDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; @@ -65,12 +66,12 @@ public class CreateActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - DbClient dbClient = db.getDbClient(); - DbSession dbSession = db.getSession(); + private DbClient dbClient = db.getDbClient(); + private DbSession dbSession = db.getSession(); - WsActionTester ws; + private WsActionTester ws; - CreateAction underTest; + private CreateAction underTest; @Before public void setUp() { @@ -83,11 +84,11 @@ public class CreateActionTest { @Test public void example_with_key() { - insertProject(); + ComponentDto project = insertProject(); String result = ws.newRequest() .setMethod("POST") - .setParam(PARAM_PROJECT_KEY, PROJECT_KEY) + .setParam(PARAM_PROJECT_KEY, project.key()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute().getInput(); @@ -97,11 +98,11 @@ public class CreateActionTest { @Test public void example_with_id() { - insertProject(); + ComponentDto project = insertProject(); String result = ws.newRequest() .setMethod("POST") - .setParam(PARAM_PROJECT_ID, PROJECT_UUID) + .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute().getInput(); @@ -111,26 +112,26 @@ public class CreateActionTest { @Test public void global_admin() throws IOException { - userSession.login("login").setGlobalPermissions(SYSTEM_ADMIN); - insertProject(); - createAndTest(); + userSession.login().setGlobalPermissions(SYSTEM_ADMIN); + ComponentDto project = insertProject(); + createAndTest(project); } @Test - public void project_admin() throws IOException { - userSession.login("login"); + public void require_project_admin() throws IOException { + userSession.login(); ComponentDto project = insertProject(); userSession.addProjectUuidPermissions(UserRole.ADMIN, project.uuid()); - createAndTest(); + createAndTest(project); } @Test public void with_long_name() throws IOException { - insertProject(); + ComponentDto project = insertProject(); String longName = StringUtils.leftPad("", 60, "a"); String expectedType = StringUtils.leftPad("", 20, "a"); - createAndTest(longName, "http://example.org", expectedType); + createAndTest(project, longName, "http://example.org", expectedType); } @Test @@ -196,7 +197,7 @@ public class CreateActionTest { @Test public void fail_if_not_project_admin() { - userSession.login("login"); + userSession.login(); insertProject(); expectedException.expect(ForbiddenException.class); @@ -208,17 +209,15 @@ public class CreateActionTest { } private ComponentDto insertProject() { - OrganizationDto organizationDto = db.organizations().insert(); - return db.components().insertProject( - organizationDto, - (t) -> t.setUuid(PROJECT_UUID) - .setKey(PROJECT_KEY)); + OrganizationDto org = db.organizations().insert(); + return db.components().insertComponent( + ComponentTesting.newProjectDto(org, PROJECT_UUID).setKey(PROJECT_KEY)); } - private void createAndTest(String name, String url, String type) throws IOException { + private void createAndTest(ComponentDto project, String name, String url, String type) throws IOException { InputStream responseStream = ws.newRequest() .setMethod("POST") - .setParam(PARAM_PROJECT_KEY, PROJECT_KEY) + .setParam(PARAM_PROJECT_KEY, project.key()) .setParam(PARAM_NAME, name) .setParam(PARAM_URL, url) .setMediaType(PROTOBUF) @@ -234,7 +233,7 @@ public class CreateActionTest { assertThat(link.getType()).isEqualTo(type); } - private void createAndTest() throws IOException { - createAndTest("Custom", "http://example.org", "custom"); + private void createAndTest(ComponentDto project) throws IOException { + createAndTest(project, "Custom", "http://example.org", "custom"); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/source/ws/IndexActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/source/ws/IndexActionTest.java index 979faeb0ec1..e9e74fee090 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/source/ws/IndexActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/source/ws/IndexActionTest.java @@ -77,7 +77,7 @@ public class IndexActionTest { @Test public void get_json() throws Exception { String fileKey = "src/Foo.java"; - userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey); + userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); when(sourceService.getLinesAsRawText(session, file.uuid(), 1, Integer.MAX_VALUE)).thenReturn(Optional.of((Iterable) newArrayList( @@ -91,7 +91,7 @@ public class IndexActionTest { @Test public void limit_range() throws Exception { String fileKey = "src/Foo.java"; - userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey); + userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); when(sourceService.getLinesAsRawText(session, file.uuid(), 1, 2)).thenReturn(Optional.of((Iterable) newArrayList( @@ -105,13 +105,14 @@ public class IndexActionTest { @Test(expected = ForbiddenException.class) public void requires_code_viewer_permission() throws Exception { - tester.newGetRequest("api/sources", "index").setParam("resource", "any").execute(); + when(componentDao.selectByKey(session, "foo")).thenReturn(Optional.of(file)); + tester.newGetRequest("api/sources", "index").setParam("resource", "foo").execute(); } @Test public void close_db_session() throws Exception { String fileKey = "src/Foo.java"; - userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey); + userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.absent()); WsTester.TestRequest request = tester.newGetRequest("api/sources", "index").setParam("resource", fileKey); diff --git a/server/sonar-server/src/test/java/org/sonar/server/tester/UserSessionRule.java b/server/sonar-server/src/test/java/org/sonar/server/tester/UserSessionRule.java index d2ebacdd2b0..2941eabb8fc 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/tester/UserSessionRule.java +++ b/server/sonar-server/src/test/java/org/sonar/server/tester/UserSessionRule.java @@ -258,7 +258,7 @@ public class UserSessionRule implements TestRule, UserSession { @Override public boolean hasComponentPermission(String permission, ComponentDto component) { - return hasComponentUuidPermission(permission, component.projectUuid()); + return currentUserSession.hasComponentPermission(permission, component); } @Override