]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-18850 clean sonar-webserver-auth of main_branc_project_uuid usage
authorBenjamin Campomenosi <109955405+benjamin-campomenosi-sonarsource@users.noreply.github.com>
Fri, 7 Apr 2023 07:50:08 +0000 (09:50 +0200)
committersonartech <sonartech@sonarsource.com>
Fri, 7 Apr 2023 20:02:58 +0000 (20:02 +0000)
27 files changed:
server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java
server/sonar-db-dao/src/testFixtures/java/org/sonar/db/issue/IssueDbTester.java
server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureTesting.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/user/AbstractUserSession.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/user/DoPrivileged.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ServerUserSession.java
server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ServerUserSessionTest.java
server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/tester/AbstractMockUserSession.java
server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/tester/UserSessionRule.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/queue/BranchReportSubmitterIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/AppActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/ShowActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/TreeActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AssignActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ShowActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/BulkChangeActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/ComponentActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/ComponentTreeActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/SearchHistoryActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/scannercache/ws/GetActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ResetActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/RawActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/ComponentActionIT.java

index 3d206dafaae1d8b516621dc19aa84c0113e5d80b..985668d9163b95f8f1203b04317025bf268b123a 100644 (file)
@@ -67,6 +67,11 @@ public class ComponentDbTester {
       defaults(), defaults(), defaults());
   }
 
+  public BranchDto getBranchDto(ComponentDto branch) {
+    return db.getDbClient().branchDao().selectByUuid(dbSession, branch.uuid())
+      .orElseThrow(() -> new IllegalStateException("Project has invalid configuration"));
+  }
+
   public ProjectDto getProjectDto(ComponentDto project) {
     return db.getDbClient().projectDao().selectByUuid(dbSession, project.uuid())
       .orElseThrow(() -> new IllegalStateException("Project has invalid configuration"));
@@ -98,7 +103,6 @@ public class ComponentDbTester {
     return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(uuid), false, defaults(), dtoPopulator);
   }
 
-
   public ComponentDto insertPublicProject(ComponentDto componentDto) {
     return insertComponentAndBranchAndProject(componentDto, false);
   }
@@ -426,6 +430,13 @@ public class ComponentDbTester {
     db.commit();
   }
 
+  public void addProjectBranchToApplicationBranch(ComponentDto applicationBranchComponent, ComponentDto... projectBranchesComponent) {
+    BranchDto applicationBranch = getBranchDto(applicationBranchComponent);
+    BranchDto[] componentDtos = Arrays.stream(projectBranchesComponent).map(this::getBranchDto).toArray(BranchDto[]::new);
+
+    addProjectBranchToApplicationBranch(applicationBranch, componentDtos);
+  }
+
   public void addProjectBranchToApplicationBranch(BranchDto applicationBranch, BranchDto... projectBranches) {
     for (BranchDto projectBranch : projectBranches) {
       dbClient.applicationProjectsDao().addProjectBranchToAppBranch(dbSession, applicationBranch, projectBranch);
index 99e6729833d714da9ea1b32eda35af29538bc293..d06e61c8e07c8f5af72343accc2c2fb168356b87 100644 (file)
@@ -175,6 +175,16 @@ public class IssueDbTester {
     return insertHotspot(issue);
   }
 
+  public final IssueDto insertHotspot(ProjectDto project, ComponentDto file, Consumer<IssueDto>... populators) {
+    RuleDto rule = db.rules().insertHotspotRule();
+    IssueDto issue = newIssue(rule, project, file)
+      .setType(SECURITY_HOTSPOT)
+      .setStatus(Issue.STATUS_TO_REVIEW)
+      .setResolution(null);
+    stream(populators).forEach(p -> p.accept(issue));
+    return insertHotspot(issue);
+  }
+
   /**
    * Inserts a Security Hotspot.
    *
index 78121b095cdad0dfe3c085e689636540155c1ecd..efa6fa2321f615a850ae7b5b11a9e8bef7ca45dd 100644 (file)
 package org.sonar.db.measure;
 
 import org.apache.commons.lang.math.RandomUtils;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.SnapshotDto;
 import org.sonar.db.metric.MetricDto;
+import org.sonar.db.project.ProjectDto;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
@@ -73,4 +75,13 @@ public class MeasureTesting {
       .setData(String.valueOf(cursor++))
       .setValue((double) cursor++);
   }
+
+  public static LiveMeasureDto newLiveMeasure(BranchDto branchDto, MetricDto metric) {
+    return new LiveMeasureDto()
+      .setMetricUuid(metric.getUuid())
+      .setComponentUuid(branchDto.getUuid())
+      .setProjectUuid(branchDto.getProjectUuid())
+      .setData(String.valueOf(cursor++))
+      .setValue((double) cursor++);
+  }
 }
index f6021eeb2d1c4dd668196d7fb9c1eeb4bd064e66..482fb88c5d1aa0e706d4e4325c9b339911de7adf 100644 (file)
@@ -88,9 +88,13 @@ public abstract class AbstractUserSession implements UserSession {
   protected abstract boolean hasPermissionImpl(GlobalPermission permission);
 
   @Override
-  public final boolean hasComponentPermission(String permission, ComponentDto component) {
-    String projectUuid = defaultString(component.getMainBranchProjectUuid(), component.branchUuid());
-    return hasProjectUuidPermission(permission, projectUuid);
+  public boolean hasComponentPermission(String permission, ComponentDto component) {
+
+    Optional<String> projectUuid1 = componentUuidToProjectUuid(component.uuid());
+
+    return projectUuid1
+      .map(projectUuid -> hasProjectUuidPermission(permission, projectUuid))
+      .orElse(false);
   }
 
   @Override
index f7e9eac5fc372d13b857a9d75d84ddc05765d600..00b3458b7a0d831594ffd3dc3916dd21f0d28f50 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.user;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Optional;
+import org.sonar.db.component.ComponentDto;
 import org.sonar.db.permission.GlobalPermission;
 import org.sonar.db.user.GroupDto;
 
@@ -111,6 +112,11 @@ public final class DoPrivileged {
         return true;
       }
 
+      @Override
+      public boolean hasComponentPermission(String permission, ComponentDto component) {
+        return true;
+      }
+
       @Override
       protected Optional<String> componentUuidToProjectUuid(String componentUuid) {
         // always root so unused
index 0fc12ce8ce955a98ba51005bb07d6ffa855a3fac..7455a5b946a0e0089dd5c4576418903b51ba2f57 100644 (file)
@@ -37,6 +37,7 @@ import org.sonar.api.resources.Scopes;
 import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentTreeQuery;
 import org.sonar.db.component.ComponentTreeQuery.Strategy;
@@ -49,13 +50,17 @@ import static java.util.Collections.singleton;
 import static java.util.Optional.of;
 import static java.util.Optional.ofNullable;
 import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
+import static org.sonar.api.resources.Qualifiers.SUBVIEW;
+import static org.sonar.api.resources.Qualifiers.VIEW;
 import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS;
 
 /**
  * Implementation of {@link UserSession} used in web server
  */
 public class ServerUserSession extends AbstractUserSession {
+
+  private static final Set<String> QUALIFIERS = Set.of(VIEW, SUBVIEW);
+
   @CheckForNull
   private final UserDto userDto;
   private final DbClient dbClient;
@@ -153,7 +158,7 @@ public class ServerUserSession extends AbstractUserSession {
       }
       // if component is part of a branch, then permissions must be
       // checked on the project (represented by its main branch)
-      projectUuid = defaultIfEmpty(component.get().getMainBranchProjectUuid(), component.get().branchUuid());
+      projectUuid = getMainProjectUuid(dbSession, component.get());
       projectUuidByComponentUuid.put(componentUuid, projectUuid);
       return of(projectUuid);
     }
@@ -204,16 +209,49 @@ public class ServerUserSession extends AbstractUserSession {
       .collect(toSet());
   }
 
-  private Set<String> findProjectUuids(Set<String> branchesComponents) {
+  private Set<String> findProjectUuids(Set<String> branchesComponentsUuid) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      return dbClient.componentDao().selectByUuids(dbSession, branchesComponents).stream()
-        .map(ServerUserSession::getProjectId)
-        .collect(toSet());
+      List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, branchesComponentsUuid);
+      return getMainProjectUuids(dbSession, componentDtos);
     }
   }
 
-  private static String getProjectId(ComponentDto branchComponent) {
-    return Optional.ofNullable(branchComponent.getMainBranchProjectUuid()).orElse(branchComponent.uuid());
+  private String getMainProjectUuid(DbSession dbSession, ComponentDto componentDto) {
+    // Portfolio & subPortfolio don't have branch, so branchUuid represents the portfolio uuid.
+    // technical project store root portfolio uuid in branchUuid
+    if (isPortfolioOrSubPortfolio(componentDto) || isTechnicalProject(componentDto)) {
+      return componentDto.branchUuid();
+    }
+    Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, componentDto.branchUuid());
+    return branchDto.map(BranchDto::getProjectUuid).orElseThrow(() -> new IllegalStateException("No branch found for component : " + componentDto));
+  }
+
+  private Set<String> getMainProjectUuids(DbSession dbSession, Collection<ComponentDto> components) {
+    Set<String> mainProjectUuids = new HashSet<>();
+
+    // the result of following stream could be project or application
+    Collection<String> componentsWithBranch = components.stream()
+      .filter(c -> !(isTechnicalProject(c) || isPortfolioOrSubPortfolio(c)))
+      .map(ComponentDto::branchUuid)
+      .toList();
+
+    dbClient.branchDao().selectByUuids(dbSession, componentsWithBranch).stream()
+      .map(BranchDto::getProjectUuid).forEach(mainProjectUuids::add);
+
+    components.stream()
+      .filter(c -> isTechnicalProject(c) || isPortfolioOrSubPortfolio(c))
+      .map(ComponentDto::branchUuid)
+      .forEach(mainProjectUuids::add);
+
+    return mainProjectUuids;
+  }
+
+  private static boolean isTechnicalProject(ComponentDto componentDto) {
+    return Qualifiers.PROJECT.equals(componentDto.qualifier()) && Scopes.FILE.equals(componentDto.scope());
+  }
+
+  private static boolean isPortfolioOrSubPortfolio(ComponentDto componentDto) {
+    return !Objects.isNull(componentDto.qualifier()) && QUALIFIERS.contains(componentDto.qualifier());
   }
 
   private boolean hasPermission(String permission, String projectUuid) {
@@ -311,16 +349,12 @@ public class ServerUserSession extends AbstractUserSession {
   @Override
   protected List<ComponentDto> doKeepAuthorizedComponents(String permission, Collection<ComponentDto> components) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      Set<String> projectUuids = components.stream()
-        .map(c -> defaultIfEmpty(c.getMainBranchProjectUuid(), c.branchUuid()))
-        .collect(MoreCollectors.toSet(components.size()));
+      Set<String> projectUuids = getMainProjectUuids(dbSession, components);
 
       Map<String, ComponentDto> originalComponents = findComponentsByCopyComponentUuid(components,
-          dbSession);
+        dbSession);
 
-      Set<String> originalComponentsProjectUuids = originalComponents.values().stream()
-          .map(c -> defaultIfEmpty(c.getMainBranchProjectUuid(), c.branchUuid()))
-          .collect(MoreCollectors.toSet(components.size()));
+      Set<String> originalComponentsProjectUuids = getMainProjectUuids(dbSession, originalComponents.values());
 
       Set<String> allProjectUuids = new HashSet<>(projectUuids);
       allProjectUuids.addAll(originalComponentsProjectUuids);
@@ -331,11 +365,11 @@ public class ServerUserSession extends AbstractUserSession {
         .filter(c -> {
           if (c.getCopyComponentUuid() != null) {
             var componentDto = originalComponents.get(c.getCopyComponentUuid());
-            return componentDto != null && authorizedProjectUuids.contains(defaultIfEmpty(componentDto.getMainBranchProjectUuid(), componentDto.branchUuid()));
+            return componentDto != null && authorizedProjectUuids.contains(getMainProjectUuid(dbSession, componentDto));
           }
 
           return authorizedProjectUuids.contains(c.branchUuid()) || authorizedProjectUuids.contains(
-              c.getMainBranchProjectUuid());
+            getMainProjectUuid(dbSession, c));
         })
         .collect(MoreCollectors.toList(components.size()));
     }
@@ -343,11 +377,11 @@ public class ServerUserSession extends AbstractUserSession {
 
   private Map<String, ComponentDto> findComponentsByCopyComponentUuid(Collection<ComponentDto> components, DbSession dbSession) {
     Set<String> copyComponentsUuid = components.stream()
-        .map(ComponentDto::getCopyComponentUuid)
-        .filter(Objects::nonNull)
-        .collect(MoreCollectors.toSet(components.size()));
+      .map(ComponentDto::getCopyComponentUuid)
+      .filter(Objects::nonNull)
+      .collect(MoreCollectors.toSet(components.size()));
     return dbClient.componentDao().selectByUuids(dbSession, copyComponentsUuid).stream()
-        .collect(Collectors.toMap(ComponentDto::uuid, componentDto -> componentDto));
+      .collect(Collectors.toMap(ComponentDto::uuid, componentDto -> componentDto));
   }
 
   @Override
index 900743d33f70bafd95f68cad1ee9cdd450ccfe15..1df7820c39caf27026511f96e182f81ac5018afc 100644 (file)
@@ -170,7 +170,7 @@ public class ServerUserSessionTest {
     ComponentDto project = db.components().insertPrivateProject();
     ComponentDto application = db.components().insertPrivateApplication();
     db.components().addApplicationProject(application, project);
-    //add computed project
+    // add computed project
     db.components().insertComponent(newProjectCopy(project, application));
 
     UserSession underTest = newUserSession(user);
@@ -653,10 +653,27 @@ public class ServerUserSessionTest {
     assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(app, subPortfolio, app2))).containsExactly(app, subPortfolio);
 
     assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, Arrays.asList(project1, project2, project3, project4, project5, project6))).isEmpty();
-    assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(project1, project2, project3, project4, project5, project6))).containsExactly(project1, project2, project4, project5);
-
+    assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(project1, project2, project3, project4, project5, project6))).containsExactly(project1, project2,
+      project4, project5);
     assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(copyProject1, copyProject2, copyProject3, copyProject4, copyProject5, copyProject6)))
-        .containsExactly(copyProject1, copyProject2, copyProject4, copyProject5);
+      .containsExactly(copyProject1, copyProject2, copyProject4, copyProject5);
+  }
+
+  @Test
+  public void keepAuthorizedComponents_filters__files_with_granted_permissions_for_logged_in_user() {
+    ComponentDto project1 = db.components().insertPrivateProject();
+    ComponentDto project2 = db.components().insertPrivateProject();
+
+    UserDto user = db.users().insertUser();
+    UserSession underTest = newUserSession(user);
+
+    db.users().insertProjectPermissionOnUser(user, UserRole.USER, project1);
+    ComponentDto file1Project1 = db.components().insertFile(db.components().getProjectDto(project1));
+    ComponentDto file2Project1 = db.components().insertFile(db.components().getProjectDto(project1));
+
+    ComponentDto file1Project2 = db.components().insertFile(db.components().getProjectDto(project2));
+
+    assertThat(underTest.keepAuthorizedComponents(UserRole.USER, List.of(file1Project1, file2Project1, file1Project2))).containsExactly(file1Project1, file2Project1);
   }
 
   @Test
@@ -733,8 +750,8 @@ public class ServerUserSessionTest {
   }
 
   @Test
-  public void keepAuthorizedProjects_shouldAcceptsPublicProjects_whenCalledWithPublicPermissionAndNoUser(){
-    ComponentDto publicProject  = db.components().insertPublicProject();
+  public void keepAuthorizedProjects_shouldAcceptsPublicProjects_whenCalledWithPublicPermissionAndNoUser() {
+    ComponentDto publicProject = db.components().insertPublicProject();
     ComponentDto privateProject = db.components().insertPrivateProject();
 
     Set<ProjectDto> projectDto = Set.of(getProjectDto(publicProject), getProjectDto(privateProject));
@@ -744,9 +761,9 @@ public class ServerUserSessionTest {
   }
 
   @Test
-  public void keepAuthorizedProjects_shouldAcceptsPublicProjects_whenCalledWithPublicPermissionAndAnUser(){
+  public void keepAuthorizedProjects_shouldAcceptsPublicProjects_whenCalledWithPublicPermissionAndAnUser() {
     UserDto userDto = db.users().insertUser();
-    ComponentDto publicProject  = db.components().insertPublicProject();
+    ComponentDto publicProject = db.components().insertPublicProject();
     ComponentDto privateProject = db.components().insertPrivateProject();
 
     Set<ProjectDto> projectDto = Set.of(getProjectDto(publicProject), getProjectDto(privateProject));
@@ -756,12 +773,12 @@ public class ServerUserSessionTest {
   }
 
   @Test
-  public void keepAuthorizedProjects_shouldAcceptsOnlyPrivateProject_whenCalledWithGoodPermissionAndAnUser(){
+  public void keepAuthorizedProjects_shouldAcceptsOnlyPrivateProject_whenCalledWithGoodPermissionAndAnUser() {
     String permission = "aNewPermission";
     UserDto userDto = db.users().insertUser();
-    ComponentDto publicProject  = db.components().insertPublicProject();
+    ComponentDto publicProject = db.components().insertPublicProject();
     ComponentDto privateProject = db.components().insertPrivateProject();
-    db.users().insertProjectPermissionOnUser(userDto, permission,privateProject);
+    db.users().insertProjectPermissionOnUser(userDto, permission, privateProject);
     ComponentDto privateProjectWithoutPermission = db.components().insertPrivateProject();
 
     Set<ProjectDto> projectDto = Set.of(getProjectDto(publicProject), getProjectDto(privateProject), getProjectDto(privateProjectWithoutPermission));
@@ -771,12 +788,12 @@ public class ServerUserSessionTest {
   }
 
   @Test
-  public void keepAuthorizedProjects_shouldRejectPrivateAndPublicProject_whenCalledWithWrongPermissionAndNoUser(){
+  public void keepAuthorizedProjects_shouldRejectPrivateAndPublicProject_whenCalledWithWrongPermissionAndNoUser() {
     String permission = "aNewPermission";
     UserDto userDto = db.users().insertUser();
-    ComponentDto publicProject  = db.components().insertPublicProject();
+    ComponentDto publicProject = db.components().insertPublicProject();
     ComponentDto privateProject = db.components().insertPrivateProject();
-    db.users().insertProjectPermissionOnUser(userDto, permission,privateProject);
+    db.users().insertProjectPermissionOnUser(userDto, permission, privateProject);
     ComponentDto privateProjectWithoutPermission = db.components().insertPrivateProject();
 
     Set<ProjectDto> projectDto = Set.of(getProjectDto(publicProject), getProjectDto(privateProject), getProjectDto(privateProjectWithoutPermission));
@@ -789,7 +806,6 @@ public class ServerUserSessionTest {
     return db.components().getProjectDto(publicProject);
   }
 
-
   private ServerUserSession newUserSession(@Nullable UserDto userDto) {
     return new ServerUserSession(dbClient, userDto);
   }
index 890bb23ebb0ee480a32ab810f43f9cb9612f2401..88a0109539bd7e7e169bad47b1a0a15680cd7b38 100644 (file)
@@ -28,7 +28,10 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.sonar.api.web.UserRole;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.permission.GlobalPermission;
 import org.sonar.db.portfolio.PortfolioDto;
@@ -38,12 +41,15 @@ import org.sonar.server.user.AbstractUserSession;
 import static com.google.common.base.Preconditions.checkArgument;
 
 public abstract class AbstractMockUserSession<T extends AbstractMockUserSession> extends AbstractUserSession {
+
+  private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMockUserSession.class);
   private static final Set<String> PUBLIC_PERMISSIONS = ImmutableSet.of(UserRole.USER, UserRole.CODEVIEWER); // FIXME to check with Simon
 
   private final Class<T> clazz;
   private final HashMultimap<String, String> projectUuidByPermission = HashMultimap.create();
   private final Set<GlobalPermission> permissions = new HashSet<>();
   private final Map<String, String> projectUuidByComponentUuid = new HashMap<>();
+  private final Map<String, String> projectUuidByBranchUuid = new HashMap<>();
   private final Map<String, Set<String>> applicationProjects = new HashMap<>();
   private final Map<String, Set<String>> portfolioProjects = new HashMap<>();
   private final Set<String> projectPermissions = new HashSet<>();
@@ -134,16 +140,18 @@ public abstract class AbstractMockUserSession<T extends AbstractMockUserSession>
     return clazz.cast(this);
   }
 
-  public T registerPortfolioProjects(PortfolioDto portfolio, ProjectDto... portfolioProjects) {
-    registerPortfolios(portfolio);
-    registerProjects(portfolioProjects);
-
-    Set<String> portfolioProjectsUuid = Arrays.stream(portfolioProjects)
-      .map(ProjectDto::getUuid)
-      .collect(Collectors.toSet());
-
-    this.portfolioProjects.put(portfolio.getUuid(), portfolioProjectsUuid);
+  public T registerBranches(BranchDto ...branchDtos){
+    Arrays.stream(branchDtos)
+      .forEach(branch -> projectUuidByBranchUuid.put(branch.getUuid(), branch.getProjectUuid()));
+    return clazz.cast(this);
+  }
 
+  /**
+   * Branches need to be registered in order to save the mapping between branch and project.
+   */
+  public T addProjectBranchMapping(String projectUuid, ComponentDto... componentDtos) {
+    Arrays.stream(componentDtos)
+      .forEach(componentDto -> projectUuidByBranchUuid.put(componentDto.uuid(), projectUuid));
     return clazz.cast(this);
   }
 
@@ -188,7 +196,18 @@ public abstract class AbstractMockUserSession<T extends AbstractMockUserSession>
 
   @Override
   protected Optional<String> componentUuidToProjectUuid(String componentUuid) {
-    return Optional.ofNullable(projectUuidByComponentUuid.get(componentUuid));
+    return Optional.ofNullable(Optional.ofNullable(projectUuidByBranchUuid.get(componentUuid))
+      .orElse(projectUuidByComponentUuid.get(componentUuid)));
+  }
+
+  @Override
+  public boolean hasComponentPermission(String permission, ComponentDto component) {
+    return componentUuidToProjectUuid(component.uuid())
+      .or(() -> componentUuidToProjectUuid(component.branchUuid()))
+      .map(projectUuid -> hasProjectUuidPermission(permission, projectUuid)).orElseGet(() -> {
+        LOGGER.warn("No project uuid for branchUuid : {}", component.branchUuid());
+        return false;
+      });
   }
 
   @Override
index d8e6775f42038cddfd4e9cd3b1579cf98b65ddee..862eb29455e19fa90c9989e6e9be74c4284e49e0 100644 (file)
@@ -28,6 +28,7 @@ import javax.annotation.Nullable;
 import org.junit.rules.TestRule;
 import org.junit.runner.Description;
 import org.junit.runners.model.Statement;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.permission.GlobalPermission;
 import org.sonar.db.portfolio.PortfolioDto;
@@ -198,6 +199,16 @@ public class UserSessionRule implements TestRule, UserSession {
     return this;
   }
 
+  public UserSessionRule addProjectBranchMapping(String projectUuid, ComponentDto... branchComponents) {
+    ensureAbstractMockUserSession().addProjectBranchMapping(projectUuid, branchComponents);
+    return this;
+  }
+
+  public UserSession registerBranches(BranchDto ...branchDtos){
+    ensureAbstractMockUserSession().registerBranches(branchDtos);
+    return this;
+  }
+
   public UserSessionRule addProjectPermission(String projectPermission, ProjectDto... projectDto) {
     ensureAbstractMockUserSession().addProjectPermission(projectPermission, projectDto);
     return this;
index 50170a866cdfc16b969910c72d63e35945fce44e..a4f53fa173ee99ef74e8b5728082bae1d3439500 100644 (file)
@@ -121,7 +121,7 @@ public class BranchReportSubmitterIT {
     ComponentDto project = db.components().insertPublicProject();
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch1"));
     UserDto user = db.users().insertUser();
-    userSession.logIn(user).addProjectPermission(SCAN.getKey(), project);
+    userSession.logIn(user).addProjectPermission(SCAN.getKey(), project).addProjectBranchMapping(project.uuid(), branch);
     Map<String, String> randomCharacteristics = randomNonEmptyMap();
     BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(project.getKey(), "branch1");
     when(branchSupportDelegate.createComponentKey(project.getKey(), randomCharacteristics)).thenReturn(componentKey);
@@ -147,6 +147,7 @@ public class BranchReportSubmitterIT {
     userSession.logIn(user).addProjectPermission(SCAN.getKey(), existingProject);
     Map<String, String> randomCharacteristics = randomNonEmptyMap();
     ComponentDto createdBranch = createButDoNotInsertBranch(existingProject);
+    userSession.addProjectBranchMapping(existingProject.uuid(), createdBranch);
     BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(existingProject.getKey(), "branch1");
     when(branchSupportDelegate.createComponentKey(existingProject.getKey(), randomCharacteristics)).thenReturn(componentKey);
     when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch))).thenReturn(createdBranch);
index e25d24bb21709c9fa40e1b871572bf4af2f86355..5323a5472104faf9c240e92c21e12fb20cdf947e 100644 (file)
@@ -24,8 +24,10 @@ import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
 import org.sonar.db.DbTester;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.metric.MetricDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.server.component.TestComponentFinder;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
@@ -254,6 +256,7 @@ public class AppActionIT {
     userSession.logIn("john").addProjectPermission(USER, project);
     String branchName = randomAlphanumeric(248);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto directory = db.components().insertComponent(newDirectory(branch, "src"));
     ComponentDto file = db.components().insertComponent(newFileDto(project.uuid(), branch, directory));
     MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
@@ -297,6 +300,7 @@ public class AppActionIT {
     userSession.logIn("john").addProjectPermission(USER, project);
     String branchName = randomAlphanumeric(248);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
 
     String result = ws.newRequest()
@@ -327,6 +331,7 @@ public class AppActionIT {
     userSession.logIn("john").addProjectPermission(USER, project);
     String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
 
     String result = ws.newRequest()
index f05a85e99d810c709d727b2c6012d77379f280b7..f8793a0ed7581e50db46cb45c1332dc5d50ff9cb 100644 (file)
@@ -251,6 +251,7 @@ public class ShowActionIT {
     userSession.addProjectPermission(UserRole.USER, project);
     String branchKey = "my_branch";
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchKey));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto directory = db.components().insertComponent(newDirectoryOnBranch(branch, "dir", project.uuid()));
     ComponentDto file = db.components().insertComponent(newFileDto(project.uuid(), branch, directory));
     db.components().insertSnapshot(branch, s -> s.setProjectVersion("1.1"));
@@ -290,6 +291,7 @@ public class ShowActionIT {
     userSession.addProjectPermission(UserRole.USER, project);
     String pullRequest = "pr-1234";
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(pullRequest).setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto directory = db.components().insertComponent(newDirectoryOnBranch(branch, "dir", project.uuid()));
     ComponentDto file = db.components().insertComponent(newFileDto(project.uuid(), branch, directory));
     db.components().insertSnapshot(branch, s -> s.setProjectVersion("1.1"));
@@ -320,12 +322,15 @@ public class ShowActionIT {
       .setNeedIssueSync(true));
     ComponentDto directory = db.components().insertComponent(newDirectoryOnBranch(branch1, "dir", project1.uuid()));
     ComponentDto file = db.components().insertComponent(newFileDto(project1.uuid(), branch1, directory));
+    userSession.addProjectBranchMapping(project1.uuid(), branch1);
 
     ComponentDto project2 = db.components().insertPrivateProject();
     String branchName2 = randomAlphanumeric(248);
     ComponentDto branch2 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(true).setKey(branchName2));
     String branchName3 = randomAlphanumeric(248);
     ComponentDto branch3 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName3));
+    userSession.addProjectBranchMapping(project2.uuid(), branch2);
+    userSession.addProjectBranchMapping(project2.uuid(), branch3);
 
     ComponentDto project3 = db.components().insertPrivateProject();
     String pullRequestKey4 = randomAlphanumeric(100);
@@ -334,6 +339,8 @@ public class ShowActionIT {
     ComponentDto fileOfBranch4 = db.components().insertComponent(newFileDto(project3.uuid(), branch4, directoryOfBranch4));
     String branchName5 = randomAlphanumeric(248);
     ComponentDto branch5 = db.components().insertProjectBranch(project3, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName5));
+    userSession.addProjectBranchMapping(project3.uuid(), branch4);
+    userSession.addProjectBranchMapping(project3.uuid(), branch5);
 
     userSession.addProjectPermission(UserRole.USER, project1, project2, project3);
     userSession.registerComponents(portfolio1, portfolio2, subview, project1, project2, project3);
@@ -430,11 +437,11 @@ public class ShowActionIT {
 
   private void insertJsonExampleComponentsAndSnapshots() {
     ComponentDto project = db.components().insertPrivateProject(c -> c.setUuid("AVIF98jgA3Ax6PH2efOW")
-        .setBranchUuid("AVIF98jgA3Ax6PH2efOW")
-        .setKey("com.sonarsource:java-markdown")
-        .setName("Java Markdown")
-        .setDescription("Java Markdown Project")
-        .setQualifier(Qualifiers.PROJECT),
+      .setBranchUuid("AVIF98jgA3Ax6PH2efOW")
+      .setKey("com.sonarsource:java-markdown")
+      .setName("Java Markdown")
+      .setDescription("Java Markdown Project")
+      .setQualifier(Qualifiers.PROJECT),
       p -> p.setTagsString("language, plugin"));
     userSession.addProjectPermission(USER, project);
     db.components().insertSnapshot(project, snapshot -> snapshot
index 74e2b271d90409a47503c651190ebb473e2b6587..53464931db8cfa31d01a1f3d318018db503fc82c 100644 (file)
@@ -291,15 +291,19 @@ public class TreeActionIT {
 
   @Test
   public void project_branch_reference_from_application_branch() {
-    ComponentDto application = db.components().insertPrivateProject(c -> c.setQualifier(APP).setKey("app-key"));
     String appBranchName = "app-branch";
     String projectBranchName = "project-branch";
+
+    ComponentDto application = db.components().insertPrivateProject(c -> c.setQualifier(APP).setKey("app-key"));
     ComponentDto applicationBranch = db.components().insertProjectBranch(application, a -> a.setKey(appBranchName));
+
     ComponentDto project = db.components().insertPrivateProject(p -> p.setKey("project-key"));
     ComponentDto projectBranch = db.components().insertProjectBranch(project, b -> b.setKey(projectBranchName));
     ComponentDto techProjectBranch = db.components().insertComponent(newProjectCopy(projectBranch, applicationBranch)
       .setKey(applicationBranch.getKey() + project.getKey()).setMainBranchProjectUuid(application.uuid()));
+
     logInWithBrowsePermission(application);
+    userSession.addProjectBranchMapping(application.uuid(), applicationBranch);
 
     TreeWsResponse result = ws.newRequest()
       .setParam(MeasuresWsParameters.PARAM_COMPONENT, applicationBranch.getKey())
@@ -355,6 +359,7 @@ public class TreeActionIT {
     userSession.addProjectPermission(UserRole.USER, project);
     String branchKey = "my_branch";
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchKey));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto directory = db.components().insertComponent(newDirectoryOnBranch(branch, "dir", project.uuid()));
     ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(directory, project.uuid()));
 
@@ -392,6 +397,7 @@ public class TreeActionIT {
     userSession.addProjectPermission(UserRole.USER, project);
     String pullRequestId = "pr-123";
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(pullRequestId).setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto directory = db.components().insertComponent(newDirectoryOnBranch(branch, "dir", project.uuid()));
     ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(directory, project.uuid()));
 
@@ -527,10 +533,10 @@ public class TreeActionIT {
 
   private ComponentDto initJsonExampleComponents() throws IOException {
     ComponentDto project = db.components().insertPrivateProject(c -> c.setUuid("MY_PROJECT_ID")
-        .setDescription("MY_PROJECT_DESCRIPTION")
-        .setKey("MY_PROJECT_KEY")
-        .setName("Project Name")
-        .setBranchUuid("MY_PROJECT_ID"),
+      .setDescription("MY_PROJECT_DESCRIPTION")
+      .setKey("MY_PROJECT_KEY")
+      .setName("Project Name")
+      .setBranchUuid("MY_PROJECT_ID"),
       p -> p.setTagsString("abc,def"));
     db.components().insertSnapshot(project);
 
index 873ac406763ce6b28f2f71c45c28d7796107fc87..cfb38f369423562da69603620736941f73faa90e 100644 (file)
@@ -109,6 +109,7 @@ public class ShowActionIT {
     userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
     String branchName = randomAlphanumeric(248);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()).setMainBranchProjectUuid(project.uuid()));
     db.measures().insertLiveMeasure(file, dataMetric, m -> m.setData(format("<duplications>\n" +
       "  <g>\n" +
@@ -125,34 +126,34 @@ public class ShowActionIT {
 
     assertJson(result).isSimilarTo(
       format("{\n" +
-          "  \"duplications\": [\n" +
-          "    {\n" +
-          "      \"blocks\": [\n" +
-          "        {\n" +
-          "          \"from\": 20,\n" +
-          "          \"size\": 5,\n" +
-          "          \"_ref\": \"1\"\n" +
-          "        },\n" +
-          "        {\n" +
-          "          \"from\": 31,\n" +
-          "          \"size\": 5,\n" +
-          "          \"_ref\": \"1\"\n" +
-          "        }\n" +
-          "      ]\n" +
-          "    }\n" +
-          "  ],\n" +
-          "  \"files\": {\n" +
-          "    \"1\": {\n" +
-          "      \"key\": \"%s\",\n" +
-          "      \"name\": \"%s\",\n" +
-          "      \"uuid\": \"%s\",\n" +
-          "      \"project\": \"%s\",\n" +
-          "      \"projectUuid\": \"%s\",\n" +
-          "      \"projectName\": \"%s\"\n" +
-          "      \"branch\": \"%s\"\n" +
-          "    }\n" +
-          "  }\n" +
-          "}",
+        "  \"duplications\": [\n" +
+        "    {\n" +
+        "      \"blocks\": [\n" +
+        "        {\n" +
+        "          \"from\": 20,\n" +
+        "          \"size\": 5,\n" +
+        "          \"_ref\": \"1\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "          \"from\": 31,\n" +
+        "          \"size\": 5,\n" +
+        "          \"_ref\": \"1\"\n" +
+        "        }\n" +
+        "      ]\n" +
+        "    }\n" +
+        "  ],\n" +
+        "  \"files\": {\n" +
+        "    \"1\": {\n" +
+        "      \"key\": \"%s\",\n" +
+        "      \"name\": \"%s\",\n" +
+        "      \"uuid\": \"%s\",\n" +
+        "      \"project\": \"%s\",\n" +
+        "      \"projectUuid\": \"%s\",\n" +
+        "      \"projectName\": \"%s\"\n" +
+        "      \"branch\": \"%s\"\n" +
+        "    }\n" +
+        "  }\n" +
+        "}",
         file.getKey(), file.longName(), file.uuid(), branch.getKey(), branch.uuid(), project.longName(), branchName));
   }
 
@@ -162,6 +163,7 @@ public class ShowActionIT {
     userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
     String pullRequestKey = randomAlphanumeric(100);
     ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
+    userSessionRule.addProjectBranchMapping(project.uuid(), pullRequest);
     ComponentDto file = db.components().insertComponent(newFileDto(pullRequest, project.uuid()));
     db.measures().insertLiveMeasure(file, dataMetric, m -> m.setData(format("<duplications>\n" +
       "  <g>\n" +
@@ -178,34 +180,34 @@ public class ShowActionIT {
 
     assertJson(result).isSimilarTo(
       format("{\n" +
-          "  \"duplications\": [\n" +
-          "    {\n" +
-          "      \"blocks\": [\n" +
-          "        {\n" +
-          "          \"from\": 20,\n" +
-          "          \"size\": 5,\n" +
-          "          \"_ref\": \"1\"\n" +
-          "        },\n" +
-          "        {\n" +
-          "          \"from\": 31,\n" +
-          "          \"size\": 5,\n" +
-          "          \"_ref\": \"1\"\n" +
-          "        }\n" +
-          "      ]\n" +
-          "    }\n" +
-          "  ],\n" +
-          "  \"files\": {\n" +
-          "    \"1\": {\n" +
-          "      \"key\": \"%s\",\n" +
-          "      \"name\": \"%s\",\n" +
-          "      \"uuid\": \"%s\",\n" +
-          "      \"project\": \"%s\",\n" +
-          "      \"projectUuid\": \"%s\",\n" +
-          "      \"projectName\": \"%s\"\n" +
-          "      \"pullRequest\": \"%s\"\n" +
-          "    }\n" +
-          "  }\n" +
-          "}",
+        "  \"duplications\": [\n" +
+        "    {\n" +
+        "      \"blocks\": [\n" +
+        "        {\n" +
+        "          \"from\": 20,\n" +
+        "          \"size\": 5,\n" +
+        "          \"_ref\": \"1\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "          \"from\": 31,\n" +
+        "          \"size\": 5,\n" +
+        "          \"_ref\": \"1\"\n" +
+        "        }\n" +
+        "      ]\n" +
+        "    }\n" +
+        "  ],\n" +
+        "  \"files\": {\n" +
+        "    \"1\": {\n" +
+        "      \"key\": \"%s\",\n" +
+        "      \"name\": \"%s\",\n" +
+        "      \"uuid\": \"%s\",\n" +
+        "      \"project\": \"%s\",\n" +
+        "      \"projectUuid\": \"%s\",\n" +
+        "      \"projectName\": \"%s\"\n" +
+        "      \"pullRequest\": \"%s\"\n" +
+        "    }\n" +
+        "  }\n" +
+        "}",
         file.getKey(), file.longName(), file.uuid(), pullRequest.getKey(), pullRequest.uuid(), project.longName(), pullRequestKey));
   }
 
index 57e5e2fcf1fe23a762a008e36e8a47ac22d6923d..9ec4eb81015328ddbe0c5fee288fdd7bdebaa738 100644 (file)
@@ -224,6 +224,7 @@ public class AssignActionIT {
     IssueDto hotspot = dbTester.issues().insertHotspot(branch, file);
 
     insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
+    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
     UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project);
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
@@ -258,6 +259,7 @@ public class AssignActionIT {
     IssueDto hotspot = dbTester.issues().insertHotspot(branch, file);
 
     insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
+    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
     UserDto assignee = insertUser(randomAlphanumeric(15));
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
index 51720ba03dd6321a7cfa7847dcff695fcb7f67b6..2ea85ddda2d8abe0d6baf4c732f65ddc453236c1 100644 (file)
@@ -917,6 +917,7 @@ public class ShowActionIT {
     ComponentDto project = dbTester.components().insertPublicProject();
     String branchName = randomAlphanumeric(248);
     ComponentDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.uuid()));
     userSessionRule.registerComponents(project);
     RuleDto rule = newRule(SECURITY_HOTSPOT);
@@ -939,6 +940,7 @@ public class ShowActionIT {
     String pullRequestKey = randomAlphanumeric(100);
     ComponentDto pullRequest = dbTester.components().insertProjectBranch(project,
       t -> t.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
+    userSessionRule.addProjectBranchMapping(project.uuid(), pullRequest);
     ComponentDto file = dbTester.components().insertComponent(newFileDto(pullRequest));
     userSessionRule.registerComponents(project);
     RuleDto rule = newRule(SECURITY_HOTSPOT);
index 0ae3fbfc5ae7c8530197f4550143bf021f4f6b19..3b69d252d1230eca3148958c7dc6d0f8f6d4fc33 100644 (file)
@@ -388,6 +388,7 @@ public class BulkChangeActionIT {
     userSession.logIn(user);
     ComponentDto project = db.components().insertPrivateProject();
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature").setBranchType(BranchType.BRANCH));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto fileOnBranch = db.components().insertComponent(newFileDto(branch, project.uuid()));
     addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
     RuleDto rule = db.rules().insertIssueRule();
@@ -425,6 +426,7 @@ public class BulkChangeActionIT {
     userSession.logIn(user);
     ComponentDto project = db.components().insertPrivateProject();
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature").setBranchType(branchType));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto fileOnBranch = db.components().insertComponent(newFileDto(branch, project.uuid()));
     addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
     RuleDto rule = db.rules().insertIssueRule();
index d12e3934ea30cb28c01186db45d73d4be0fac638..979374a67fd3ba2b97309a9537f1473ea64f6222 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.server.measure.ws;
 
 import java.util.Optional;
 import java.util.function.Function;
-import java.util.function.Predicate;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
@@ -48,7 +47,6 @@ import static java.util.function.Predicate.not;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.assertj.core.api.Assertions.tuple;
-import static org.assertj.core.api.InstanceOfAssertFactories.OPTIONAL;
 import static org.sonar.api.utils.DateUtils.parseDateTime;
 import static org.sonar.api.web.UserRole.USER;
 import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
@@ -124,6 +122,7 @@ public class ComponentActionIT {
     userSession.addProjectPermission(USER, project);
     String branchName = "my_branch";
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     MetricDto complexity = db.measures().insertMetric(m1 -> m1.setKey("complexity").setValueType("INT"));
@@ -164,6 +163,7 @@ public class ComponentActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     MetricDto complexity = db.measures().insertMetric(m1 -> m1.setKey("complexity").setValueType("INT"));
@@ -187,6 +187,7 @@ public class ComponentActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     MetricDto bugs = db.measures().insertMetric(m1 -> m1.setKey("bugs").setValueType("INT"));
@@ -224,6 +225,7 @@ public class ComponentActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     MetricDto bugs = db.measures().insertMetric(m1 -> m1.setKey("bugs").setOptimizedBestValue(false).setValueType("INT"));
index bdf477370432d57ae2e35f20e9788871174dc13c..a03feacb19d9d94f3f6e7fbb818aa85bd170b0d5 100644 (file)
@@ -53,7 +53,6 @@ import org.sonarqube.ws.Measures.PeriodValue;
 
 import static java.lang.Double.parseDouble;
 import static java.lang.String.format;
-import static java.util.Collections.singletonList;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.assertj.core.api.Assertions.tuple;
@@ -525,6 +524,7 @@ public class ComponentTreeActionIT {
     userSession.addProjectPermission(USER, project);
     String branchName = "my-branch";
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     MetricDto complexity = db.measures().insertMetric(m -> m.setValueType(INT.name()));
@@ -563,8 +563,10 @@ public class ComponentTreeActionIT {
   @Test
   public void show_branch_on_empty_response_if_not_main_branch() {
     ComponentDto mainProjectBranch = db.components().insertPrivateProject();
-    ComponentDto branch = db.components().insertProjectBranch(mainProjectBranch, b -> b.setKey("develop"));
     userSession.addProjectPermission(USER, mainProjectBranch);
+    ComponentDto branch = db.components().insertProjectBranch(mainProjectBranch, b -> b.setKey("develop"));
+    userSession.addProjectBranchMapping(mainProjectBranch.uuid(), branch);
+
     ComponentDto file = db.components().insertComponent(newFileDto(branch, mainProjectBranch.uuid()));
     MetricDto complexity = db.measures().insertMetric(m -> m.setValueType(INT.name()));
 
@@ -583,6 +585,7 @@ public class ComponentTreeActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()).setMainBranchProjectUuid(project.uuid()));
     MetricDto complexity = db.measures().insertMetric(m -> m.setValueType(INT.name()));
@@ -606,6 +609,7 @@ public class ComponentTreeActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     MetricDto bug = db.measures().insertMetric(m -> m.setValueType(INT.name()).setKey(CoreMetrics.BUGS_KEY));
@@ -635,6 +639,7 @@ public class ComponentTreeActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(USER, project);
     ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setKey("pr").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), pr);
     SnapshotDto analysis = db.components().insertSnapshot(pr);
     ComponentDto file = db.components().insertComponent(newFileDto(pr, project.uuid()));
     MetricDto bug = db.measures().insertMetric(m -> m.setValueType(INT.name()).setKey(CoreMetrics.BUGS_KEY));
@@ -749,10 +754,14 @@ public class ComponentTreeActionIT {
     userSession.registerApplication(application);
     String branchName = "app-branch";
     ComponentDto applicationBranch = db.components().insertProjectBranch(application, a -> a.setKey(branchName), a -> a.setUuid("custom-uuid"));
+    userSession.addProjectBranchMapping(application.uuid(), applicationBranch);
     ComponentDto project = db.components().insertPrivateProject(p -> p.setKey("project-key"));
+
     ComponentDto projectBranch = db.components().insertProjectBranch(project, b -> b.setKey("project-branch"));
+    userSession.addProjectBranchMapping(project.uuid(), projectBranch);
     ComponentDto techProjectBranch = db.components().insertComponent(newProjectCopy(projectBranch, applicationBranch)
       .setKey(applicationBranch.getKey() + branchName + projectBranch.getKey()));
+
     SnapshotDto applicationBranchAnalysis = db.components().insertSnapshot(applicationBranch);
     db.measures().insertLiveMeasure(applicationBranch, ncloc, m -> m.setValue(5d));
     db.measures().insertLiveMeasure(techProjectBranch, ncloc, m -> m.setValue(1d));
index 0305abd358f57bc6718bab4d4c17468fe0abb9bd..1071677054962a9cef8077d4417cf70f8327c50a 100644 (file)
@@ -220,6 +220,7 @@ public class SearchActionIT {
   public void return_measures_on_sub_view() {
     ComponentDto view = db.components().insertPrivatePortfolio();
     ComponentDto subView = db.components().insertComponent(newSubPortfolio(view));
+    userSession.addProjectPermission(UserRole.USER, view);
     userSession.addProjectPermission(UserRole.USER, subView);
     MetricDto metric = db.measures().insertMetric(m -> m.setValueType(FLOAT.name()));
     db.measures().insertLiveMeasure(subView, metric, m -> m.setValue(15.5d));
@@ -265,7 +266,7 @@ public class SearchActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project);
 
-    assertThatThrownBy(() ->  call(singletonList(project.uuid()), null))
+    assertThatThrownBy(() -> call(singletonList(project.uuid()), null))
       .isInstanceOf(IllegalArgumentException.class)
       .hasMessage("The 'metricKeys' parameter is missing");
   }
@@ -286,7 +287,7 @@ public class SearchActionIT {
     userSession.addProjectPermission(UserRole.USER, project);
     MetricDto metric = db.measures().insertMetric();
 
-    assertThatThrownBy(() ->  call(singletonList(project.getKey()), newArrayList("violations", metric.getKey(), "ncloc")))
+    assertThatThrownBy(() -> call(singletonList(project.getKey()), newArrayList("violations", metric.getKey(), "ncloc")))
       .isInstanceOf(BadRequestException.class)
       .hasMessage("The following metrics are not found: ncloc, violations");
   }
index 6488d86ca01c0a2d4ab85e98b8c3259edb515f7e..222b4ac399b48677ff5bc04d7a428b449377e42c 100644 (file)
@@ -296,6 +296,7 @@ public class SearchHistoryActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     MeasureDto measure = db.measures().insertMeasure(file, analysis, nclocMetric, m -> m.setValue(2d));
@@ -319,6 +320,7 @@ public class SearchHistoryActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     SnapshotDto analysis = db.components().insertSnapshot(branch);
     MeasureDto measure = db.measures().insertMeasure(file, analysis, nclocMetric, m -> m.setValue(2d));
@@ -404,8 +406,8 @@ public class SearchHistoryActionIT {
       .setParam(PARAM_COMPONENT, "file-key")
       .setParam(PARAM_METRICS, "ncloc")
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining("Component key 'file-key' not found");
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining("Component key 'file-key' not found");
   }
 
   @Test
@@ -420,8 +422,8 @@ public class SearchHistoryActionIT {
       .setParam(PARAM_BRANCH, "another_branch")
       .setParam(PARAM_METRICS, "ncloc")
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
   }
 
   @Test
index 66972c2c75f6e184fa5d378ec65bf609ecbd5c09..544a21daa8452558c9686a422fb8b57167bd8bdc 100644 (file)
@@ -71,7 +71,6 @@ import static org.assertj.core.api.Assertions.tuple;
 import static org.sonar.api.utils.DateUtils.formatDate;
 import static org.sonar.api.utils.DateUtils.formatDateTime;
 import static org.sonar.api.utils.DateUtils.parseDateTime;
-import static org.sonar.db.component.BranchType.BRANCH;
 import static org.sonar.db.component.ComponentDbTester.toProjectDto;
 import static org.sonar.db.component.ComponentTesting.newBranchDto;
 import static org.sonar.db.component.ComponentTesting.newFileDto;
@@ -585,6 +584,7 @@ public class SearchActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(branch));
     EventDto event = db.events().insertEvent(newEvent(analysis).setCategory(QUALITY_GATE.getLabel()));
 
index 44bd67d9f6d896233df23aaac967503fac6fde9e..3535aed77d4e697a917a489b3a565a097d4adaac 100644 (file)
@@ -109,7 +109,8 @@ public class GetActionIT {
     dao.insert(dbTester.getSession(), project1.getUuid(), stringToCompressedInputStream("test data1"));
     dao.insert(dbTester.getSession(), branch.getUuid(), stringToCompressedInputStream("test data2"));
 
-    userSession.logIn().addProjectPermission(SCAN, project1);
+    userSession.logIn().addProjectPermission(SCAN, project1)
+      .registerBranches(branch);
     TestResponse response = wsTester.newRequest()
       .setParam("project", project1.getKey())
       .setParam("branch", branch.getKey())
index fcd531463707d119032cd05ab65f27bc97f45cba..fe88307c97371898b3ad5d27d98be64bbd163b45 100644 (file)
@@ -32,7 +32,6 @@ import org.sonar.api.utils.System2;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
-import org.sonar.db.component.ComponentDbTester;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentTesting;
 import org.sonar.db.property.PropertyDbTester;
@@ -209,6 +208,7 @@ public class ResetActionIT {
     definitions.addComponent(PropertyDefinition.builder("foo").onQualifiers(PROJECT).build());
     propertyDb.insertProperties(null, branch.name(), null, null, newComponentPropertyDto(branch).setKey("foo").setValue("value"));
     userSession.logIn().addProjectPermission(ADMIN, project);
+    userSession.addProjectBranchMapping(project.uuid(), branch);
 
     ws.newRequest()
       .setMediaType(MediaTypes.PROTOBUF)
@@ -478,9 +478,9 @@ public class ResetActionIT {
 
   private void assertUserPropertyExists(String key, UserDto user) {
     assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
-        .setKey(key)
-        .setUserUuid(user.getUuid())
-        .build(),
+      .setKey(key)
+      .setUserUuid(user.getUuid())
+      .build(),
       dbSession)).isNotEmpty();
   }
 
index 7d5e9a6add6b1b2c2d854070c1e6e7f19e2bbfc4..665f524774adf918b517c8ec12b57eec387800e2 100644 (file)
@@ -80,7 +80,7 @@ public class LinesActionIT {
   public void show_source() {
     ComponentDto privateProject = db.components().insertPrivateProject();
     ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(3).build(), privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     TestResponse response = tester.newRequest()
       .setParam("uuid", file.uuid())
@@ -93,7 +93,7 @@ public class LinesActionIT {
   public void fail_to_show_source_if_no_source_found() {
     ComponentDto privateProject = db.components().insertPrivateProject();
     ComponentDto file = insertFile(privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     TestRequest request = tester.newRequest()
       .setParam("uuid", file.uuid());
@@ -106,7 +106,7 @@ public class LinesActionIT {
   public void show_paginated_lines() {
     ComponentDto privateProject = db.components().insertPrivateProject();
     ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(3).build(), privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     tester
       .newRequest()
@@ -120,7 +120,7 @@ public class LinesActionIT {
   @Test
   public void branch() {
     ComponentDto project = db.components().insertPrivateProject();
-    userSession.addProjectPermission(UserRole.USER, project);
+
     String branchName = randomAlphanumeric(248);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
@@ -132,6 +132,8 @@ public class LinesActionIT {
     db.commit();
 
     userSession.logIn("login")
+      .addProjectPermission(UserRole.USER, project)
+      .addProjectBranchMapping(project.uuid(), branch)
       .addProjectPermission(UserRole.CODEVIEWER, project, file);
 
     tester.newRequest()
@@ -144,7 +146,6 @@ public class LinesActionIT {
   @Test
   public void pull_request() {
     ComponentDto project = db.components().insertPrivateProject();
-    userSession.addProjectPermission(UserRole.USER, project);
     String pullRequestKey = randomAlphanumeric(100);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
@@ -156,7 +157,9 @@ public class LinesActionIT {
     db.commit();
 
     userSession.logIn("login")
-      .addProjectPermission(UserRole.CODEVIEWER, project, file);
+      .addProjectPermission(UserRole.USER, project)
+      .addProjectPermission(UserRole.CODEVIEWER, project, file)
+      .registerComponents(branch);
 
     tester.newRequest()
       .setParam("key", file.getKey())
@@ -191,7 +194,7 @@ public class LinesActionIT {
     ComponentDto privateProject = db.components().insertPrivateProject();
     ComponentDto file = newFileDto(privateProject).setKey("file-key").setEnabled(false);
     db.components().insertComponents(file);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     assertThatThrownBy(() -> tester.newRequest().setParam("key", "file-key").execute())
       .isInstanceOf(NotFoundException.class)
@@ -217,7 +220,7 @@ public class LinesActionIT {
   public void display_deprecated_fields() {
     ComponentDto privateProject = db.components().insertPrivateProject();
     ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(1).build(), privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     tester.newRequest()
       .setParam("uuid", file.uuid())
@@ -235,7 +238,7 @@ public class LinesActionIT {
     ComponentDto project = db.components().insertPrivateProject();
     insertPeriod(project, 2000L);
     ComponentDto file = insertFileWithData(dataBuilder.build(), project);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, project);
 
     tester.newRequest()
       .setParam("uuid", file.uuid())
@@ -257,7 +260,7 @@ public class LinesActionIT {
       .setDeprecatedItLineHits(1)
       .setDeprecatedItConditions(2)
       .setDeprecatedItCoveredConditions(3)).build(), privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     tester.newRequest()
       .setParam("uuid", file.uuid())
@@ -276,7 +279,7 @@ public class LinesActionIT {
       .setDeprecatedItLineHits(1)
       .setDeprecatedItConditions(2)
       .setDeprecatedItCoveredConditions(3)).build(), privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     tester.newRequest()
       .setParam("uuid", file.uuid())
@@ -292,7 +295,7 @@ public class LinesActionIT {
       .setDeprecatedItLineHits(1)
       .setDeprecatedItConditions(2)
       .setDeprecatedItCoveredConditions(3)).build(), privateProject);
-    setUserWithValidPermission(file);
+    setUserWithValidPermission(file, privateProject);
 
     tester.newRequest()
       .setParam("uuid", file.uuid())
@@ -311,8 +314,8 @@ public class LinesActionIT {
       .setParam("key", file.getKey())
       .setParam("branch", "another_branch")
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
   }
 
   @Test
@@ -326,8 +329,8 @@ public class LinesActionIT {
       .setParam("uuid", file.uuid())
       .setParam("branch", "another_branch")
       .execute())
-      .isInstanceOf(IllegalArgumentException.class)
-      .hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'");
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'");
   }
 
   @Test
@@ -339,8 +342,8 @@ public class LinesActionIT {
     assertThatThrownBy(() -> tester.newRequest()
       .setParam("uuid", branch.uuid())
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining(format("Component id '%s' not found", branch.uuid()));
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining(format("Component id '%s' not found", branch.uuid()));
   }
 
   @Test
@@ -390,8 +393,7 @@ public class LinesActionIT {
     return file;
   }
 
-  private void setUserWithValidPermission(ComponentDto file) {
-    ComponentDto privateProject = db.components().insertPrivateProject();
+  private void setUserWithValidPermission(ComponentDto file, ComponentDto privateProject) {
     userSession.logIn("login")
       .addProjectPermission(UserRole.CODEVIEWER, privateProject, file);
   }
index 7eaf4a53ec61860d1bf6ed277eecbb0c2b5f4653..518e4155fd122958584a8a8c9584ab9db75a045d 100644 (file)
@@ -79,6 +79,7 @@ public class RawActionIT {
     userSession.addProjectPermission(UserRole.CODEVIEWER, project);
     String branchName = randomAlphanumeric(248);
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
     db.fileSources().insertFileSource(file, s -> s.setSourceData(
       Data.newBuilder()
@@ -99,8 +100,8 @@ public class RawActionIT {
     assertThatThrownBy(() -> ws.newRequest()
       .setParam("key", "unknown")
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining("Component key 'unknown' not found");
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining("Component key 'unknown' not found");
   }
 
   @Test
@@ -115,8 +116,8 @@ public class RawActionIT {
       .setParam("key", file.getKey())
       .setParam("branch", "unknown")
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining(format("Component '%s' on branch 'unknown' not found", file.getKey()));
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining(format("Component '%s' on branch 'unknown' not found", file.getKey()));
   }
 
   @Test
@@ -130,8 +131,8 @@ public class RawActionIT {
     assertThatThrownBy(() -> ws.newRequest()
       .setParam("key", file.getKey())
       .execute())
-      .isInstanceOf(NotFoundException.class)
-      .hasMessageContaining(format("Component key '%s' not found", file.getKey()));
+        .isInstanceOf(NotFoundException.class)
+        .hasMessageContaining(format("Component key '%s' not found", file.getKey()));
   }
 
   @Test
@@ -143,6 +144,6 @@ public class RawActionIT {
     assertThatThrownBy(() -> ws.newRequest()
       .setParam("key", file.getKey())
       .execute())
-      .isInstanceOf(ForbiddenException.class);
+        .isInstanceOf(ForbiddenException.class);
   }
 }
index accf986bb328546d683803a1e2ab6e8791d551b5..469ec426a1dcc9c5a80bb694b3c0f3ece784782f 100644 (file)
@@ -168,11 +168,12 @@ public class ComponentActionIT {
   public void return_favourite_for_branch() {
     ComponentDto project = insertProject();
     String branchName = "feature1";
-    componentDbTester.insertProjectBranch(project, b -> b.setKey(branchName).setUuid("xyz"));
+    ComponentDto branch = componentDbTester.insertProjectBranch(project, b -> b.setKey(branchName).setUuid("xyz"));
     UserDto user = db.users().insertUser("obiwan");
     propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setComponentUuid(project.uuid()).setUserUuid(user.getUuid()),
       project.getKey(), project.name(), project.qualifier(), user.getLogin());
-    userSession.logIn(user).addProjectPermission(UserRole.USER, project);
+    userSession.logIn(user).addProjectPermission(UserRole.USER, project)
+      .addProjectBranchMapping(project.uuid(), branch);
     init();
 
     String json = ws.newRequest()
@@ -202,7 +203,8 @@ public class ComponentActionIT {
     propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setComponentUuid(subportfolio.uuid()).setUserUuid(user.getUuid()),
       subportfolio.getKey(), subportfolio.name(), subportfolio.qualifier(), user.getLogin());
 
-    userSession.logIn(user).addProjectPermission(UserRole.USER, subportfolio);
+    userSession.logIn(user).addProjectPermission(UserRole.USER, portfolio)
+      .addProjectPermission(UserRole.USER, subportfolio);
     init();
 
     String json = ws.newRequest()
@@ -317,6 +319,7 @@ public class ComponentActionIT {
     String branchName = "feature1";
     ComponentDto branch = componentDbTester.insertProjectBranch(project, b -> b.setKey(branchName));
     userSession.addProjectPermission(UserRole.USER, project);
+    userSession.addProjectBranchMapping(project.uuid(), branch);
     init();
     ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(branch, "src"));
     ComponentDto fileDto = componentDbTester.insertComponent(newFileDto(project.uuid(), branch, dirDto)
@@ -400,7 +403,8 @@ public class ComponentActionIT {
     BranchDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
     QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way"));
     db.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
-    userSession.addProjectPermission(UserRole.USER, project);
+    userSession.addProjectPermission(UserRole.USER, project)
+      .addProjectBranchMapping(project.getUuid(), db.components().getComponentDto(branch));
     init();
 
     String json = ws.newRequest()