diff options
30 files changed, 649 insertions, 641 deletions
diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java index 01788086927..684524fade4 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java @@ -24,7 +24,6 @@ import java.util.function.Consumer; import javax.annotation.Nullable; import org.sonar.db.DbSession; import org.sonar.db.DbTester; -import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.UserDto; public class OrganizationDbTester { @@ -69,18 +68,6 @@ public class OrganizationDbTester { return dto; } - public void setDefaultTemplates(PermissionTemplateDto projectDefaultTemplate, @Nullable PermissionTemplateDto applicationDefaultTemplate, - @Nullable PermissionTemplateDto portfolioDefaultTemplate) { - - DbSession dbSession = db.getSession(); - db.getDbClient().organizationDao().setDefaultTemplates(dbSession, db.getDefaultOrganization().getUuid(), - new DefaultTemplates() - .setProjectUuid(projectDefaultTemplate.getUuid()) - .setPortfoliosUuid(portfolioDefaultTemplate == null ? null : portfolioDefaultTemplate.getUuid()) - .setApplicationsUuid(applicationDefaultTemplate == null ? null : applicationDefaultTemplate.getUuid())); - dbSession.commit(); - } - public void setDefaultTemplates(String projectDefaultTemplateUuid, @Nullable String applicationDefaultTemplateUuid, @Nullable String portfoliosDefaultTemplateUuid) { DbSession dbSession = db.getSession(); db.getDbClient().organizationDao().setDefaultTemplates(dbSession, db.getDefaultOrganization().getUuid(), diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java index eae6c1c8fac..50a0f665a9d 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java @@ -26,6 +26,7 @@ import org.sonar.db.DbTester; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; +import static java.util.Optional.ofNullable; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateCharacteristicDto; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; @@ -40,6 +41,24 @@ public class PermissionTemplateDbTester { this.dbSession = db.getSession(); } + public void setDefaultTemplates(String projectDefaultTemplateUuid, @Nullable String applicationDefaultTemplateUuid, @Nullable String portfoliosDefaultTemplateUuid) { + db.getDbClient().internalPropertiesDao().save(dbSession, "defaultTemplate.prj", projectDefaultTemplateUuid); + if (applicationDefaultTemplateUuid != null) { + db.getDbClient().internalPropertiesDao().save(dbSession, "defaultTemplate.app", applicationDefaultTemplateUuid); + } + if (portfoliosDefaultTemplateUuid != null) { + db.getDbClient().internalPropertiesDao().save(dbSession, "defaultTemplate.port", portfoliosDefaultTemplateUuid); + } + dbSession.commit(); + } + + public void setDefaultTemplates(PermissionTemplateDto projectDefaultTemplate, @Nullable PermissionTemplateDto applicationDefaultTemplate, + @Nullable PermissionTemplateDto portfoliosDefaultTemplate) { + setDefaultTemplates(projectDefaultTemplate.getUuid(), + ofNullable(applicationDefaultTemplate).map(PermissionTemplateDto::getUuid).orElse(null), + ofNullable(portfoliosDefaultTemplate).map(PermissionTemplateDto::getUuid).orElse(null)); + } + public PermissionTemplateDto insertTemplate() { return insertTemplate(newPermissionTemplateDto()); } diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v85/package-info.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v85/package-info.java new file mode 100644 index 00000000000..62c81368b98 --- /dev/null +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v85/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube + * Copyright (C) 2009-2020 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.server.platform.db.migration.version.v85; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/DbVersion86.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/DbVersion86.java index d759359e750..9e2283de50d 100644 --- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/DbVersion86.java +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/DbVersion86.java @@ -41,6 +41,7 @@ public class DbVersion86 implements DbVersion { .add(4111, "Drop 'organization_uuid' in 'groups'", DropOrganizationInGroups.class) .add(4112, "Make 'name' column in 'groups' table not nullable", MakeNameColumnInGroupsTableNotNullable.class) .add(4113, "Make 'name' column in 'groups' table unique", AddUniqueIndexOnNameColumnOfGroupsTable.class) + .add(4114, "Move default permission templates to internal properties", MoveDefaultTemplatesToInternalProperties.class) ; } } diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalProperties.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalProperties.java new file mode 100644 index 00000000000..bec8fff7402 --- /dev/null +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalProperties.java @@ -0,0 +1,109 @@ +/* + * SonarQube + * Copyright (C) 2009-2020 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.platform.db.migration.version.v86; + +import java.sql.SQLException; +import java.util.Optional; +import org.sonar.api.utils.System2; +import org.sonar.db.Database; +import org.sonar.server.platform.db.migration.step.DataChange; +import org.sonar.server.platform.db.migration.step.Select; +import org.sonar.server.platform.db.migration.step.Upsert; + +public class MoveDefaultTemplatesToInternalProperties extends DataChange { + + private final System2 system2; + + public MoveDefaultTemplatesToInternalProperties(Database db, System2 system2) { + super(db); + this.system2 = system2; + } + + @Override + protected void execute(Context context) throws SQLException { + OrganizationDefaultTemplates organizationDefaultTemplates = context + .prepareSelect("select org.default_perm_template_project, org.default_perm_template_port, org.default_perm_template_app from organizations org " + + "where org.kee = 'default-organization'") + .get(OrganizationDefaultTemplates::new); + if (organizationDefaultTemplates == null) { + throw new IllegalStateException("Default organization is missing"); + } + Upsert updateInternalProperties = context.prepareUpsert("insert into internal_properties (kee, text_value, is_empty, created_at) values (?, ?, ?, ?)"); + + Optional<String> defaultPermissionTemplateForProject = organizationDefaultTemplates.getDefaultPermissionTemplateForProject(); + if (defaultPermissionTemplateForProject.isPresent()) { + insertInInternalProperties(context, updateInternalProperties, "defaultTemplate.prj", defaultPermissionTemplateForProject.get()); + } else { + // If default permission templates are missing, they will be added during the startup task "RegisterPermissionTemplates" + return; + } + + organizationDefaultTemplates.getDefaultPermissionTemplateForPortfolio() + .ifPresent( + defaultPermissionTemplate -> insertInInternalProperties(context, updateInternalProperties, "defaultTemplate.port", defaultPermissionTemplate)); + organizationDefaultTemplates.getDefaultPermissionTemplateForApplication() + .ifPresent( + defaultPermissionTemplate -> insertInInternalProperties(context, updateInternalProperties, "defaultTemplate.app", defaultPermissionTemplate)); + } + + private void insertInInternalProperties(Context context, Upsert updateInternalProperties, String key, String value) { + try { + Integer isInternalPropertyAlreadyExists = context.prepareSelect("select count(1) from internal_properties ip where ip.kee = ?") + .setString(1, key) + .get(row -> row.getInt(1)); + if (isInternalPropertyAlreadyExists != null && isInternalPropertyAlreadyExists > 0) { + return; + } + updateInternalProperties + .setString(1, key) + .setString(2, value) + .setBoolean(3, false) + .setLong(4, system2.now()) + .execute() + .commit(); + } catch (SQLException throwables) { + throw new IllegalStateException(throwables); + } + } + + private static class OrganizationDefaultTemplates { + private final String defaultPermissionTemplateForProject; + private final String defaultPermissionTemplateForPortfolio; + private final String defaultPermissionTemplateForApplication; + + OrganizationDefaultTemplates(Select.Row row) throws SQLException { + this.defaultPermissionTemplateForProject = row.getNullableString(1); + this.defaultPermissionTemplateForPortfolio = row.getNullableString(2); + this.defaultPermissionTemplateForApplication = row.getNullableString(3); + } + + Optional<String> getDefaultPermissionTemplateForProject() { + return Optional.ofNullable(defaultPermissionTemplateForProject); + } + + Optional<String> getDefaultPermissionTemplateForPortfolio() { + return Optional.ofNullable(defaultPermissionTemplateForPortfolio); + } + + Optional<String> getDefaultPermissionTemplateForApplication() { + return Optional.ofNullable(defaultPermissionTemplateForApplication); + } + } +} diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/package-info.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/package-info.java new file mode 100644 index 00000000000..f5eff666f26 --- /dev/null +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v86/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube + * Copyright (C) 2009-2020 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.server.platform.db.migration.version.v86; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalPropertiesTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalPropertiesTest.java new file mode 100644 index 00000000000..32a6c3badd5 --- /dev/null +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalPropertiesTest.java @@ -0,0 +1,150 @@ +/* + * SonarQube + * Copyright (C) 2009-2020 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.platform.db.migration.version.v86; + +import java.sql.SQLException; +import javax.annotation.Nullable; +import org.assertj.core.groups.Tuple; +import org.junit.Rule; +import org.junit.Test; +import org.sonar.api.impl.utils.TestSystem2; +import org.sonar.api.utils.System2; +import org.sonar.core.util.UuidFactory; +import org.sonar.core.util.UuidFactoryFast; +import org.sonar.db.CoreDbTester; +import org.sonar.server.platform.db.migration.step.DataChange; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; + +public class MoveDefaultTemplatesToInternalPropertiesTest { + + private static final long NOW = 100_000_000_000L; + + @Rule + public CoreDbTester db = CoreDbTester.createForSchema(MoveDefaultTemplatesToInternalPropertiesTest.class, "schema.sql"); + + private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); + private final System2 system2 = new TestSystem2().setNow(NOW); + + private final DataChange underTest = new MoveDefaultTemplatesToInternalProperties(db.database(), system2); + + @Test + public void create_internal_properties_for_all_components() throws SQLException { + insertDefaultOrganization("PRJ", "PORT", "APP"); + + underTest.execute(); + + assertInternalProperties( + tuple("defaultTemplate.prj", "PRJ", NOW), + tuple("defaultTemplate.port", "PORT", NOW), + tuple("defaultTemplate.app", "APP", NOW) + ); + } + + @Test + public void create_internal_properties_when_only_template_for_project() throws SQLException { + insertDefaultOrganization("PRJ", null, null); + + underTest.execute(); + + assertInternalProperties( + tuple("defaultTemplate.prj", "PRJ", NOW)); + } + + @Test + public void create_internal_properties_when_template_for_project_and_portfolio() throws SQLException { + insertDefaultOrganization("PRJ", "PORT", null); + + underTest.execute(); + + assertInternalProperties( + tuple("defaultTemplate.prj", "PRJ", NOW), + tuple("defaultTemplate.port", "PORT", NOW) + ); + } + + @Test + public void create_internal_properties_when_template_for_project_and_application() throws SQLException { + insertDefaultOrganization("PRJ", null, "APP"); + + underTest.execute(); + + assertInternalProperties( + tuple("defaultTemplate.prj", "PRJ", NOW), + tuple("defaultTemplate.app", "APP", NOW) + ); + } + + @Test + public void do_nothing_when_permission_template_for_project_is_missing() throws SQLException { + insertDefaultOrganization(null, null, "APP"); + + underTest.execute(); + + assertThat(db.countRowsOfTable("internal_properties")).isZero(); + } + + @Test + public void migration_is_reentrant() throws SQLException { + insertDefaultOrganization("PRJ", "PORT", "APP"); + + underTest.execute(); + underTest.execute(); + + assertInternalProperties( + tuple("defaultTemplate.prj", "PRJ", NOW), + tuple("defaultTemplate.port", "PORT", NOW), + tuple("defaultTemplate.app", "APP", NOW) + ); + } + + @Test + public void fail_when_default_organization_is_missing() { + assertThatThrownBy(underTest::execute) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Default organization is missing"); + } + + private void assertInternalProperties(Tuple... tuples) { + assertThat(db.select("select kee, text_value, created_at from internal_properties")) + .extracting(m -> m.get("KEE"), m -> m.get("TEXT_VALUE"), m -> m.get("CREATED_AT")) + .containsExactlyInAnyOrder(tuples); + } + + private void insertDefaultOrganization(@Nullable String defaultPermissionTemplateForProject, @Nullable String defaultPermissionTemplateForPortfolio, + @Nullable String defaultPermissionTemplateForApplication) { + String uuid = uuidFactory.create(); + db.executeInsert("organizations", + "uuid", uuid, + "kee", "default-organization", + "name", "name" + uuid, + "default_perm_template_project", defaultPermissionTemplateForProject, + "default_perm_template_port", defaultPermissionTemplateForPortfolio, + "default_perm_template_app", defaultPermissionTemplateForApplication, + "default_quality_gate_uuid", uuid, + "new_project_private", true, + "subscription", uuid, + "created_at", NOW, + "updated_at", NOW); + } + +} diff --git a/server/sonar-db-migration/src/test/resources/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalPropertiesTest/schema.sql b/server/sonar-db-migration/src/test/resources/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalPropertiesTest/schema.sql new file mode 100644 index 00000000000..a101d7797ce --- /dev/null +++ b/server/sonar-db-migration/src/test/resources/org/sonar/server/platform/db/migration/version/v86/MoveDefaultTemplatesToInternalPropertiesTest/schema.sql @@ -0,0 +1,29 @@ +CREATE TABLE "INTERNAL_PROPERTIES"( + "KEE" VARCHAR(20) NOT NULL, + "IS_EMPTY" BOOLEAN NOT NULL, + "TEXT_VALUE" VARCHAR(4000), + "CLOB_VALUE" CLOB, + "CREATED_AT" BIGINT NOT NULL +); +ALTER TABLE "INTERNAL_PROPERTIES" ADD CONSTRAINT "PK_INTERNAL_PROPERTIES" PRIMARY KEY("KEE"); + +CREATE TABLE "ORGANIZATIONS"( + "UUID" VARCHAR(40) NOT NULL, + "KEE" VARCHAR(255) NOT NULL, + "NAME" VARCHAR(255) NOT NULL, + "DESCRIPTION" VARCHAR(256), + "URL" VARCHAR(256), + "AVATAR_URL" VARCHAR(256), + "GUARDED" BOOLEAN, + "DEFAULT_QUALITY_GATE_UUID" VARCHAR(40) NOT NULL, + "DEFAULT_PERM_TEMPLATE_PROJECT" VARCHAR(40), + "DEFAULT_PERM_TEMPLATE_APP" VARCHAR(40), + "DEFAULT_PERM_TEMPLATE_PORT" VARCHAR(40), + "NEW_PROJECT_PRIVATE" BOOLEAN NOT NULL, + "SUBSCRIPTION" VARCHAR(40) NOT NULL, + "CREATED_AT" BIGINT NOT NULL, + "UPDATED_AT" BIGINT NOT NULL, + "DEFAULT_GROUP_UUID" VARCHAR(40) +); +ALTER TABLE "ORGANIZATIONS" ADD CONSTRAINT "PK_ORGANIZATIONS" PRIMARY KEY("UUID"); +CREATE UNIQUE INDEX "ORGANIZATION_KEY" ON "ORGANIZATIONS"("KEE"); diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalProperties.java b/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalProperties.java index 0baea30e81a..55cb14407d1 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalProperties.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalProperties.java @@ -54,6 +54,13 @@ public interface InternalProperties { String INSTALLATION_VERSION = "installation.version"; /** + * Default permission templates + */ + String DEFAULT_PROJECT_TEMPLATE = "defaultTemplate.prj"; + String DEFAULT_PORTFOLIO_TEMPLATE = "defaultTemplate.port"; + String DEFAULT_APPLICATION_TEMPLATE = "defaultTemplate.app"; + + /** * Read the value of the specified property. * * @return {@link Optional#empty()} if the property does not exist, an empty string if the property is empty, diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/organization/OrganizationUpdaterImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/organization/OrganizationUpdaterImplTest.java index 290adc759ad..90e1462d8a7 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/organization/OrganizationUpdaterImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/organization/OrganizationUpdaterImplTest.java @@ -30,7 +30,6 @@ import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; -import org.sonar.api.web.UserRole; import org.sonar.core.permission.GlobalPermissions; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.UuidFactory; @@ -38,11 +37,8 @@ import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.organization.OrganizationDto; import org.sonar.db.organization.OrganizationDto.Subscription; -import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.db.permission.template.PermissionTemplateGroupDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.RulesProfileDto; @@ -65,7 +61,6 @@ import org.sonar.server.usergroups.DefaultGroupCreatorImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.language.LanguageTesting.newLanguage; diff --git a/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/BackendCleanup.java b/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/BackendCleanup.java index c8b26751aa4..b7bbd9b0782 100644 --- a/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/BackendCleanup.java +++ b/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/BackendCleanup.java @@ -229,9 +229,12 @@ public class BackendCleanup { * Internal property {@link InternalProperties#DEFAULT_ORGANIZATION} must never be deleted. */ private static void truncateInternalProperties(String tableName, Statement ddlStatement, Connection connection) throws SQLException { - try (PreparedStatement preparedStatement = connection.prepareStatement("delete from internal_properties where kee not in (?,?)")) { + try (PreparedStatement preparedStatement = connection.prepareStatement("delete from internal_properties where kee not in (?,?,?,?,?)")) { preparedStatement.setString(1, InternalProperties.DEFAULT_ORGANIZATION); preparedStatement.setString(2, InternalProperties.SERVER_ID_CHECKSUM); + preparedStatement.setString(3, InternalProperties.DEFAULT_PROJECT_TEMPLATE); + preparedStatement.setString(4, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE); + preparedStatement.setString(5, InternalProperties.DEFAULT_APPLICATION_TEMPLATE); preparedStatement.execute(); // commit is useless on some databases connection.commit(); diff --git a/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java b/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java index ce495844b16..a027562baff 100644 --- a/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java +++ b/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java @@ -23,31 +23,35 @@ import java.util.Date; import java.util.Optional; import org.picocontainer.Startable; import org.sonar.api.security.DefaultGroups; +import org.sonar.api.utils.System2; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.api.web.UserRole; +import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.permission.OrganizationPermission; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; -import org.sonar.server.organization.DefaultOrganizationProvider; +import org.sonar.server.usergroups.DefaultGroupFinder; -import static java.lang.String.format; +import static org.sonar.server.property.InternalProperties.DEFAULT_PROJECT_TEMPLATE; public class RegisterPermissionTemplates implements Startable { private static final Logger LOG = Loggers.get(RegisterPermissionTemplates.class); - private static final String DEFAULT_TEMPLATE_UUID = "default_template"; private final DbClient dbClient; - private final DefaultOrganizationProvider defaultOrganizationProvider; + private final UuidFactory uuidFactory; + private final System2 system2; + private final DefaultGroupFinder defaultGroupFinder; - public RegisterPermissionTemplates(DbClient dbClient, DefaultOrganizationProvider defaultOrganizationProvider) { + public RegisterPermissionTemplates(DbClient dbClient, UuidFactory uuidFactory, System2 system2, DefaultGroupFinder defaultGroupFinder) { this.dbClient = dbClient; - this.defaultOrganizationProvider = defaultOrganizationProvider; + this.uuidFactory = uuidFactory; + this.system2 = system2; + this.defaultGroupFinder = defaultGroupFinder; } @Override @@ -55,11 +59,10 @@ public class RegisterPermissionTemplates implements Startable { Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register permission templates"); try (DbSession dbSession = dbClient.openSession(false)) { - String defaultOrganizationUuid = defaultOrganizationProvider.get().getUuid(); - Optional<DefaultTemplates> defaultTemplates = dbClient.organizationDao().getDefaultTemplates(dbSession, defaultOrganizationUuid); - if (!defaultTemplates.isPresent()) { + Optional<String> defaultProjectTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, DEFAULT_PROJECT_TEMPLATE); + if (!defaultProjectTemplate.isPresent()) { PermissionTemplateDto defaultTemplate = getOrInsertDefaultTemplate(dbSession); - dbClient.organizationDao().setDefaultTemplates(dbSession, defaultOrganizationUuid, new DefaultTemplates().setProjectUuid(defaultTemplate.getUuid())); + dbClient.internalPropertiesDao().save(dbSession, DEFAULT_PROJECT_TEMPLATE, defaultTemplate.getUuid()); dbSession.commit(); } } @@ -73,17 +76,12 @@ public class RegisterPermissionTemplates implements Startable { } private PermissionTemplateDto getOrInsertDefaultTemplate(DbSession dbSession) { - PermissionTemplateDto permissionTemplateDto = dbClient.permissionTemplateDao().selectByUuid(dbSession, DEFAULT_TEMPLATE_UUID); - if (permissionTemplateDto != null) { - return permissionTemplateDto; - } - PermissionTemplateDto template = new PermissionTemplateDto() .setName("Default template") - .setUuid(DEFAULT_TEMPLATE_UUID) + .setUuid(uuidFactory.create()) .setDescription("This permission template will be used as default when no other permission configuration is available") - .setCreatedAt(new Date()) - .setUpdatedAt(new Date()); + .setCreatedAt(new Date(system2.now())) + .setUpdatedAt(new Date(system2.now())); dbClient.permissionTemplateDao().insert(dbSession, template); insertDefaultGroupPermissions(dbSession, template); @@ -108,10 +106,7 @@ public class RegisterPermissionTemplates implements Startable { } private void insertPermissionsForDefaultGroup(DbSession dbSession, PermissionTemplateDto template) { - String defaultGroupUuid = dbClient.organizationDao().getDefaultGroupUuid(dbSession, defaultOrganizationProvider.get().getUuid()) - .orElseThrow(() -> new IllegalStateException("Default group is not defined")); - GroupDto defaultGroup = Optional.ofNullable(dbClient.groupDao().selectByUuid(dbSession, defaultGroupUuid)) - .orElseThrow(() -> new IllegalStateException(format("Default group with id %s doesn't exist", defaultGroupUuid))); + GroupDto defaultGroup = defaultGroupFinder.findDefaultGroup(dbSession); insertGroupPermission(dbSession, template, UserRole.USER, defaultGroup); insertGroupPermission(dbSession, template, UserRole.CODEVIEWER, defaultGroup); insertGroupPermission(dbSession, template, UserRole.ISSUE_ADMIN, defaultGroup); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java index 1c9d0879c11..ebb7b0f1cd0 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java @@ -25,30 +25,24 @@ import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.ResourceTypes; import org.sonar.api.security.DefaultGroups; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.api.web.UserRole; +import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbTester; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.permission.OrganizationPermission; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.permission.template.PermissionTemplateGroupDto; import org.sonar.db.user.GroupDto; -import org.sonar.server.organization.DefaultOrganizationProvider; -import org.sonar.server.organization.TestDefaultOrganizationProvider; +import org.sonar.server.usergroups.DefaultGroupFinder; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; +import static org.sonar.server.property.InternalProperties.DEFAULT_PROJECT_TEMPLATE; public class RegisterPermissionTemplatesTest { - private static final String DEFAULT_TEMPLATE_UUID = "default_template"; @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -57,62 +51,13 @@ public class RegisterPermissionTemplatesTest { @Rule public ExpectedException expectedException = ExpectedException.none(); - private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); - private ResourceTypes resourceTypes = mock(ResourceTypes.class); - private RegisterPermissionTemplates underTest = new RegisterPermissionTemplates(db.getDbClient(), defaultOrganizationProvider); + private RegisterPermissionTemplates underTest = new RegisterPermissionTemplates(db.getDbClient(), UuidFactoryFast.getInstance(), System2.INSTANCE, new DefaultGroupFinder(db.getDbClient())); @Test - public void fail_with_ISE_if_default_template_must_be_created_and_no_default_group_is_defined() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default group is not defined"); - - underTest.start(); - } - - @Test - public void fail_with_ISE_if_default_template_must_be_created_and_default_group_does_not_exist() { - setDefaultGroup(new GroupDto().setUuid("22")); - - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default group with id 22 doesn't exist"); - - underTest.start(); - } - - @Test - public void insert_default_permission_template_if_fresh_install_without_governance() { - GroupDto defaultGroup = createAndSetDefaultGroup(); - db.users().insertGroup(DefaultGroups.ADMINISTRATORS); - - when(resourceTypes.isQualifierPresent(eq(Qualifiers.APP))).thenReturn(false); - when(resourceTypes.isQualifierPresent(eq(Qualifiers.VIEW))).thenReturn(false); - underTest.start(); - - PermissionTemplateDto defaultTemplate = selectTemplate(); - assertThat(defaultTemplate.getName()).isEqualTo("Default template"); - - List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate); - assertThat(groupPermissions).hasSize(7); - expectGroupPermission(groupPermissions, UserRole.ADMIN, DefaultGroups.ADMINISTRATORS); - expectGroupPermission(groupPermissions, OrganizationPermission.APPLICATION_CREATOR.getKey(), DefaultGroups.ADMINISTRATORS); - expectGroupPermission(groupPermissions, OrganizationPermission.PORTFOLIO_CREATOR.getKey(), DefaultGroups.ADMINISTRATORS); - expectGroupPermission(groupPermissions, UserRole.CODEVIEWER, defaultGroup.getName()); - expectGroupPermission(groupPermissions, UserRole.USER, defaultGroup.getName()); - expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, defaultGroup.getName()); - expectGroupPermission(groupPermissions, UserRole.SECURITYHOTSPOT_ADMIN, defaultGroup.getName()); - - verifyDefaultTemplates(); - - assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); - } - - @Test - public void insert_default_permission_template_if_fresh_install_with_governance() { - GroupDto defaultGroup = createAndSetDefaultGroup(); + public void insert_default_permission_template_if_fresh_install() { + GroupDto defaultGroup = db.users().insertDefaultGroup(); db.users().insertGroup(DefaultGroups.ADMINISTRATORS); - when(resourceTypes.isQualifierPresent(eq(Qualifiers.APP))).thenReturn(true); - when(resourceTypes.isQualifierPresent(eq(Qualifiers.VIEW))).thenReturn(true); underTest.start(); PermissionTemplateDto defaultTemplate = selectTemplate(); @@ -128,14 +73,14 @@ public class RegisterPermissionTemplatesTest { expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, defaultGroup.getName()); expectGroupPermission(groupPermissions, UserRole.SECURITYHOTSPOT_ADMIN, defaultGroup.getName()); - verifyDefaultTemplates(); + verifyDefaultTemplateForProject(defaultTemplate.getUuid()); assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); } @Test public void ignore_administrators_permissions_if_group_does_not_exist() { - GroupDto defaultGroup = createAndSetDefaultGroup(); + GroupDto defaultGroup = db.users().insertDefaultGroup(); underTest.start(); @@ -149,33 +94,25 @@ public class RegisterPermissionTemplatesTest { expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, defaultGroup.getName()); expectGroupPermission(groupPermissions, UserRole.SECURITYHOTSPOT_ADMIN, defaultGroup.getName()); - verifyDefaultTemplates(); + verifyDefaultTemplateForProject(defaultTemplate.getUuid()); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Cannot setup default permission for group: sonar-administrators"); } @Test - public void do_not_create_default_template_if_already_exists_but_register_when_it_is_not() { - db.permissionTemplates().insertTemplate(newPermissionTemplateDto().setUuid(DEFAULT_TEMPLATE_UUID)); - - underTest.start(); - - verifyDefaultTemplates(); - } - - @Test - public void do_not_fail_if_default_template_exists_and_is_registered() { - PermissionTemplateDto projectTemplate = db.permissionTemplates().insertTemplate(newPermissionTemplateDto() - .setUuid(DEFAULT_TEMPLATE_UUID)); - db.organizations().setDefaultTemplates(projectTemplate, null, null); + public void do_not_fail_if_default_template_exists() { + db.users().insertDefaultGroup(); + PermissionTemplateDto projectTemplate = db.permissionTemplates().insertTemplate(newPermissionTemplateDto()); + db.getDbClient().internalPropertiesDao().save(db.getSession(), DEFAULT_PROJECT_TEMPLATE, projectTemplate.getUuid()); + db.commit(); underTest.start(); - verifyDefaultTemplates(); + verifyDefaultTemplateForProject(projectTemplate.getUuid()); } private PermissionTemplateDto selectTemplate() { - return db.getDbClient().permissionTemplateDao().selectByUuid(db.getSession(), DEFAULT_TEMPLATE_UUID); + return db.getDbClient().permissionTemplateDao().selectByName(db.getSession(), "Default template"); } private List<PermissionTemplateGroupDto> selectGroupPermissions(PermissionTemplateDto template) { @@ -189,21 +126,10 @@ public class RegisterPermissionTemplatesTest { .isTrue(); } - private void verifyDefaultTemplates() { - Optional<DefaultTemplates> defaultTemplates = db.getDbClient().organizationDao().getDefaultTemplates(db.getSession(), db.getDefaultOrganization().getUuid()); - assertThat(defaultTemplates) - .isPresent(); - assertThat(defaultTemplates.get().getProjectUuid()).isEqualTo(DEFAULT_TEMPLATE_UUID); + private void verifyDefaultTemplateForProject(String expectedDefaultTemplateForProjectUuid) { + Optional<String> defaultPermissionTemplateForProject = db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), DEFAULT_PROJECT_TEMPLATE); + assertThat(defaultPermissionTemplateForProject).isPresent(); + assertThat(defaultPermissionTemplateForProject).contains(expectedDefaultTemplateForProjectUuid); } - private void setDefaultGroup(GroupDto defaultGroup) { - db.getDbClient().organizationDao().setDefaultGroupUuid(db.getSession(), db.getDefaultOrganization().getUuid(), defaultGroup); - db.commit(); - } - - private GroupDto createAndSetDefaultGroup() { - GroupDto res = db.users().insertGroup(); - setDefaultGroup(res); - return res; - } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolver.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolver.java index cb9ac5d0796..1a94569e933 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolver.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolver.java @@ -22,6 +22,7 @@ package org.sonar.server.permission; import java.util.Optional; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; +import org.sonar.db.DbSession; import org.sonar.db.organization.DefaultTemplates; import static java.util.Objects.requireNonNull; @@ -39,7 +40,7 @@ public interface DefaultTemplatesResolver { * when it is non {@code null}, otherwise it is {@link DefaultTemplates#projectUuid}</li> * </ul> */ - ResolvedDefaultTemplates resolve(DefaultTemplates defaultTemplates); + ResolvedDefaultTemplates resolve(DbSession dbSession); @Immutable final class ResolvedDefaultTemplates { diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.java index 0119d306201..2e2217837b6 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.java @@ -22,28 +22,35 @@ package org.sonar.server.permission; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; -import org.sonar.db.organization.DefaultTemplates; - -import static java.util.Optional.ofNullable; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.server.property.InternalProperties; public class DefaultTemplatesResolverImpl implements DefaultTemplatesResolver { + + private final DbClient dbClient; private final ResourceTypes resourceTypes; - public DefaultTemplatesResolverImpl(ResourceTypes resourceTypes) { + public DefaultTemplatesResolverImpl(DbClient dbClient, ResourceTypes resourceTypes) { + this.dbClient = dbClient; this.resourceTypes = resourceTypes; } @Override - public ResolvedDefaultTemplates resolve(DefaultTemplates defaultTemplates) { - String projectDefaultTemplate = defaultTemplates.getProjectUuid(); - - return new ResolvedDefaultTemplates( - projectDefaultTemplate, - isViewsEnabled(resourceTypes) ? ofNullable(defaultTemplates.getApplicationsUuid()).orElse(projectDefaultTemplate) : null, - isViewsEnabled(resourceTypes) ? ofNullable(defaultTemplates.getPortfoliosUuid()).orElse(projectDefaultTemplate) : null); + public ResolvedDefaultTemplates resolve(DbSession dbSession) { + String defaultProjectTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE).orElseThrow(() -> { + throw new IllegalStateException("Default template for project is missing"); + }); + if (!isPortfolioEnabled(resourceTypes)) { + return new ResolvedDefaultTemplates(defaultProjectTemplate, null, null); + } else { + String defaultPortfolioTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE).orElse(defaultProjectTemplate); + String defaultApplicationTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE).orElse(defaultProjectTemplate); + return new ResolvedDefaultTemplates(defaultProjectTemplate, defaultApplicationTemplate, defaultPortfolioTemplate); + } } - private static boolean isViewsEnabled(ResourceTypes resourceTypes) { + private static boolean isPortfolioEnabled(ResourceTypes resourceTypes) { return resourceTypes.getRoots() .stream() .map(ResourceType::getQualifier) diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionTemplateService.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionTemplateService.java index cae41108bed..53667c91195 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionTemplateService.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionTemplateService.java @@ -36,7 +36,6 @@ import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.permission.GroupPermissionDto; import org.sonar.db.permission.UserPermissionDto; import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto; @@ -46,7 +45,6 @@ import org.sonar.db.permission.template.PermissionTemplateUserDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.ProjectIndexer; import org.sonar.server.es.ProjectIndexers; -import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates; import org.sonar.server.user.UserSession; @@ -65,16 +63,14 @@ public class PermissionTemplateService { private final UserSession userSession; private final DefaultTemplatesResolver defaultTemplatesResolver; private final UuidFactory uuidFactory; - private final DefaultOrganizationProvider defaultOrganizationProvider; public PermissionTemplateService(DbClient dbClient, ProjectIndexers projectIndexers, UserSession userSession, - DefaultTemplatesResolver defaultTemplatesResolver, UuidFactory uuidFactory, DefaultOrganizationProvider defaultOrganizationProvider) { + DefaultTemplatesResolver defaultTemplatesResolver, UuidFactory uuidFactory) { this.dbClient = dbClient; this.projectIndexers = projectIndexers; this.userSession = userSession; this.defaultTemplatesResolver = defaultTemplatesResolver; this.uuidFactory = uuidFactory; - this.defaultOrganizationProvider = defaultOrganizationProvider; } public boolean wouldUserHaveScanPermissionWithDefaultTemplate(DbSession dbSession, @Nullable String userUuid, String projectKey) { @@ -191,7 +187,6 @@ public class PermissionTemplateService { */ @CheckForNull private PermissionTemplateDto findTemplate(DbSession dbSession, ComponentDto component) { - String organizationUuid = defaultOrganizationProvider.get().getUuid(); List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(dbSession, null); List<PermissionTemplateDto> matchingTemplates = new ArrayList<>(); for (PermissionTemplateDto permissionTemplateDto : allPermissionTemplates) { @@ -205,12 +200,8 @@ public class PermissionTemplateService { return matchingTemplates.get(0); } - DefaultTemplates defaultTemplates = dbClient.organizationDao().getDefaultTemplates(dbSession, organizationUuid) - .orElseThrow(() -> new IllegalStateException( - format("No Default templates defined for organization with uuid '%s'", organizationUuid))); - String qualifier = component.qualifier(); - ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(defaultTemplates); + ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession); switch (qualifier) { case Qualifiers.PROJECT: return dbClient.permissionTemplateDao().selectByUuid(dbSession, resolvedDefaultTemplates.getProject()); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/CreateTemplateAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/CreateTemplateAction.java index ae66f5e9656..318c7171cf7 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/CreateTemplateAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/CreateTemplateAction.java @@ -30,7 +30,6 @@ import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.PermissionsWsAction; import org.sonar.server.permission.ws.WsParameters; @@ -53,13 +52,11 @@ public class CreateTemplateAction implements PermissionsWsAction { private final DbClient dbClient; private final UserSession userSession; private final System2 system; - private final DefaultOrganizationProvider defaultOrganizationProvider; - public CreateTemplateAction(DbClient dbClient, UserSession userSession, System2 system, DefaultOrganizationProvider defaultOrganizationProvider) { + public CreateTemplateAction(DbClient dbClient, UserSession userSession, System2 system) { this.dbClient = dbClient; this.userSession = userSession; this.system = system; - this.defaultOrganizationProvider = defaultOrganizationProvider; } private static CreateTemplateRequest toCreateTemplateWsRequest(Request request) { diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/DeleteTemplateAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/DeleteTemplateAction.java index 121ab4ee7b8..f66429b6f1a 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/DeleteTemplateAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/DeleteTemplateAction.java @@ -26,9 +26,7 @@ import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates; import org.sonar.server.permission.ws.PermissionWsSupport; @@ -37,7 +35,6 @@ import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.user.UserSession; import static org.sonar.server.exceptions.BadRequestException.checkRequest; -import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin; import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; @@ -48,15 +45,13 @@ public class DeleteTemplateAction implements PermissionsWsAction { private final UserSession userSession; private final PermissionWsSupport wsSupport; private final DefaultTemplatesResolver defaultTemplatesResolver; - private final DefaultOrganizationProvider defaultOrganizationProvider; public DeleteTemplateAction(DbClient dbClient, UserSession userSession, PermissionWsSupport support, - DefaultTemplatesResolver defaultTemplatesResolver, DefaultOrganizationProvider defaultOrganizationProvider) { + DefaultTemplatesResolver defaultTemplatesResolver) { this.dbClient = dbClient; this.userSession = userSession; this.wsSupport = support; this.defaultTemplatesResolver = defaultTemplatesResolver; - this.defaultOrganizationProvider = defaultOrganizationProvider; } private static DeleteTemplateRequest toDeleteTemplateWsRequest(Request request) { @@ -89,43 +84,23 @@ public class DeleteTemplateAction implements PermissionsWsAction { PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName())); checkGlobalAdmin(userSession); - DefaultTemplates defaultTemplates = retrieveDefaultTemplates(dbSession); - - checkTemplateUuidIsNotDefault(template, defaultTemplates); + checkTemplateUuidIsNotDefault(dbSession, template); dbClient.permissionTemplateDao().deleteByUuid(dbSession, template.getUuid()); - updateViewDefaultTemplateWhenGovernanceIsNotInstalled(dbSession, template, defaultTemplates); - dbSession.commit(); } } - /** - * The default template for view can be removed when Governance is not installed. To avoid keeping a reference - * to a non existing template, we update the default templates. - */ - private void updateViewDefaultTemplateWhenGovernanceIsNotInstalled(DbSession dbSession, PermissionTemplateDto template, DefaultTemplates defaultTemplates) { - String viewDefaultTemplateUuid = defaultTemplates.getApplicationsUuid(); - if (viewDefaultTemplateUuid != null && viewDefaultTemplateUuid.equals(template.getUuid())) { - defaultTemplates.setApplicationsUuid(null); - dbClient.organizationDao().setDefaultTemplates(dbSession, defaultOrganizationProvider.get().getUuid(), defaultTemplates); - } - } - - private DefaultTemplates retrieveDefaultTemplates(DbSession dbSession) { - return checkFoundWithOptional(dbClient.organizationDao().getDefaultTemplates(dbSession, defaultOrganizationProvider.get().getUuid()), "Can't find default templates"); - } - - private void checkTemplateUuidIsNotDefault(PermissionTemplateDto template, DefaultTemplates defaultTemplates) { - ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(defaultTemplates); + private void checkTemplateUuidIsNotDefault(DbSession dbSession, PermissionTemplateDto template) { + ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession); checkRequest(!resolvedDefaultTemplates.getProject().equals(template.getUuid()), "It is not possible to delete the default permission template for projects"); resolvedDefaultTemplates.getApplication() - .ifPresent(viewDefaultTemplateUuid -> checkRequest( - !viewDefaultTemplateUuid.equals(template.getUuid()), + .ifPresent(defaultApplicationTemplate -> checkRequest( + !defaultApplicationTemplate.equals(template.getUuid()), "It is not possible to delete the default permission template for applications")); resolvedDefaultTemplates.getPortfolio() - .ifPresent(viewDefaultTemplateUuid -> checkRequest( - !viewDefaultTemplateUuid.equals(template.getUuid()), + .ifPresent(defaultPortfolioTemplate -> checkRequest( + !defaultPortfolioTemplate.equals(template.getUuid()), "It is not possible to delete the default permission template for portfolios")); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesAction.java index 1f056a7849d..20e9a0a49a8 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesAction.java @@ -34,11 +34,9 @@ import org.sonar.api.server.ws.WebService.Param; import org.sonar.core.i18n.I18n; import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.permission.template.CountByTemplateAndPermissionDto; import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto; import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates; import org.sonar.server.permission.PermissionService; @@ -52,7 +50,6 @@ import org.sonarqube.ws.Permissions.SearchTemplatesWsResponse.TemplateIdQualifie import static java.util.Optional.ofNullable; import static org.sonar.api.utils.DateUtils.formatDateTime; -import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin; import static org.sonar.server.permission.ws.template.SearchTemplatesData.builder; import static org.sonar.server.ws.WsUtils.writeProtobuf; @@ -66,21 +63,19 @@ public class SearchTemplatesAction implements PermissionsWsAction { private final I18n i18n; private final DefaultTemplatesResolver defaultTemplatesResolver; private final PermissionService permissionService; - private final DefaultOrganizationProvider defaultOrganizationProvider; public SearchTemplatesAction(DbClient dbClient, UserSession userSession, I18n i18n, DefaultTemplatesResolver defaultTemplatesResolver, - PermissionService permissionService, DefaultOrganizationProvider defaultOrganizationProvider) { + PermissionService permissionService) { this.dbClient = dbClient; this.userSession = userSession; this.i18n = i18n; this.defaultTemplatesResolver = defaultTemplatesResolver; this.permissionService = permissionService; - this.defaultOrganizationProvider = defaultOrganizationProvider; } @Override public void define(WebService.NewController context) { - WebService.NewAction action = context.createAction("search_templates") + context.createAction("search_templates") .setDescription("List permission templates.<br />" + "Requires the following permission: 'Administer System'.") .setResponseExample(getClass().getResource("search_templates-example.json")) @@ -184,10 +179,7 @@ public class SearchTemplatesAction implements PermissionsWsAction { List<PermissionTemplateDto> templates = searchTemplates(dbSession, request); List<String> templateUuids = templates.stream().map(PermissionTemplateDto::getUuid).collect(Collectors.toList()); - DefaultTemplates defaultTemplates = checkFoundWithOptional( - dbClient.organizationDao().getDefaultTemplates(dbSession, defaultOrganizationProvider.get().getUuid()), "No Default templates"); - ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(defaultTemplates); - + ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession); data.templates(templates) .defaultTemplates(resolvedDefaultTemplates) .userCountByTemplateUuidAndPermission(userCountByTemplateUuidAndPermission(dbSession, templateUuids)) diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SetDefaultTemplateAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SetDefaultTemplateAction.java index 35407297c16..74935aae9e5 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SetDefaultTemplateAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SetDefaultTemplateAction.java @@ -29,17 +29,15 @@ import org.sonar.api.server.ws.WebService; import org.sonar.core.i18n.I18n; import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.db.organization.DefaultTemplates; -import org.sonar.db.organization.OrganizationDao; import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.PermissionWsSupport; import org.sonar.server.permission.ws.PermissionsWsAction; import org.sonar.server.permission.ws.WsParameters; +import org.sonar.server.property.InternalProperties; import org.sonar.server.user.UserSession; -import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; +import static java.lang.String.format; import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin; import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef; import static org.sonar.server.ws.WsParameterBuilder.createDefaultTemplateQualifierParameter; @@ -54,21 +52,19 @@ public class SetDefaultTemplateAction implements PermissionsWsAction { private final ResourceTypes resourceTypes; private final UserSession userSession; private final I18n i18n; - private final DefaultOrganizationProvider defaultOrganizationProvider; public SetDefaultTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, ResourceTypes resourceTypes, - UserSession userSession, I18n i18n, DefaultOrganizationProvider defaultOrganizationProvider) { + UserSession userSession, I18n i18n) { this.dbClient = dbClient; this.wsSupport = wsSupport; this.resourceTypes = resourceTypes; this.userSession = userSession; this.i18n = i18n; - this.defaultOrganizationProvider = defaultOrganizationProvider; } private static SetDefaultTemplateRequest toSetDefaultTemplateWsRequest(Request request) { return new SetDefaultTemplateRequest() - .setQualifier(request.param(PARAM_QUALIFIER)) + .setQualifier(request.mandatoryParam(PARAM_QUALIFIER)) .setTemplateId(request.param(PARAM_TEMPLATE_ID)) .setTemplateName(request.param(PARAM_TEMPLATE_NAME)); } @@ -109,33 +105,31 @@ public class SetDefaultTemplateAction implements PermissionsWsAction { } private void setDefaultTemplateUuid(DbSession dbSession, PermissionTemplateDto permissionTemplateDto, String qualifier) { - OrganizationDao organizationDao = dbClient.organizationDao(); - - DefaultTemplates defaultTemplates = checkFoundWithOptional( - organizationDao.getDefaultTemplates(dbSession, defaultOrganizationProvider.get().getUuid()), "No Default templates"); - - if (Qualifiers.PROJECT.equals(qualifier)) { - defaultTemplates.setProjectUuid(permissionTemplateDto.getUuid()); - } else if (Qualifiers.VIEW.equals(qualifier)) { - defaultTemplates.setPortfoliosUuid(permissionTemplateDto.getUuid()); - } else if (Qualifiers.APP.equals(qualifier)) { - defaultTemplates.setApplicationsUuid(permissionTemplateDto.getUuid()); + switch (qualifier) { + case Qualifiers.PROJECT: + dbClient.internalPropertiesDao().save(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE, permissionTemplateDto.getUuid()); + break; + case Qualifiers.VIEW: + dbClient.internalPropertiesDao().save(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE, permissionTemplateDto.getUuid()); + break; + case Qualifiers.APP: + dbClient.internalPropertiesDao().save(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE, permissionTemplateDto.getUuid()); + break; + default: + throw new IllegalStateException(format("Unsupported qualifier : %s", qualifier)); } - organizationDao.setDefaultTemplates(dbSession, defaultOrganizationProvider.get().getUuid(), defaultTemplates); } private static class SetDefaultTemplateRequest { private String qualifier; private String templateId; - private String organization; private String templateName; - @CheckForNull public String getQualifier() { return qualifier; } - public SetDefaultTemplateRequest setQualifier(@Nullable String qualifier) { + public SetDefaultTemplateRequest setQualifier(String qualifier) { this.qualifier = qualifier; return this; } @@ -151,16 +145,6 @@ public class SetDefaultTemplateAction implements PermissionsWsAction { } @CheckForNull - public String getOrganization() { - return organization; - } - - public SetDefaultTemplateRequest setOrganization(@Nullable String s) { - this.organization = s; - return this; - } - - @CheckForNull public String getTemplateName() { return templateName; } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverImplTest.java index cf4a8ca69e9..bd33a2426c3 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverImplTest.java @@ -19,59 +19,74 @@ */ package org.sonar.server.permission; -import java.util.stream.Stream; +import org.junit.Rule; import org.junit.Test; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.ResourceType; -import org.sonar.api.resources.ResourceTypeTree; -import org.sonar.api.resources.ResourceTypes; -import org.sonar.db.organization.DefaultTemplates; +import org.sonar.api.utils.System2; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ResourceTypesRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.sonar.api.resources.Qualifiers.APP; +import static org.sonar.api.resources.Qualifiers.PROJECT; +import static org.sonar.api.resources.Qualifiers.VIEW; public class DefaultTemplatesResolverImplTest { - private static final ResourceTypes RESOURCE_TYPES_WITHOUT_VIEWS = new ResourceTypes(new ResourceTypeTree[] { - ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.PROJECT).build()).build() - }); - private static final ResourceTypes RESOURCE_TYPES_WITH_VIEWS = new ResourceTypes(new ResourceTypeTree[] { - ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.PROJECT).build()).build(), - ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.VIEW).build()).build() - }); - private DefaultTemplatesResolverImpl underTestWithoutViews = new DefaultTemplatesResolverImpl(RESOURCE_TYPES_WITHOUT_VIEWS); - private DefaultTemplatesResolverImpl underTestWithViews = new DefaultTemplatesResolverImpl(RESOURCE_TYPES_WITH_VIEWS); + @Rule + public DbTester db = DbTester.create(System2.INSTANCE); + + private ResourceTypesRule resourceTypesWithPortfoliosInstalled = new ResourceTypesRule().setRootQualifiers(PROJECT, APP, VIEW); + private ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT); + + private DefaultTemplatesResolverImpl underTestWithPortfoliosInstalled = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypesWithPortfoliosInstalled); + private DefaultTemplatesResolverImpl underTest = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypes); @Test - public void project_is_project_of_DefaultTemplates_no_matter_if_views_is_installed() { - Stream.of( - new DefaultTemplates().setProjectUuid("foo").setApplicationsUuid(null), - new DefaultTemplates().setProjectUuid("foo").setApplicationsUuid("bar")).forEach( - defaultTemplates -> { - assertThat(underTestWithoutViews.resolve(defaultTemplates).getProject()).isEqualTo("foo"); - assertThat(underTestWithViews.resolve(defaultTemplates).getProject()).isEqualTo("foo"); - }); + public void get_default_templates_when_portfolio_not_installed() { + db.permissionTemplates().setDefaultTemplates("prj", null, null); + + assertThat(underTest.resolve(db.getSession()).getProject()).contains("prj"); + assertThat(underTest.resolve(db.getSession()).getApplication()).isEmpty(); + assertThat(underTest.resolve(db.getSession()).getPortfolio()).isEmpty(); } @Test - public void view_is_empty_no_matter_view_in_DefaultTemplates_if_views_is_not_installed() { - DefaultTemplates defaultTemplatesNoView = new DefaultTemplates().setProjectUuid("foo").setApplicationsUuid(null); - DefaultTemplates defaultTemplatesView = new DefaultTemplates().setProjectUuid("foo").setApplicationsUuid("bar"); + public void get_default_templates_always_return_project_template_even_when_all_templates_are_defined_but_portfolio_not_installed() { + db.permissionTemplates().setDefaultTemplates("prj", "app", "port"); - assertThat(underTestWithoutViews.resolve(defaultTemplatesNoView).getApplication()).isEmpty(); - assertThat(underTestWithoutViews.resolve(defaultTemplatesView).getApplication()).isEmpty(); + assertThat(underTest.resolve(db.getSession()).getProject()).contains("prj"); + assertThat(underTest.resolve(db.getSession()).getApplication()).isEmpty(); + assertThat(underTest.resolve(db.getSession()).getPortfolio()).isEmpty(); } @Test - public void view_is_project_of_DefaultTemplates_if_view_in_DefaultTemplates_is_null_and_views_is_installed() { - DefaultTemplates defaultTemplates = new DefaultTemplates().setProjectUuid("foo").setApplicationsUuid(null); + public void get_default_templates_always_return_project_template_when_only_project_template_and_portfolio_is_installed_() { + db.permissionTemplates().setDefaultTemplates("prj", null, null); - assertThat(underTestWithViews.resolve(defaultTemplates).getApplication()).contains("foo"); + assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getProject()).contains("prj"); + assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getApplication()).contains("prj"); + assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getPortfolio()).contains("prj"); } @Test - public void view_is_view_of_DefaultTemplates_if_view_in_DefaultTemplates_is_not_null_and_views_is_installed() { - DefaultTemplates defaultTemplates = new DefaultTemplates().setProjectUuid("foo").setApplicationsUuid("bar"); + public void get_default_templates_for_all_components_when_portfolio_is_installed() { + db.permissionTemplates().setDefaultTemplates("prj", "app", "port"); - assertThat(underTestWithViews.resolve(defaultTemplates).getApplication()).contains("bar"); + assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getProject()).contains("prj"); + assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getApplication()).contains("app"); + assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getPortfolio()).contains("port"); } + + @Test + public void fail_when_default_template_for_project_is_missing() { + DbSession session = db.getSession(); + assertThatThrownBy(() -> { + underTestWithPortfoliosInstalled.resolve(session); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Default template for project is missing"); + } + } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverRule.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverRule.java deleted file mode 100644 index ca277a9ee50..00000000000 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/DefaultTemplatesResolverRule.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2020 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.permission; - -import org.junit.rules.ExternalResource; -import org.sonar.api.resources.ResourceType; -import org.sonar.api.resources.ResourceTypeTree; -import org.sonar.api.resources.ResourceTypes; -import org.sonar.db.organization.DefaultTemplates; - -import static org.sonar.api.resources.Qualifiers.APP; -import static org.sonar.api.resources.Qualifiers.PROJECT; -import static org.sonar.api.resources.Qualifiers.VIEW; - -public class DefaultTemplatesResolverRule extends ExternalResource implements DefaultTemplatesResolver { - private static final DefaultTemplatesResolver WITH_GOV = new DefaultTemplatesResolverImpl( - new ResourceTypes(new ResourceTypeTree[] { - ResourceTypeTree.builder() - .addType(ResourceType.builder(PROJECT).build()) - .build(), - ResourceTypeTree.builder() - .addType(ResourceType.builder(VIEW).build()) - .build(), - ResourceTypeTree.builder() - .addType(ResourceType.builder(APP).build()) - .build() - })); - private static final DefaultTemplatesResolver WITHOUT_GOV = new DefaultTemplatesResolverImpl( - new ResourceTypes(new ResourceTypeTree[] {ResourceTypeTree.builder() - .addType(ResourceType.builder(PROJECT).build()) - .build()})); - - private final boolean governanceInitiallyInstalled; - private boolean governanceInstalled; - - private DefaultTemplatesResolverRule(boolean governanceInitiallyInstalled) { - this.governanceInitiallyInstalled = governanceInitiallyInstalled; - this.governanceInstalled = governanceInitiallyInstalled; - } - - @Override - protected void before() { - this.governanceInstalled = governanceInitiallyInstalled; - } - - public void installGovernance() { - this.governanceInstalled = true; - } - - public void uninstallGovernance() { - this.governanceInstalled = false; - } - - public static DefaultTemplatesResolverRule withoutGovernance() { - return new DefaultTemplatesResolverRule(false); - } - - public static DefaultTemplatesResolverRule withGovernance() { - return new DefaultTemplatesResolverRule(true); - } - - @Override - public DefaultTemplatesResolverImpl.ResolvedDefaultTemplates resolve(DefaultTemplates defaultTemplates) { - if (governanceInstalled) { - return WITH_GOV.resolve(defaultTemplates); - } - return WITHOUT_GOV.resolve(defaultTemplates); - } -} diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java index 9887279c2dd..a99fd41812b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java @@ -24,9 +24,6 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.ResourceTypes; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; @@ -39,11 +36,13 @@ import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.ProjectIndexers; import org.sonar.server.es.TestProjectIndexers; -import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.tester.UserSessionRule; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.api.resources.Qualifiers.APP; +import static org.sonar.api.resources.Qualifiers.PROJECT; +import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; import static org.sonar.db.permission.OrganizationPermission.PROVISION_PROJECTS; import static org.sonar.db.permission.OrganizationPermission.SCAN; @@ -53,20 +52,18 @@ public class PermissionTemplateServiceTest { @Rule public ExpectedException throwable = ExpectedException.none(); @Rule - public DbTester dbTester = DbTester.create(new AlwaysIncreasingSystem2()); - @Rule - public DefaultTemplatesResolverRule defaultTemplatesResolver = DefaultTemplatesResolverRule.withGovernance(); - - private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); - private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); + public DbTester dbTester = DbTester.create(); + private ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers(PROJECT, VIEW, APP); + private DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(dbTester.getDbClient(), resourceTypesRule); + private PermissionService permissionService = new PermissionServiceImpl(resourceTypesRule); private UserSessionRule userSession = UserSessionRule.standalone(); private PermissionTemplateDbTester templateDb = dbTester.permissionTemplates(); private DbSession session = dbTester.getSession(); private ProjectIndexers projectIndexers = new TestProjectIndexers(); private PermissionTemplateService underTest = new PermissionTemplateService(dbTester.getDbClient(), projectIndexers, userSession, defaultTemplatesResolver, - new SequenceUuidFactory(), TestDefaultOrganizationProvider.from(dbTester)); + new SequenceUuidFactory()); @Test public void apply_does_not_insert_permission_to_group_AnyOne_when_applying_template_on_private_project() { @@ -85,7 +82,7 @@ public class PermissionTemplateServiceTest { UserDto creator = dbTester.users().insertUser(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, privateProject, creator.getUuid()); @@ -113,7 +110,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, publicProject, null); @@ -144,7 +141,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, perm)); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, privateProject, null); @@ -175,7 +172,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, perm)); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, publicProject, null); @@ -206,7 +203,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, perm)); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, publicProject, null); @@ -237,7 +234,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, perm)); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, privateProject, null); @@ -253,7 +250,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, publicProject, user.getUuid()); @@ -269,7 +266,7 @@ public class PermissionTemplateServiceTest { permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, "p1"); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, privateProject, user.getUuid()); @@ -279,16 +276,16 @@ public class PermissionTemplateServiceTest { @Test public void apply_template_on_view() { - ComponentDto view = dbTester.components().insertView(); + ComponentDto portfolio = dbTester.components().insertPrivatePortfolio(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); - underTest.applyDefault(session, view, null); + underTest.applyDefault(session, portfolio, null); - assertThat(selectProjectPermissionsOfGroup(group, view)) + assertThat(selectProjectPermissionsOfGroup(group, portfolio)) .containsOnly(ADMINISTER.getKey(), PROVISION_PROJECTS.getKey()); } @@ -300,7 +297,7 @@ public class PermissionTemplateServiceTest { GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(projectPermissionTemplate.getUuid(), appPermissionTemplate.getUuid(), null); + dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, appPermissionTemplate, null); underTest.applyDefault(session, view, null); @@ -316,7 +313,7 @@ public class PermissionTemplateServiceTest { GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(portPermissionTemplate, group, ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(portPermissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(projectPermissionTemplate.getUuid(), null, portPermissionTemplate.getUuid()); + dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, portPermissionTemplate); underTest.applyDefault(session, view, null); @@ -330,7 +327,7 @@ public class PermissionTemplateServiceTest { PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(projectPermissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(projectPermissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, null); underTest.applyDefault(session, view, null); @@ -344,7 +341,7 @@ public class PermissionTemplateServiceTest { GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(permissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefault(session, application, null); @@ -361,7 +358,7 @@ public class PermissionTemplateServiceTest { GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(projectPermissionTemplate.getUuid(), appPermissionTemplate.getUuid(), portPermissionTemplate.getUuid()); + dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, appPermissionTemplate, portPermissionTemplate); underTest.applyDefault(session, application, null); @@ -375,7 +372,7 @@ public class PermissionTemplateServiceTest { PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(projectPermissionTemplate, group, PROVISION_PROJECTS.getKey()); - dbTester.organizations().setDefaultTemplates(projectPermissionTemplate.getUuid(), null, null); + dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, null); underTest.applyDefault(session, application, null); @@ -428,7 +425,7 @@ public class PermissionTemplateServiceTest { UserDto user = dbTester.users().insertUser(); dbTester.users().insertMember(group, user); PermissionTemplateDto template = templateDb.insertTemplate(); - dbTester.organizations().setDefaultTemplates(template, null, null); + dbTester.permissionTemplates().setDefaultTemplates(template, null, null); templateDb.addProjectCreatorToTemplate(template.getUuid(), SCAN.getKey()); templateDb.addUserToTemplate(template.getUuid(), user.getUuid(), UserRole.USER); templateDb.addGroupToTemplate(template.getUuid(), group.getUuid(), UserRole.CODEVIEWER); @@ -443,7 +440,7 @@ public class PermissionTemplateServiceTest { @Test public void would_user_have_scan_permission_with_unknown_default_permission_template() { - dbTester.organizations().setDefaultTemplates("UNKNOWN_TEMPLATE_UUID", null, null); + dbTester.permissionTemplates().setDefaultTemplates("UNKNOWN_TEMPLATE_UUID", null, null); checkWouldUserHaveScanPermission(null, false); } @@ -451,7 +448,7 @@ public class PermissionTemplateServiceTest { @Test public void would_user_have_scan_permission_with_empty_template() { PermissionTemplateDto template = templateDb.insertTemplate(); - dbTester.organizations().setDefaultTemplates(template, null, null); + dbTester.permissionTemplates().setDefaultTemplates(template, null, null); checkWouldUserHaveScanPermission(null, false); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java index 82d22c0dbb8..2002bc7dc19 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java @@ -32,7 +32,6 @@ import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.es.EsTester; import org.sonar.server.es.ProjectIndexersImpl; -import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.permission.GroupPermissionChanger; import org.sonar.server.permission.PermissionUpdater; import org.sonar.server.permission.UserPermissionChanger; @@ -58,7 +57,6 @@ public abstract class BasePermissionWsTest<A extends PermissionsWsAction> { @Rule public ExpectedException expectedException = ExpectedException.none(); - protected TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); protected UserSessionRule userSession = UserSessionRule.standalone(); protected WsActionTester wsTester; diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java index 0db7a368c4b..fe66d54a03a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java @@ -26,7 +26,9 @@ import org.junit.Rule; import org.junit.Test; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; +import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; +import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; @@ -35,12 +37,16 @@ import org.sonar.server.es.TestProjectIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; -import org.sonar.server.permission.DefaultTemplatesResolverRule; +import org.sonar.server.permission.DefaultTemplatesResolver; +import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.permission.ws.BasePermissionWsTest; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.api.resources.Qualifiers.APP; +import static org.sonar.api.resources.Qualifiers.PROJECT; +import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.db.permission.OrganizationPermission.SCAN; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; @@ -50,7 +56,8 @@ import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_T public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateAction> { @Rule - public DefaultTemplatesResolverRule defaultTemplatesResolver = DefaultTemplatesResolverRule.withoutGovernance(); + public DbTester dbTester = DbTester.create(); + private UserDto user1; private UserDto user2; private GroupDto group1; @@ -59,8 +66,10 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA private PermissionTemplateDto template1; private PermissionTemplateDto template2; + private ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers(PROJECT, VIEW, APP); + private DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(dbTester.getDbClient(), resourceTypesRule); private PermissionTemplateService permissionTemplateService = new PermissionTemplateService(db.getDbClient(), - new TestProjectIndexers(), userSession, defaultTemplatesResolver, new SequenceUuidFactory(), defaultOrganizationProvider); + new TestProjectIndexers(), userSession, defaultTemplatesResolver, new SequenceUuidFactory()); @Override protected ApplyTemplateAction buildWsAction() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java index 1c8834300ce..cdd08b990f4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java @@ -30,6 +30,7 @@ import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; +import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; @@ -39,11 +40,15 @@ import org.sonar.server.es.TestProjectIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.l18n.I18nRule; -import org.sonar.server.permission.DefaultTemplatesResolverRule; +import org.sonar.server.permission.DefaultTemplatesResolver; +import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.permission.ws.BasePermissionWsTest; import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.api.resources.Qualifiers.APP; +import static org.sonar.api.resources.Qualifiers.PROJECT; +import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.api.utils.DateUtils.parseDate; import static org.sonar.db.component.ComponentTesting.newApplication; import static org.sonar.db.component.ComponentTesting.newView; @@ -58,9 +63,6 @@ import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBIL public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyTemplateAction> { - @org.junit.Rule - public DefaultTemplatesResolverRule defaultTemplatesResolver = DefaultTemplatesResolverRule.withoutGovernance(); - private UserDto user1; private UserDto user2; private GroupDto group1; @@ -69,10 +71,13 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT private PermissionTemplateDto template2; private ProjectIndexers projectIndexers = new TestProjectIndexers(); + private ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers(PROJECT, VIEW, APP); + private DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypesRule); + @Override protected BulkApplyTemplateAction buildWsAction() { PermissionTemplateService permissionTemplateService = new PermissionTemplateService(db.getDbClient(), - projectIndexers, userSession, defaultTemplatesResolver, new SequenceUuidFactory(), defaultOrganizationProvider); + projectIndexers, userSession, defaultTemplatesResolver, new SequenceUuidFactory()); return new BulkApplyTemplateAction(db.getDbClient(), userSession, permissionTemplateService, newPermissionWsSupport(), new I18nRule(), newRootResourceTypes()); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java index 2ed123bc931..18277a32122 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java @@ -21,8 +21,8 @@ package org.sonar.server.permission.ws.template; import javax.annotation.Nullable; import org.junit.Test; -import org.sonar.api.utils.System2; import org.sonar.api.impl.utils.TestSystem2; +import org.sonar.api.utils.System2; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; @@ -44,7 +44,7 @@ public class CreateTemplateActionTest extends BasePermissionWsTest<CreateTemplat @Override protected CreateTemplateAction buildWsAction() { - return new CreateTemplateAction(db.getDbClient(), userSession, system, defaultOrganizationProvider); + return new CreateTemplateAction(db.getDbClient(), userSession, system); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java index f92d0a53aeb..3758937b908 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java @@ -19,20 +19,17 @@ */ package org.sonar.server.permission.ws.template; -import java.util.Arrays; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; -import org.sonar.api.resources.Qualifiers; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.db.permission.template.PermissionTemplateTesting; import org.sonar.db.user.GroupDto; import org.sonar.db.user.GroupTesting; import org.sonar.db.user.UserDto; @@ -42,8 +39,6 @@ import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; -import org.sonar.server.organization.DefaultOrganizationProvider; -import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.ws.PermissionWsSupport; @@ -55,6 +50,9 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.api.resources.Qualifiers.APP; +import static org.sonar.api.resources.Qualifiers.PROJECT; +import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; @@ -68,88 +66,58 @@ public class DeleteTemplateActionTest { private UserSessionRule userSession = UserSessionRule.standalone(); private DbClient dbClient = db.getDbClient(); - private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); - private final ResourceTypesRule resourceTypesWithViews = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT, Qualifiers.VIEW); + private ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT, APP, VIEW); + private DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(dbClient, resourceTypes); - private DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(resourceTypes); - private DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(resourceTypesWithViews); - - private WsActionTester underTestWithoutViews; - private WsActionTester underTestWithViews; + private WsActionTester underTest; @Before public void setUp() { - DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); GroupWsSupport groupWsSupport = new GroupWsSupport(dbClient, new DefaultGroupFinder(db.getDbClient())); - this.underTestWithoutViews = new WsActionTester(new DeleteTemplateAction(dbClient, userSession, - new PermissionWsSupport(dbClient, new ComponentFinder(dbClient, resourceTypes), groupWsSupport), defaultTemplatesResolver, defaultOrganizationProvider)); - this.underTestWithViews = new WsActionTester(new DeleteTemplateAction(dbClient, userSession, - new PermissionWsSupport(dbClient, new ComponentFinder(dbClient, resourceTypes), groupWsSupport), defaultTemplatesResolverWithViews, defaultOrganizationProvider)); + this.underTest = new WsActionTester(new DeleteTemplateAction(dbClient, userSession, + new PermissionWsSupport(dbClient, new ComponentFinder(dbClient, resourceTypes), groupWsSupport), defaultTemplatesResolver)); } @Test - public void delete_template_in_db() throws Exception { - runOnAllUnderTests((underTest) -> { - PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); - db.organizations().setDefaultTemplates( - db.permissionTemplates().insertTemplate(), - null, db.permissionTemplates().insertTemplate() - ); - loginAsAdmin(); - - TestResponse result = newRequestByUuid(underTest, template.getUuid()); - - assertThat(result.getInput()).isEmpty(); - assertTemplateDoesNotExist(template); - }); - } + public void delete_template_in_db() { + PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); + PermissionTemplateDto projectPermissionTemplate = db.permissionTemplates().insertTemplate(); + PermissionTemplateDto portfolioPermissionTemplate = db.permissionTemplates().insertTemplate(); + db.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, portfolioPermissionTemplate); + loginAsAdmin(); - @Test - public void delete_template_by_name_case_insensitive() throws Exception { - runOnAllUnderTests((underTest) -> { - db.organizations().setDefaultTemplates( - db.permissionTemplates().insertTemplate(), - db.permissionTemplates().insertTemplate(), db.permissionTemplates().insertTemplate() - ); - PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); - loginAsAdmin(); - newRequestByName(underTest, template); - - assertTemplateDoesNotExist(template); - }); + TestResponse result = newRequestByUuid(underTest, template.getUuid()); + + assertThat(result.getInput()).isEmpty(); + assertTemplateDoesNotExist(template); } @Test - public void fail_if_uuid_is_not_known_without_views() { - userSession.logIn(); + public void delete_template_by_name_case_insensitive() { + db.permissionTemplates().setDefaultTemplates( + db.permissionTemplates().insertTemplate().getUuid(), + db.permissionTemplates().insertTemplate().getUuid(), db.permissionTemplates().insertTemplate().getUuid()); + PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); + loginAsAdmin(); - expectedException.expect(NotFoundException.class); + newRequestByName(underTest, template); - newRequestByUuid(underTestWithoutViews, "unknown-template-uuid"); + assertTemplateDoesNotExist(template); } @Test - public void fail_if_uuid_is_not_known_with_views() { + public void fail_if_uuid_is_not_known() { userSession.logIn(); expectedException.expect(NotFoundException.class); - newRequestByUuid(underTestWithViews, "unknown-template-uuid"); + newRequestByUuid(underTest, "unknown-template-uuid"); } @Test - public void fail_to_delete_by_uuid_if_template_is_default_template_for_project_without_views() { - fail_to_delete_by_uuid_if_template_is_default_template_for_project(this.underTestWithoutViews); - } - - @Test - public void fail_to_delete_by_uuid_if_template_is_default_template_for_project_with_views() { - fail_to_delete_by_uuid_if_template_is_default_template_for_project(this.underTestWithViews); - } - - private void fail_to_delete_by_uuid_if_template_is_default_template_for_project(WsActionTester underTest) { + public void fail_to_delete_by_uuid_if_template_is_default_template() { PermissionTemplateDto projectTemplate = insertTemplateAndAssociatedPermissions(); - db.organizations().setDefaultTemplates(projectTemplate, + db.permissionTemplates().setDefaultTemplates(projectTemplate, null, db.permissionTemplates().insertTemplate()); loginAsAdmin(); @@ -160,18 +128,9 @@ public class DeleteTemplateActionTest { } @Test - public void fail_to_delete_by_name_if_template_is_default_template_for_project_without_views() { - fail_to_delete_by_name_if_template_is_default_template_for_project(this.underTestWithoutViews); - } - - @Test - public void fail_to_delete_by_name_if_template_is_default_template_for_project_with_views() { - fail_to_delete_by_name_if_template_is_default_template_for_project(this.underTestWithViews); - } - - private void fail_to_delete_by_name_if_template_is_default_template_for_project(WsActionTester underTest) { + public void fail_to_delete_by_name_if_template_is_default_template_for_project() { PermissionTemplateDto projectTemplate = insertTemplateAndAssociatedPermissions(); - db.organizations().setDefaultTemplates(projectTemplate, null, db.permissionTemplates().insertTemplate()); + db.permissionTemplates().setDefaultTemplates(projectTemplate, null, db.permissionTemplates().insertTemplate()); loginAsAdmin(); expectedException.expect(BadRequestException.class); @@ -181,184 +140,87 @@ public class DeleteTemplateActionTest { } @Test - public void fail_to_delete_by_uuid_if_template_is_default_template_for_portfolios_with_views() { + public void fail_to_delete_by_uuid_if_template_is_default_template_for_portfolios() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, template); + db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, template); loginAsAdmin(); expectedException.expect(BadRequestException.class); expectedException.expectMessage("It is not possible to delete the default permission template for portfolios"); - newRequestByUuid(this.underTestWithViews, template.getUuid()); + newRequestByUuid(this.underTest, template.getUuid()); } @Test - public void fail_to_delete_by_uuid_if_template_is_default_template_for_applications_with_views() { + public void fail_to_delete_by_uuid_if_template_is_default_template_for_applications() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), template, null); + db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), template, null); loginAsAdmin(); expectedException.expect(BadRequestException.class); expectedException.expectMessage("It is not possible to delete the default permission template for applications"); - newRequestByUuid(this.underTestWithViews, template.getUuid()); - } - - @Test - public void default_template_for_views_can_be_deleted_by_uuid_if_views_is_not_installed_and_default_template_for_views_is_reset() { - PermissionTemplateDto projectTemplate = db.permissionTemplates().insertTemplate(); - PermissionTemplateDto viewTemplate = insertTemplateAndAssociatedPermissions(); - db.organizations().setDefaultTemplates(projectTemplate, null, viewTemplate); - loginAsAdmin(); - - newRequestByUuid(this.underTestWithoutViews, viewTemplate.getUuid()); - - assertTemplateDoesNotExist(viewTemplate); - - assertThat(db.getDbClient().organizationDao().getDefaultTemplates(db.getSession(), db.getDefaultOrganization().getUuid()) - .get().getApplicationsUuid()) - .isNull(); - } - - @Test - public void fail_to_delete_by_uuid_if_not_logged_in_without_views() { - expectedException.expect(UnauthorizedException.class); - - newRequestByUuid(underTestWithoutViews, "uuid"); + newRequestByUuid(this.underTest, template.getUuid()); } @Test - public void fail_to_delete_by_uuid_if_not_logged_in_with_views() { + public void fail_to_delete_by_uuid_if_not_logged_in() { expectedException.expect(UnauthorizedException.class); - newRequestByUuid(underTestWithViews, "uuid"); + newRequestByUuid(underTest, "uuid"); } @Test - public void fail_to_delete_by_name_if_not_logged_in_without_views() { + public void fail_to_delete_by_name_if_not_logged_in() { expectedException.expect(UnauthorizedException.class); - newRequestByName(underTestWithoutViews, "name"); - } - - @Test - public void fail_to_delete_by_name_if_not_logged_in_with_views() { - expectedException.expect(UnauthorizedException.class); - newRequestByName(underTestWithViews, "name"); - } - - @Test - public void fail_to_delete_by_uuid_if_not_admin_without_views() { - PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); - userSession.logIn(); - - expectedException.expect(ForbiddenException.class); - - newRequestByUuid(underTestWithoutViews, template.getUuid()); + newRequestByName(underTest, "name"); } @Test - public void fail_to_delete_by_uuid_if_not_admin_with_views() { + public void fail_to_delete_by_uuid_if_not_admin() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); userSession.logIn(); expectedException.expect(ForbiddenException.class); - newRequestByUuid(underTestWithViews, template.getUuid()); + newRequestByUuid(underTest, template.getUuid()); } @Test - public void fail_to_delete_by_name_if_not_admin_without_views() { + public void fail_to_delete_by_name_if_not_admin() { PermissionTemplateDto template = db.permissionTemplates().insertTemplate(); userSession.logIn(); expectedException.expect(ForbiddenException.class); - newRequestByName(underTestWithoutViews, template.getName()); + newRequestByName(underTest, template.getName()); } @Test - public void fail_to_delete_by_name_if_not_admin_with_views() { - PermissionTemplateDto template = db.permissionTemplates().insertTemplate(PermissionTemplateTesting.newPermissionTemplateDto() - .setName("the name")); - userSession.logIn(); - - expectedException.expect(ForbiddenException.class); - - newRequestByName(underTestWithViews, template); - } - - @Test - public void fail_if_neither_uuid_nor_name_is_provided_without_views() { + public void fail_if_neither_uuid_nor_name_is_provided() { userSession.logIn(); expectedException.expect(BadRequestException.class); - newRequestByUuid(underTestWithoutViews, null); + newRequestByUuid(underTest, null); } @Test - public void fail_if_neither_uuid_nor_name_is_provided_with_views() { + public void fail_if_both_uuid_and_name_are_provided() { userSession.logIn(); expectedException.expect(BadRequestException.class); - newRequestByUuid(underTestWithViews, null); - } - - @Test - public void fail_if_both_uuid_and_name_are_provided_without_views() { - userSession.logIn(); - - expectedException.expect(BadRequestException.class); - - underTestWithoutViews.newRequest().setMethod("POST") - .setParam(PARAM_TEMPLATE_ID, "uuid") - .setParam(PARAM_TEMPLATE_NAME, "name") - .execute(); - } - - @Test - public void fail_if_both_uuid_and_name_are_provided_with_views() { - userSession.logIn(); - - expectedException.expect(BadRequestException.class); - - underTestWithViews.newRequest().setMethod("POST") + underTest.newRequest().setMethod("POST") .setParam(PARAM_TEMPLATE_ID, "uuid") .setParam(PARAM_TEMPLATE_NAME, "name") .execute(); } - // @Test - // public void delete_perm_tpl_characteristic_when_delete_template() throws Exception { - // db.getDbClient().permissionTemplateCharacteristicDao().insert(db.getSession(), new PermissionTemplateCharacteristicDto() - // .setPermission(UserRole.USER) - // .setTemplateId(template.getId()) - // .setWithProjectCreator(true) - // .setCreatedAt(new Date().getTime()) - // .setUpdatedAt(new Date().getTime())); - // db.commit(); - // - // newRequest(template.getUuid()); - // - // assertThat(db.getDbClient().permissionTemplateCharacteristicDao().selectByTemplateIds(db.getSession(), - // asList(template.getId()))).isEmpty(); - // } - private UserSessionRule loginAsAdmin() { return userSession.logIn().addPermission(ADMINISTER); } - private void runOnAllUnderTests(ConsumerWithException<WsActionTester> consumer) throws Exception { - for (WsActionTester underTest : Arrays.asList(underTestWithoutViews, underTestWithViews)) { - consumer.accept(underTest); - } - } - - private interface ConsumerWithException<T> { - void accept(T e) throws Exception; - } - private PermissionTemplateDto insertTemplateAndAssociatedPermissions() { PermissionTemplateDto dto = db.permissionTemplates().insertTemplate(); UserDto user = db.getDbClient().userDao().insert(db.getSession(), UserTesting.newUserDto().setActive(true)); @@ -377,8 +239,8 @@ public class DeleteTemplateActionTest { return request.execute(); } - private TestResponse newRequestByName(WsActionTester actionTester, @Nullable PermissionTemplateDto permissionTemplateDto) { - return newRequestByName( + private void newRequestByName(WsActionTester actionTester, @Nullable PermissionTemplateDto permissionTemplateDto) { + newRequestByName( actionTester, permissionTemplateDto == null ? null : permissionTemplateDto.getName()); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java index f4d7b62abde..d79230d8c90 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java @@ -57,23 +57,25 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla private I18nRule i18n = new I18nRule(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); + private ResourceTypesRule resourceTypesWithViews = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP); private ResourceTypesRule resourceTypesWithoutViews = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionServiceWithViews = new PermissionServiceImpl(resourceTypesWithViews); private PermissionService permissionServiceWithoutViews = new PermissionServiceImpl(resourceTypesWithoutViews); + private DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(dbClient, resourceTypesWithViews); + private WsActionTester underTestWithoutViews; @Override protected SearchTemplatesAction buildWsAction() { - DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(resourceTypesWithViews); - return new SearchTemplatesAction(dbClient, userSession, i18n, defaultTemplatesResolverWithViews, permissionServiceWithViews, defaultOrganizationProvider); + return new SearchTemplatesAction(dbClient, userSession, i18n, defaultTemplatesResolverWithViews, permissionServiceWithViews); } @Before public void setUp() { - DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(resourceTypesWithoutViews); + DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(dbClient, resourceTypesWithoutViews); underTestWithoutViews = new WsActionTester( - new SearchTemplatesAction(dbClient, userSession, i18n, defaultTemplatesResolverWithViews, permissionServiceWithoutViews, defaultOrganizationProvider)); + new SearchTemplatesAction(dbClient, userSession, i18n, defaultTemplatesResolverWithViews, permissionServiceWithoutViews)); i18n.setProjectPermissions(); userSession.logIn().addPermission(ADMINISTER); } @@ -97,7 +99,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla addGroupToTemplate(projectTemplate.getUuid(), group1.getUuid(), UserRole.ADMIN); addPermissionTemplateWithProjectCreator(projectTemplate.getUuid(), UserRole.ADMIN); - db.organizations().setDefaultTemplates(projectTemplate, null, null); + db.permissionTemplates().setDefaultTemplates(projectTemplate, null, null); String result = newRequest(underTestWithoutViews).execute().getInput(); @@ -133,7 +135,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla addGroupToTemplate(portfoliosTemplate.getUuid(), group2.getUuid(), UserRole.ISSUE_ADMIN); addGroupToTemplate(portfoliosTemplate.getUuid(), group3.getUuid(), UserRole.ISSUE_ADMIN); - db.organizations().setDefaultTemplates(projectTemplate, applicationsTemplate, portfoliosTemplate); + db.permissionTemplates().setDefaultTemplates(projectTemplate, applicationsTemplate, portfoliosTemplate); String result = newRequest().execute().getInput(); @@ -144,7 +146,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla @Test public void empty_result() { - db.organizations().setDefaultTemplates("AU-Tpxb--iU5OvuD2FLy", "AU-Tpxb--iU5OvuD2FLz", "AU-TpxcA-iU5OvuD2FLx"); + db.permissionTemplates().setDefaultTemplates("AU-Tpxb--iU5OvuD2FLy", "AU-Tpxb--iU5OvuD2FLz", "AU-TpxcA-iU5OvuD2FLx"); String result = newRequest(wsTester).execute().getInput(); assertJson(result) @@ -171,7 +173,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla @Test public void empty_result_without_views() { - db.organizations().setDefaultTemplates("AU-Tpxb--iU5OvuD2FLy", "AU-TpxcA-iU5OvuD2FLz", "AU-TpxcA-iU5OvuD2FLx"); + db.permissionTemplates().setDefaultTemplates("AU-Tpxb--iU5OvuD2FLy", "AU-TpxcA-iU5OvuD2FLz", "AU-TpxcA-iU5OvuD2FLx"); String result = newRequest(underTestWithoutViews).execute().getInput(); assertJson(result) @@ -190,7 +192,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla @Test public void search_by_name() { - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); + db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); insertProjectTemplate(); insertPortfoliosTemplate(); @@ -214,7 +216,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla @Test public void display_all_project_permissions() { - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); + db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); String result = newRequest(underTestWithoutViews).execute().getInput(); @@ -263,7 +265,7 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest<SearchTempla @Test public void display_all_project_permissions_with_views() { - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); + db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); String result = newRequest().execute().getInput(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java index 39d27aaa82a..8e5767f698d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java @@ -22,17 +22,15 @@ package org.sonar.server.permission.ws.template; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.resources.Qualifiers; -import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.db.organization.DefaultTemplates; import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.db.permission.template.PermissionTemplateTesting; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.l18n.I18nRule; import org.sonar.server.permission.ws.BasePermissionWsTest; +import org.sonar.server.property.InternalProperties; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; @@ -45,20 +43,19 @@ import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_T public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaultTemplateAction> { - private DbClient dbClient = db.getDbClient(); private I18nRule i18n = new I18nRule(); @Override protected SetDefaultTemplateAction buildWsAction() { - return new SetDefaultTemplateAction(db.getDbClient(), newPermissionWsSupport(), newRootResourceTypes(), userSession, i18n, defaultOrganizationProvider); + return new SetDefaultTemplateAction(db.getDbClient(), newPermissionWsSupport(), newRootResourceTypes(), userSession, i18n); } @Test public void update_project_default_template() { + PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto portfolioDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto applicationDefaultTemplate = db.permissionTemplates().insertTemplate(); - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), - applicationDefaultTemplate, portfolioDefaultTemplate); + db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, applicationDefaultTemplate, portfolioDefaultTemplate); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); @@ -69,7 +66,7 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaul @Test public void update_project_default_template_without_qualifier_param() { - db.organizations().setDefaultTemplates("any-project-template-uuid", "any-view-template-uuid", null); + db.permissionTemplates().setDefaultTemplates("any-project-template-uuid", "any-view-template-uuid", null); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); @@ -81,9 +78,10 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaul @Test public void update_project_default_template_by_template_name() { + PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto portfolioDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto applicationDefaultTemplate = db.permissionTemplates().insertTemplate(); - db.organizations().setDefaultTemplates(db.permissionTemplates().insertTemplate(), applicationDefaultTemplate, portfolioDefaultTemplate); + db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, applicationDefaultTemplate, portfolioDefaultTemplate); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); @@ -98,7 +96,7 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaul @Test public void update_view_default_template() { PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); - db.organizations().setDefaultTemplates(projectDefaultTemplate, null, null); + db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, null, null); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); @@ -110,7 +108,7 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaul @Test public void update_app_default_template() { PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); - db.organizations().setDefaultTemplates(projectDefaultTemplate, null, null); + db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, null, null); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); @@ -164,18 +162,7 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaul newRequest(template.getUuid(), Qualifiers.FILE); } - @Test - public void fail_if_no_default_templates() { - PermissionTemplateDto template = insertTemplate(); - loginAsAdmin(); - - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No Default templates"); - - newRequest(template.getUuid(), null); - } - - private String newRequest(@Nullable String templateUuid, @Nullable String qualifier) { + private void newRequest(@Nullable String templateUuid, @Nullable String qualifier) { TestRequest request = newRequest(); if (templateUuid != null) { request.setParam(PARAM_TEMPLATE_ID, templateUuid); @@ -183,24 +170,29 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaul if (qualifier != null) { request.setParam(PARAM_QUALIFIER, qualifier); } - - return request.execute().getInput(); + request.execute(); } private PermissionTemplateDto insertTemplate() { - PermissionTemplateDto res = dbClient.permissionTemplateDao().insert(db.getSession(), PermissionTemplateTesting.newPermissionTemplateDto() - .setUuid("permission-template-uuid")); - db.commit(); - return res; + return db.permissionTemplates().insertTemplate(); } private void assertDefaultTemplates(@Nullable String projectDefaultTemplateUuid, @Nullable String applicationDefaultTemplateUuid, @Nullable String portfolioDefaultTemplateUuid) { DbSession dbSession = db.getSession(); - DefaultTemplates defaultTemplates = db.getDbClient().organizationDao().getDefaultTemplates(dbSession, db.getDefaultOrganization().getUuid()) - .orElseThrow(() -> new IllegalStateException("No default templates")); - - assertThat(defaultTemplates.getProjectUuid()).isEqualTo(projectDefaultTemplateUuid); - assertThat(defaultTemplates.getApplicationsUuid()).isEqualTo(applicationDefaultTemplateUuid); - assertThat(defaultTemplates.getPortfoliosUuid()).isEqualTo(portfolioDefaultTemplateUuid); + if (projectDefaultTemplateUuid != null) { + assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE)).contains(projectDefaultTemplateUuid); + } else { + assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE)).isEmpty(); + } + if (portfolioDefaultTemplateUuid != null) { + assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE)).contains(portfolioDefaultTemplateUuid); + } else { + assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE)).isEmpty(); + } + if (applicationDefaultTemplateUuid != null) { + assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE)).contains(applicationDefaultTemplateUuid); + } else { + assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE)).isEmpty(); + } } } |