*/
package org.sonar.server.permission;
+import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ResourceDto;
import org.sonar.db.permission.PermissionRepository;
+import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.index.IssueAuthorizationIndexer;
import org.sonar.server.user.UserSession;
-import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdminUserByComponentKey;
@ServerSide
return permissionRepository.wouldUserHavePermissionWithDefaultTemplate(dbSession, userId, permission, effectiveKey, qualifier);
}
- public void applyPermissionTemplate(DbSession dbSession, ApplyPermissionTemplateQuery query) {
- if (query.getComponentKeys().size() == 1) {
- checkProjectAdminUserByComponentKey(userSession, query.getComponentKeys().get(0));
- } else {
- checkGlobalAdminUser(userSession);
+ public void apply(DbSession dbSession, PermissionTemplateDto template, Collection<ComponentDto> projects) {
+ if (projects.isEmpty()) {
+ return;
}
- // TODO apply permission templates in on query instead of on on each project
- for (String componentKey : query.getComponentKeys()) {
- ComponentDto component = componentFinder.getByKey(dbSession, componentKey);
- permissionRepository.applyPermissionTemplate(dbSession, query.getTemplateUuid(), component);
+ for (ComponentDto project : projects) {
+ permissionRepository.apply(dbSession, template, project, null);
}
dbSession.commit();
-
indexProjectPermissions();
}
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupIdParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupNameParameter;
+import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createOrganizationParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createPermissionParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
.setHandler(this);
createPermissionParameter(action);
+ createOrganizationParameter(action);
createGroupNameParameter(action);
createGroupIdParameter(action);
createProjectParameters(action);
dbClient.permissionTemplateDao().selectByUuid(dbSession, ref.uuid()),
"Permission template with id '%s' is not found", ref.uuid());
} else {
+ OrganizationDto org = findOrganization(dbSession, ref.getOrganization());
return checkFound(
- dbClient.permissionTemplateDao().selectByName(dbSession, ref.name()),
+ dbClient.permissionTemplateDao().selectByName(dbSession, org.getUuid(), ref.name()),
"Permission template with name '%s' is not found (case insensitive)", ref.name());
}
}
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupIdParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupNameParameter;
+import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createOrganizationParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createPermissionParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
.setHandler(this);
createPermissionParameter(action);
+ createOrganizationParameter(action);
createGroupNameParameter(action);
createGroupIdParameter(action);
createProjectParameters(action);
*/
package org.sonar.server.permission.ws.template;
+import java.util.Collections;
+import java.util.Optional;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.server.permission.ApplyPermissionTemplateQuery;
import org.sonar.server.permission.PermissionService;
+import org.sonar.server.permission.ProjectId;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
+import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.permission.ApplyTemplateWsRequest;
-import static java.util.Collections.singletonList;
+import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectParameters;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
import static org.sonar.server.permission.ws.ProjectWsRef.newWsProjectRef;
public class ApplyTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
+ private final UserSession userSession;
private final PermissionService permissionService;
private final PermissionWsSupport wsSupport;
- public ApplyTemplateAction(DbClient dbClient, PermissionService permissionService, PermissionWsSupport wsSupport) {
+ public ApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionService permissionService,
+ PermissionWsSupport wsSupport) {
this.dbClient = dbClient;
+ this.userSession = userSession;
this.permissionService = permissionService;
this.wsSupport = wsSupport;
}
private void doHandle(ApplyTemplateWsRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
- PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName()));
+ PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
+ request.getTemplateId(), request.getOrganization(), request.getTemplateName()));
+
ComponentDto project = wsSupport.getRootComponentOrModule(dbSession, newWsProjectRef(request.getProjectId(), request.getProjectKey()));
+ ProjectId projectId = new ProjectId(project);
+ checkProjectAdmin(userSession, template.getOrganizationUuid(), Optional.of(projectId));
- ApplyPermissionTemplateQuery query = ApplyPermissionTemplateQuery.create(
- template.getUuid(),
- singletonList(project.key()));
- permissionService.applyPermissionTemplate(dbSession, query);
+ permissionService.apply(dbSession, template, Collections.singletonList(project));
}
}
package org.sonar.server.permission.ws.template;
import com.google.common.collect.Collections2;
-import com.google.common.collect.Lists;
import java.util.List;
+import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.i18n.I18n;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentDtoFunctions;
import org.sonar.db.component.ComponentQuery;
import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.server.permission.ApplyPermissionTemplateQuery;
import org.sonar.server.permission.PermissionService;
+import org.sonar.server.permission.ProjectId;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
+import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.permission.BulkApplyTemplateWsRequest;
import static org.sonar.server.component.ResourceTypeFunctions.RESOURCE_TYPE_TO_QUALIFIER;
+import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
import static org.sonar.server.ws.WsParameterBuilder.createRootQualifierParameter;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ORGANIZATION_KEY;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class BulkApplyTemplateAction implements PermissionsWsAction {
+
private final DbClient dbClient;
+ private final UserSession userSession;
private final PermissionService permissionService;
private final PermissionWsSupport wsSupport;
private final I18n i18n;
private final ResourceTypes resourceTypes;
- public BulkApplyTemplateAction(DbClient dbClient, PermissionService permissionService, PermissionWsSupport wsSupport, I18n i18n,
+ public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionService permissionService, PermissionWsSupport wsSupport, I18n i18n,
ResourceTypes resourceTypes) {
this.dbClient = dbClient;
+ this.userSession = userSession;
this.permissionService = permissionService;
this.wsSupport = wsSupport;
this.i18n = i18n;
private void doHandle(BulkApplyTemplateWsRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
- PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName()));
+ PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
+ request.getTemplateId(), request.getOrganization(), request.getTemplateName()));
ComponentQuery componentQuery = ComponentQuery.builder()
.setNameOrKeyQuery(request.getQuery())
.setQualifiers(qualifiers(request.getQualifier()))
.build();
- List<ComponentDto> rootComponents = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
- if (rootComponents.isEmpty()) {
- return;
- }
+ List<ComponentDto> projects = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
- ApplyPermissionTemplateQuery query = ApplyPermissionTemplateQuery.create(
- template.getUuid(),
- Lists.transform(rootComponents, ComponentDtoFunctions.toKey()));
- permissionService.applyPermissionTemplate(dbSession, query);
+ for (ComponentDto project : projects) {
+ ProjectId projectId = new ProjectId(project);
+ checkProjectAdmin(userSession, template.getOrganizationUuid(), Optional.of(projectId));
+ }
+ permissionService.apply(dbSession, template, projects);
}
}
private static BulkApplyTemplateWsRequest toBulkApplyTemplateWsRequest(Request request) {
return new BulkApplyTemplateWsRequest()
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
+ .setOrganization(request.param(PARAM_ORGANIZATION_KEY))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME))
.setQualifier(request.param(PARAM_QUALIFIER))
.setQuery(request.param(Param.TEXT_QUERY));
import org.sonar.api.server.ws.Request;
import static org.sonar.server.ws.WsUtils.checkRequest;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ORGANIZATION_KEY;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
/**
- * Template from a WS request. Guaranties the template id or the template name is provided, not both.
+ * Reference to a template as defined by WS request. Guaranties one of template id or
+ * template name is provided, not both.
*/
public class WsTemplateRef {
private final String uuid;
+ private final String organization;
private final String name;
- private WsTemplateRef(@Nullable String uuid, @Nullable String name) {
+ private WsTemplateRef(@Nullable String uuid, @Nullable String organization, @Nullable String name) {
checkRequest(uuid != null ^ name != null, "Template name or template id must be provided, not both.");
this.uuid = uuid;
+ this.organization = organization;
this.name = name;
}
public static WsTemplateRef fromRequest(Request wsRequest) {
String uuid = wsRequest.param(PARAM_TEMPLATE_ID);
+ String organization = wsRequest.param(PARAM_ORGANIZATION_KEY);
String name = wsRequest.param(PARAM_TEMPLATE_NAME);
- return new WsTemplateRef(uuid, name);
+ return new WsTemplateRef(uuid, organization, name);
}
- public static WsTemplateRef newTemplateRef(@Nullable String uuid, @Nullable String name) {
- return new WsTemplateRef(uuid, name);
+ public static WsTemplateRef newTemplateRef(@Nullable String uuid, @Nullable String organization, @Nullable String name) {
+ return new WsTemplateRef(uuid, organization, name);
}
@CheckForNull
return this.uuid;
}
+ @CheckForNull
+ public String getOrganization() {
+ return this.organization;
+ }
+
@CheckForNull
public String name() {
return this.name;
public void define(NewController context) {
WebService.NewAction action = context.createAction("search")
.setDescription("Search for user groups.<br>" +
- "Requires to be logged.")
+ "Requires to be logged in.")
.setHandler(this)
.setResponseExample(getClass().getResource("example-search.json"))
.setSince("5.2")
import org.junit.Test;
import org.sonar.api.web.UserRole;
-import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.organization.OrganizationDto;
private WsTester.TestRequest newRequest() {
return wsTester.newPostRequest(CONTROLLER, ACTION);
}
-
- private void loginAsAdminOnDefaultOrganization() {
- loginAsAdmin(db.getDefaultOrganization());
- }
-
- private void loginAsAdmin(OrganizationDto org) {
- userSession.login().addOrganizationPermission(org.getUuid(), GlobalPermissions.SYSTEM_ADMIN);
- }
}
import org.junit.Test;
import org.sonar.api.web.UserRole;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
@Test
public void add_permission_to_user() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
wsTester.newPostRequest(CONTROLLER, ACTION)
.setParam(PARAM_USER_LOGIN, user.getLogin())
.setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
public void add_permission_to_project_referenced_by_its_id() throws Exception {
ComponentDto project = db.components().insertProject();
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
wsTester.newPostRequest(CONTROLLER, ACTION)
.setParam(PARAM_USER_LOGIN, user.getLogin())
.setParam(PARAM_PROJECT_ID, project.uuid())
public void add_permission_to_project_referenced_by_its_key() throws Exception {
ComponentDto project = db.components().insertProject();
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
wsTester.newPostRequest(CONTROLLER, ACTION)
.setParam(PARAM_USER_LOGIN, user.getLogin())
.setParam(PARAM_PROJECT_KEY, project.getKey())
public void add_permission_to_view() throws Exception {
ComponentDto view = db.components().insertComponent(newView("view-uuid").setKey("view-key"));
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
wsTester.newPostRequest(CONTROLLER, ACTION)
.setParam(PARAM_USER_LOGIN, user.getLogin())
.setParam(PARAM_PROJECT_ID, view.uuid())
@Test
public void fail_when_project_uuid_is_unknown() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(NotFoundException.class);
@Test
public void fail_when_project_permission_without_project() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
@Test
public void fail_when_component_is_not_a_project() throws Exception {
db.components().insertComponent(newFileDto(newProjectDto("project-uuid"), null, "file-uuid"));
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
@Test
public void fail_when_get_request() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(ServerException.class);
@Test
public void fail_when_user_login_is_missing() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(IllegalArgumentException.class);
@Test
public void fail_when_permission_is_missing() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(NotFoundException.class);
@Test
public void fail_when_project_uuid_and_project_key_are_provided() throws Exception {
db.components().insertProject();
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Project id or project key can be provided, not both.");
assertThat(db.users().selectUserPermissions(user, project)).containsOnly(ISSUE_ADMIN);
}
-
- private void loginAsAdmin() {
- loginAsOrganizationAdmin(db.getDefaultOrganization());
- }
-
- private void loginAsOrganizationAdmin(OrganizationDto org) {
- userSession.login().addOrganizationPermission(org.getUuid(), SYSTEM_ADMIN);
- }
}
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ResourceTypesRule;
+import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateTesting;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.ws.WsTester;
import static org.mockito.Mockito.mock;
+import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN;
+import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
public abstract class BasePermissionWsTest<A extends PermissionsWsAction> {
}
protected PermissionTemplateDto insertTemplate() {
- PermissionTemplateDto dto = db.getDbClient().permissionTemplateDao().insert(db.getSession(), PermissionTemplateTesting.newPermissionTemplateDto());
+ PermissionTemplateDto dto = PermissionTemplateTesting.newPermissionTemplateDto()
+ .setOrganizationUuid(db.getDefaultOrganization().getUuid());
+ dto = db.getDbClient().permissionTemplateDao().insert(db.getSession(), dto);
+ db.commit();
+ return dto;
+ }
+
+ protected void loginAsAdminOnDefaultOrganization() {
+ loginAsAdmin(db.getDefaultOrganization());
+ }
+
+ protected void loginAsAdmin(OrganizationDto org) {
+ userSession.login().addOrganizationPermission(org.getUuid(), SYSTEM_ADMIN);
+ }
+
+ protected PermissionTemplateDto selectTemplateInDefaultOrganization(String name) {
+ return db.getDbClient().permissionTemplateDao().selectByName(db.getSession(), db.getDefaultOrganization().getUuid(), name);
+ }
+
+ protected PermissionTemplateDto addTemplateToDefaultOrganization() {
+ PermissionTemplateDto dto = newPermissionTemplateDto()
+ .setOrganizationUuid(db.getDefaultOrganization().getUuid());
+ db.getDbClient().permissionTemplateDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
import org.junit.Test;
import org.sonar.api.web.UserRole;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.GroupDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
public void remove_permission_using_group_name() throws Exception {
db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
db.users().insertPermissionOnGroup(aGroup, PROVISIONING);
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_GROUP_NAME, aGroup.getName())
public void remove_permission_using_group_id() throws Exception {
db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
db.users().insertPermissionOnGroup(aGroup, PROVISIONING);
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_GROUP_ID, aGroup.getId().toString())
db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
db.users().insertProjectPermissionOnGroup(aGroup, ADMIN, project);
db.users().insertProjectPermissionOnGroup(aGroup, ISSUE_ADMIN, project);
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_GROUP_NAME, aGroup.getName())
db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
db.users().insertProjectPermissionOnGroup(aGroup, ADMIN, view);
db.users().insertProjectPermissionOnGroup(aGroup, ISSUE_ADMIN, view);
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_GROUP_NAME, aGroup.getName())
db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
db.users().insertProjectPermissionOnGroup(aGroup, ADMIN, project);
db.users().insertProjectPermissionOnGroup(aGroup, ISSUE_ADMIN, project);
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_GROUP_NAME, aGroup.getName())
public void fail_to_remove_last_admin_permission() throws Exception {
db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
db.users().insertPermissionOnGroup(aGroup, PROVISIONING);
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Last group with permission 'admin'. Permission cannot be removed.");
@Test
public void fail_when_project_does_not_exist() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Project id 'unknown-project-uuid' not found");
@Test
public void fail_when_project_project_permission_without_project() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Invalid global permission 'issueadmin'. Valid values are [admin, profileadmin, gateadmin, scan, provisioning]");
@Test
public void fail_when_component_is_not_a_project() throws Exception {
ComponentDto file = db.components().insertComponent(newFileDto(newProjectDto(), null, "file-uuid"));
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Component 'KEY_file-uuid' (id: file-uuid) must be a project or a module.");
@Test
public void fail_when_get_request() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(ServerException.class);
expectedException.expectMessage("HTTP method POST is required");
@Test
public void fail_when_group_name_is_missing() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Group name or group id must be provided");
@Test
public void fail_when_permission_name_and_id_are_missing() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The 'permission' parameter is missing");
@Test
public void fail_when_group_id_does_not_exist() throws Exception {
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("No group with id '42'");
@Test
public void fail_when_project_uuid_and_project_key_are_provided() throws Exception {
ComponentDto project = db.components().insertProject();
- loginAsAdmin();
+ loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Project id or project key can be provided, not both.");
private WsTester.TestRequest newRequest() {
return wsTester.newPostRequest(CONTROLLER, ACTION);
}
-
- private void loginAsAdmin() {
- loginAsOrganizationAdmin(db.getDefaultOrganization());
- }
-
- private void loginAsOrganizationAdmin(OrganizationDto org) {
- userSession.login().addOrganizationPermission(org.getUuid(), SYSTEM_ADMIN);
- }
-
}
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.issue.index.IssueAuthorizationIndexer;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.ws.BasePermissionWsTest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN;
import static org.sonar.db.component.ComponentTesting.newProjectDto;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.CONTROLLER;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID;
PermissionRepository repository = new PermissionRepository(db.getDbClient(), new MapSettings());
ComponentFinder componentFinder = new ComponentFinder(db.getDbClient());
PermissionService permissionService = new PermissionService(db.getDbClient(), repository, issueAuthorizationIndexer, userSession, componentFinder);
- return new ApplyTemplateAction(db.getDbClient(), permissionService, newPermissionWsSupport());
+ return new ApplyTemplateAction(db.getDbClient(), userSession, permissionService, newPermissionWsSupport());
}
@Before
public void setUp() {
- loginAsAdmin();
-
user1 = db.users().insertUser("user-login-1");
user2 = db.users().insertUser("user-login-2");
OrganizationDto defaultOrg = defaultOrganizationProvider.getDto();
@Test
public void apply_template_with_project_uuid() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
newRequest(template1.getUuid(), project.uuid(), null);
assertTemplate1AppliedToProject();
@Test
public void apply_template_with_project_uuid_by_template_name() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
wsTester.newPostRequest(CONTROLLER, ACTION)
.setParam(PARAM_TEMPLATE_NAME, template1.getName().toUpperCase())
.setParam(PARAM_PROJECT_ID, project.uuid())
@Test
public void apply_template_with_project_key() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
newRequest(template1.getUuid(), null, project.key());
assertTemplate1AppliedToProject();
@Test
public void fail_when_unknown_template() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Permission template with id 'unknown-template-uuid' is not found");
@Test
public void fail_when_unknown_project_uuid() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Project id 'unknown-project-uuid' not found");
@Test
public void fail_when_unknown_project_key() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Project key 'unknown-project-key' not found");
@Test
public void fail_when_template_is_not_provided() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(BadRequestException.class);
newRequest(null, project.uuid(), null);
@Test
public void fail_when_project_uuid_and_key_not_provided() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Project id or project key can be provided, not both.");
}
@Test
- public void fail_when_anonymous() throws Exception {
- expectedException.expect(UnauthorizedException.class);
- userSession.anonymous();
-
- newRequest(template1.getUuid(), project.uuid(), null);
- }
+ public void fail_when_not_admin_of_organization() throws Exception {
+ userSession.login().addOrganizationPermission("otherOrg", SYSTEM_ADMIN);
- @Test
- public void fail_when_insufficient_privileges() throws Exception {
expectedException.expect(ForbiddenException.class);
userSession.login().setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
PermissionQuery query = PermissionQuery.builder().setPermission(permission).setComponentUuid(project.uuid()).build();
return db.getDbClient().userPermissionDao().selectLogins(db.getSession(), query);
}
-
- private void loginAsAdmin() {
- userSession.login("login").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
- }
}
import org.sonar.api.config.MapSettings;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.web.UserRole;
-import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.PermissionQuery;
PermissionRepository repository = new PermissionRepository(db.getDbClient(), new MapSettings());
ComponentFinder componentFinder = new ComponentFinder(db.getDbClient());
PermissionService permissionService = new PermissionService(db.getDbClient(), repository, issueAuthorizationIndexer, userSession, componentFinder);
- return new BulkApplyTemplateAction(db.getDbClient(), permissionService, newPermissionWsSupport(), new I18nRule(), newRootResourceTypes());
+ return new BulkApplyTemplateAction(db.getDbClient(), userSession, permissionService, newPermissionWsSupport(), new I18nRule(), newRootResourceTypes());
}
@Before
public void setUp() {
- loginAsAdmin();
-
user1 = db.users().insertUser("user-login-1");
user2 = db.users().insertUser("user-login-2");
OrganizationDto defaultOrg = defaultOrganizationProvider.getDto();
db.users().insertProjectPermissionOnUser(user2, UserRole.ADMIN, developer);
db.users().insertProjectPermissionOnGroup(group1, UserRole.ADMIN, developer);
db.users().insertProjectPermissionOnGroup(group2, UserRole.ADMIN, developer);
+ loginAsAdminOnDefaultOrganization();
newRequest().setParam(PARAM_TEMPLATE_ID, template1.getUuid()).execute();
@Test
public void bulk_apply_template_by_template_name() throws Exception {
ComponentDto project = db.components().insertComponent(newProjectDto());
+ loginAsAdminOnDefaultOrganization();
newRequest().setParam(PARAM_TEMPLATE_NAME, template1.getName()).execute();
public void apply_template_by_qualifier() throws Exception {
ComponentDto project = db.components().insertComponent(newProjectDto());
ComponentDto view = db.components().insertComponent(newView());
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_TEMPLATE_ID, template1.getUuid())
ComponentDto projectUntouched = newProjectDto().setKey("new-sonar").setName("project-name");
db.components().insertProjectAndSnapshot(projectUntouched);
db.components().indexAllComponents();
+ loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_TEMPLATE_ID, template1.getUuid())
@Test
public void fail_if_no_template_parameter() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Template name or template id must be provided, not both.");
@Test
public void fail_if_template_name_is_incorrect() throws Exception {
+ loginAsAdminOnDefaultOrganization();
+
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Permission template with id 'unknown-template-uuid' is not found");
private WsTester.TestRequest newRequest() {
return wsTester.newPostRequest(CONTROLLER, ACTION);
}
-
- private void loginAsAdmin() {
- userSession.login().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
- }
}
private PermissionTemplateDto insertProjectTemplate() {
return insertTemplate(newPermissionTemplateDto()
+ .setOrganizationUuid(db.getDefaultOrganization().getUuid())
.setUuid(UUID_EXAMPLE_01)
.setName("Default template for Projects")
.setDescription("Template for new projects")
private PermissionTemplateDto insertViewsTemplate() {
return insertTemplate(newPermissionTemplateDto()
+ .setOrganizationUuid(db.getDefaultOrganization().getUuid())
.setUuid(UUID_EXAMPLE_02)
.setName("Default template for Views")
.setDescription("Template for new views")
private PermissionTemplateDto insertDeveloperTemplate() {
return insertTemplate(newPermissionTemplateDto()
+ .setOrganizationUuid(db.getDefaultOrganization().getUuid())
.setUuid(UUID_EXAMPLE_03)
.setName("Default template for Developers")
.setKeyPattern(".*sonar.developer.*")
import org.sonar.api.web.UserRole;
import org.sonar.db.DbTester;
import org.sonar.db.loadedtemplate.LoadedTemplateDto;
-import org.sonar.db.permission.template.PermissionTemplate;
+import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateGroupDto;
import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.organization.DefaultOrganizationProviderRule;
underTest.start();
- PermissionTemplate defaultTemplate = selectTemplate();
- assertThat(defaultTemplate.getTemplate().getName()).isEqualTo("Default template");
+ PermissionTemplateDto defaultTemplate = selectTemplate();
+ assertThat(defaultTemplate.getName()).isEqualTo("Default template");
- List<PermissionTemplateGroupDto> groupPermissions = defaultTemplate.getGroupPermissions();
+ List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate);
assertThat(groupPermissions).hasSize(4);
expectGroupPermission(groupPermissions, UserRole.ADMIN, DefaultGroups.ADMINISTRATORS);
expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, DefaultGroups.ADMINISTRATORS);
expectGroupPermission(groupPermissions, UserRole.USER, DefaultGroups.ANYONE);
// template is marked as default
- verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getTemplate().getUuid());
+ verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getUuid());
assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
}
public void ignore_administrators_permissions_if_group_does_not_exist() {
underTest.start();
- PermissionTemplate defaultTemplate = selectTemplate();
- assertThat(defaultTemplate.getTemplate().getName()).isEqualTo("Default template");
+ PermissionTemplateDto defaultTemplate = selectTemplate();
+ assertThat(defaultTemplate.getName()).isEqualTo("Default template");
- List<PermissionTemplateGroupDto> groupPermissions = defaultTemplate.getGroupPermissions();
+ List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate);
assertThat(groupPermissions).hasSize(2);
expectGroupPermission(groupPermissions, UserRole.CODEVIEWER, DefaultGroups.ANYONE);
expectGroupPermission(groupPermissions, UserRole.USER, DefaultGroups.ANYONE);
// marked as default
- verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getTemplate().getUuid());
+ verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getUuid());
assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Cannot setup default permission for group: sonar-administrators");
}
db.getDbClient().loadedTemplateDao().insert(new LoadedTemplateDto(DEFAULT_TEMPLATE_KEY, LoadedTemplateDto.PERMISSION_TEMPLATE_TYPE));
}
- private PermissionTemplate selectTemplate() {
- return db.getDbClient().permissionTemplateDao().selectByUuidWithUserAndGroupPermissions(db.getSession(), DEFAULT_TEMPLATE_KEY);
+ private PermissionTemplateDto selectTemplate() {
+ return db.getDbClient().permissionTemplateDao().selectByUuid(db.getSession(), DEFAULT_TEMPLATE_KEY);
+ }
+
+ private List<PermissionTemplateGroupDto> selectGroupPermissions(PermissionTemplateDto template) {
+ return db.getDbClient().permissionTemplateDao().selectGroupPermissionsByTemplateId(db.getSession(), template.getId());
}
private void expectGroupPermission(List<PermissionTemplateGroupDto> groupPermissions, String expectedPermission,
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
+import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.config.Settings;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.permission.template.PermissionTemplate;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateGroupDto;
import org.sonar.db.permission.template.PermissionTemplateUserDto;
+import static java.util.Arrays.asList;
import static org.sonar.api.security.DefaultGroups.isAnyone;
/**
this.settings = settings;
}
- public void applyPermissionTemplate(DbSession session, String templateUuid, ComponentDto project) {
- applyPermissionTemplate(session, templateUuid, project, null);
- }
-
- private void applyPermissionTemplate(DbSession session, String templateUuid, ComponentDto project, @Nullable Long currentUserId) {
- PermissionTemplate template = dbClient.permissionTemplateDao().selectPermissionTemplateWithPermissions(session, templateUuid);
+ public void apply(DbSession session, PermissionTemplateDto template, ComponentDto project, @Nullable Long currentUserId) {
updateProjectAuthorizationDate(session, project.getId());
dbClient.groupPermissionDao().deleteByRootComponentId(session, project.getId());
dbClient.userPermissionDao().deleteProjectPermissions(session, project.getId());
- List<PermissionTemplateUserDto> usersPermissions = template.getUserPermissions();
- String organizationUuid = template.getTemplate().getOrganizationUuid();
+ List<PermissionTemplateUserDto> usersPermissions = dbClient.permissionTemplateDao().selectUserPermissionsByTemplateId(session, template.getId());
+ String organizationUuid = template.getOrganizationUuid();
usersPermissions
.forEach(up -> {
UserPermissionDto dto = new UserPermissionDto(organizationUuid, up.getPermission(), up.getUserId(), project.getId());
dbClient.userPermissionDao().insert(session, dto);
});
- List<PermissionTemplateGroupDto> groupsPermissions = template.getGroupPermissions();
+ List<PermissionTemplateGroupDto> groupsPermissions = dbClient.permissionTemplateDao().selectGroupPermissionsByTemplateId(session, template.getId());
groupsPermissions.forEach(gp -> {
GroupPermissionDto dto = new GroupPermissionDto()
- .setOrganizationUuid(template.getTemplate().getOrganizationUuid())
+ .setOrganizationUuid(organizationUuid)
.setGroupId(isAnyone(gp.getGroupName()) ? null : gp.getGroupId())
.setRole(gp.getPermission())
.setResourceId(project.getId());
dbClient.groupPermissionDao().insert(session, dto);
});
- List<PermissionTemplateCharacteristicDto> characteristics = template.getCharacteristics();
+ List<PermissionTemplateCharacteristicDto> characteristics = dbClient.permissionTemplateCharacteristicDao().selectByTemplateIds(session, asList(template.getId()));
if (currentUserId != null) {
Set<String> permissionsForCurrentUserAlreadyInDb = usersPermissions.stream()
.filter(userPermission -> currentUserId.equals(userPermission.getUserId()))
.filter(PermissionTemplateCharacteristicDto::getWithProjectCreator)
.filter(characteristic -> !permissionsForCurrentUserAlreadyInDb.contains(characteristic.getPermission()))
.forEach(c -> {
- UserPermissionDto dto = new UserPermissionDto(template.getTemplate().getOrganizationUuid(), c.getPermission(), currentUserId, project.getId());
+ UserPermissionDto dto = new UserPermissionDto(organizationUuid, c.getPermission(), currentUserId, project.getId());
dbClient.userPermissionDao().insert(session, dto);
});
}
}
- /**
- * For each modification of permission on a project, update the authorization_updated_at to help ES reindex only relevant changes
- */
- private void updateProjectAuthorizationDate(DbSession dbSession, long projectId) {
- dbClient.resourceDao().updateAuthorizationDate(projectId, dbSession);
- }
-
/**
* Warning, this method is also used by the Developer Cockpit plugin
*/
}
public void applyDefaultPermissionTemplate(DbSession dbSession, ComponentDto componentDto, @Nullable Long userId) {
- String applicablePermissionTemplateKey = getApplicablePermissionTemplateKey(dbSession, componentDto.getKey(), componentDto.qualifier());
- applyPermissionTemplate(dbSession, applicablePermissionTemplateKey, componentDto, userId);
+ PermissionTemplateDto template = getApplicablePermissionTemplate(dbSession, componentDto);
+ if (template == null) {
+ throw new IllegalArgumentException("Can not retrieve default permission template");
+ }
+ apply(dbSession, template, componentDto, userId);
}
/**
* Return the permission template for the given componentKey. If no template key pattern match then consider default
* permission template for the resource qualifier.
*/
- private String getApplicablePermissionTemplateKey(DbSession session, final String componentKey, String qualifier) {
+ @CheckForNull
+ private PermissionTemplateDto getApplicablePermissionTemplate(DbSession dbSession, ComponentDto component) {
// FIXME performance issue here, we should not load all templates
- List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(session);
+ List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(dbSession);
List<PermissionTemplateDto> matchingTemplates = new ArrayList<>();
for (PermissionTemplateDto permissionTemplateDto : allPermissionTemplates) {
String keyPattern = permissionTemplateDto.getKeyPattern();
- if (StringUtils.isNotBlank(keyPattern) && componentKey.matches(keyPattern)) {
+ if (StringUtils.isNotBlank(keyPattern) && component.getKey().matches(keyPattern)) {
matchingTemplates.add(permissionTemplateDto);
}
}
- checkAtMostOneMatchForComponentKey(componentKey, matchingTemplates);
+ checkAtMostOneMatchForComponentKey(component.getKey(), matchingTemplates);
if (matchingTemplates.size() == 1) {
- return matchingTemplates.get(0).getUuid();
+ return matchingTemplates.get(0);
}
- String qualifierTemplateKey = settings.getString("sonar.permission.template." + qualifier + ".default");
+ String qualifierTemplateKey = settings.getString("sonar.permission.template." + component.qualifier() + ".default");
if (!StringUtils.isBlank(qualifierTemplateKey)) {
- return qualifierTemplateKey;
+ return dbClient.permissionTemplateDao().selectByUuid(dbSession, qualifierTemplateKey);
}
String defaultTemplateKey = settings.getString("sonar.permission.template.default");
if (StringUtils.isBlank(defaultTemplateKey)) {
throw new IllegalStateException("At least one default permission template should be defined");
}
- return defaultTemplateKey;
+ return dbClient.permissionTemplateDao().selectByUuid(dbSession, defaultTemplateKey);
}
public boolean wouldUserHavePermissionWithDefaultTemplate(DbSession dbSession, @Nullable Long currentUserId, String permission, String projectKey, String qualifier) {
- String templateUuid = getApplicablePermissionTemplateKey(dbSession, projectKey, qualifier);
- PermissionTemplateDto template = dbClient.permissionTemplateDao().selectByUuid(dbSession, templateUuid);
+ PermissionTemplateDto template = getApplicablePermissionTemplate(dbSession, new ComponentDto().setKey(projectKey).setQualifier(qualifier));
if (template == null) {
return false;
}
List<String> potentialPermissions = dbClient.permissionTemplateDao().selectPotentialPermissionsByUserIdAndTemplateId(dbSession, currentUserId, template.getId());
-
return potentialPermissions.contains(permission);
}
templatesNames.toString()));
}
}
+
+ /**
+ * For each modification of permission on a project, update the authorization_updated_at to help ES reindex only relevant changes
+ */
+ private void updateProjectAuthorizationDate(DbSession dbSession, long projectId) {
+ dbClient.resourceDao().updateAuthorizationDate(projectId, dbSession);
+ }
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.db.permission.template;
-
-import java.util.List;
-import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
-import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.db.permission.template.PermissionTemplateGroupDto;
-import org.sonar.db.permission.template.PermissionTemplateUserDto;
-
-public class PermissionTemplate {
- private final PermissionTemplateDto template;
- private final List<PermissionTemplateUserDto> userPermissions;
- private final List<PermissionTemplateGroupDto> groupPermissions;
- private final List<PermissionTemplateCharacteristicDto> characteristics;
-
- public PermissionTemplate(PermissionTemplateDto template,
- List<PermissionTemplateUserDto> userPermissions,
- List<PermissionTemplateGroupDto> groupPermissions,
- List<PermissionTemplateCharacteristicDto> characteristics) {
- this.template = template;
- this.userPermissions = userPermissions;
- this.groupPermissions = groupPermissions;
- this.characteristics = characteristics;
- }
-
- public PermissionTemplateDto getTemplate() {
- return template;
- }
-
- public List<PermissionTemplateUserDto> getUserPermissions() {
- return userPermissions;
- }
-
- public List<PermissionTemplateGroupDto> getGroupPermissions() {
- return groupPermissions;
- }
-
- public List<PermissionTemplateCharacteristicDto> getCharacteristics() {
- return characteristics;
- }
-}
import static java.util.Objects.requireNonNull;
public class PermissionTemplateCharacteristicDao implements Dao {
+
public List<PermissionTemplateCharacteristicDto> selectByTemplateIds(DbSession dbSession, List<Long> templateIds) {
return templateIds.isEmpty() ? emptyList() : mapper(dbSession).selectByTemplateIds(templateIds);
}
import org.apache.ibatis.annotations.Param;
public interface PermissionTemplateCharacteristicMapper {
- List<PermissionTemplateCharacteristicDto> selectByTemplateId(long templateId);
-
List<PermissionTemplateCharacteristicDto> selectByTemplateIds(@Param("templateIds") List<Long> templateId);
PermissionTemplateCharacteristicDto selectByPermissionAndTemplateId(@Param("permission") String permission, @Param("templateId") long templateId);
return executeLargeInputs(logins, l -> mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, l));
}
- private static List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, long templateId) {
+ public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, long templateId) {
return mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, Collections.emptyList());
}
return executeLargeInputs(groups, g -> mapper(dbSession).selectGroupPermissionsByTemplateIdAndGroupNames(templateId, g));
}
- List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateId(DbSession dbSession, long templateId) {
+ public List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateId(DbSession dbSession, long templateId) {
return mapper(dbSession).selectGroupPermissionsByTemplateIdAndGroupNames(templateId, Collections.emptyList());
}
return mapper(session).selectByUuid(templateUuid);
}
- @CheckForNull
- public PermissionTemplate selectByUuidWithUserAndGroupPermissions(DbSession session, String templateUuid) {
- PermissionTemplateMapper mapper = mapper(session);
-
- PermissionTemplateDto template = mapper.selectByUuid(templateUuid);
- if (template == null) {
- return null;
- }
-
- List<PermissionTemplateUserDto> userPermissions = selectUserPermissionsByTemplateId(session, template.getId());
- List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissionsByTemplateId(session, template.getId());
- PermissionTemplateCharacteristicMapper characteristicMapper = session.getMapper(PermissionTemplateCharacteristicMapper.class);
- List<PermissionTemplateCharacteristicDto> characteristics = characteristicMapper.selectByTemplateId(template.getId());
-
- return new PermissionTemplate(template, userPermissions, groupPermissions, characteristics);
- }
-
public List<PermissionTemplateDto> selectAll(DbSession session, String nameMatch) {
String uppercaseNameMatch = toUppercaseSqlQuery(nameMatch);
return mapper(session).selectAll(uppercaseNameMatch);
session.commit();
}
- /**
- * Load permission template and load associated collections of users and groups permissions, and characteristics
- */
- public PermissionTemplate selectPermissionTemplateWithPermissions(DbSession session, String templateUuid) {
- PermissionTemplateDto template = selectByUuid(session, templateUuid);
- if (template == null) {
- throw new IllegalArgumentException("Could not retrieve permission template with uuid " + templateUuid);
- }
- PermissionTemplate templateWithDependencies = selectByUuidWithUserAndGroupPermissions(session, template.getUuid());
- if (templateWithDependencies == null) {
- throw new IllegalArgumentException("Could not retrieve permissions for template with uuid " + templateUuid);
- }
- return templateWithDependencies;
- }
-
- public PermissionTemplateDto selectByName(DbSession dbSession, String name) {
- return mapper(dbSession).selectByName(name.toUpperCase(Locale.ENGLISH));
+ public PermissionTemplateDto selectByName(DbSession dbSession, String organizationUuid, String name) {
+ return mapper(dbSession).selectByName(organizationUuid, name.toUpperCase(Locale.ENGLISH));
}
public List<String> selectPotentialPermissionsByUserIdAndTemplateId(DbSession dbSession, @Nullable Long currentUserId, long templateId) {
void deleteByGroupId(long groupId);
- PermissionTemplateDto selectByName(String name);
+ PermissionTemplateDto selectByName(@Param("organizationUuid") String organizationUuid, @Param("name") String name);
List<String> selectUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateId") long templateId, RowBounds rowBounds);
ptc.updated_at as updatedAt
</sql>
- <select id="selectByTemplateId" parameterType="long" resultType="PermissionTemplateCharacteristic">
- select
- <include refid="columns" />
- from perm_tpl_characteristics ptc
- where
- ptc.template_id = #{templateId}
- order by id
- </select>
-
<select id="selectByTemplateIds" parameterType="long" resultType="PermissionTemplateCharacteristic">
select
<include refid="columns" />
ORDER BY UPPER(name), name
</select>
- <select id="selectByName" parameterType="String" resultType="PermissionTemplate">
- SELECT
+ <select id="selectByName" parameterType="map" resultType="PermissionTemplate">
+ select
<include refid="templateColumns"/>
- FROM permission_templates
- WHERE UPPER(name)=#{templateName}
+ from permission_templates
+ where
+ organization_uuid = #{organizationUuid,jdbcType=VARCHAR} and
+ upper(name) = #{name,jdbcType=VARCHAR}
</select>
<sql id="permissionTemplateUserColumns">
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
+import static org.sonar.db.component.ComponentTesting.newProjectDto;
import static org.sonar.db.user.GroupTesting.newGroupDto;
public class PermissionRepositoryTest {
private static final String DEFAULT_TEMPLATE = "default_20130101_010203";
- private static final ComponentDto PROJECT = new ComponentDto().setId(123L).setUuid("THE_PROJECT_UUID");
+ private static final ComponentDto PROJECT = newProjectDto().setId(123L).setUuid("THE_PROJECT_UUID");
private static final long NOW = 123456789L;
@Rule
assertThat(roleDao.selectGroupPermissions(session, "Anyone", PROJECT.getId())).isEmpty();
assertThat(dbTester.getDbClient().userPermissionDao().selectPermissionsByLogin(session, "marius", PROJECT.uuid())).isEmpty();
- underTest.applyPermissionTemplate(session, "default_20130101_010203", PROJECT);
+ PermissionTemplateDto template = dbTester.getDbClient().permissionTemplateDao().selectByUuid(session, "default_20130101_010203");
+ underTest.apply(session, template, PROJECT, null);
assertThat(roleDao.selectGroupPermissions(session, "sonar-administrators", PROJECT.getId())).containsOnly("admin", "issueadmin");
assertThat(roleDao.selectGroupPermissions(session, "sonar-users", PROJECT.getId())).containsOnly("user", "codeviewer");
import org.sonar.db.user.UserDto;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.sonar.api.security.DefaultGroups.ANYONE;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.CODEVIEWER;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
import static org.sonar.db.user.GroupTesting.newGroupDto;
-import static org.sonar.db.user.UserTesting.newUserDto;
public class PermissionTemplateDaoTest {
db.assertDbUnitTable(getClass(), "createPermissionTemplate-result.xml", "permission_templates", "id", "name", "description");
}
- @Test
- public void should_select_permission_template() {
- db.prepareDbUnit(getClass(), "selectPermissionTemplate.xml");
-
- PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "my_template_20130102_030405");
-
- assertThat(result).isNotNull();
- PermissionTemplateDto template = result.getTemplate();
- assertThat(template.getName()).isEqualTo("my template");
- assertThat(template.getUuid()).isEqualTo("my_template_20130102_030405");
- assertThat(template.getDescription()).isEqualTo("my description");
- List<PermissionTemplateUserDto> usersPermissions = result.getUserPermissions();
- assertThat(usersPermissions).hasSize(3);
- assertThat(usersPermissions).extracting("userId").containsOnly(1L, 2L, 1L);
- assertThat(usersPermissions).extracting("userLogin").containsOnly("login1", "login2", "login2");
- assertThat(usersPermissions).extracting("userName").containsOnly("user1", "user2", "user2");
- assertThat(usersPermissions).extracting("permission").containsOnly("user_permission1", "user_permission1", "user_permission2");
- List<PermissionTemplateGroupDto> groupsPermissions = result.getGroupPermissions();
- assertThat(groupsPermissions).hasSize(3);
- assertThat(groupsPermissions).extracting("groupId").containsOnly(1L, 2L, 0L);
- assertThat(groupsPermissions).extracting("groupName").containsOnly("group1", "group2", "Anyone");
- assertThat(groupsPermissions).extracting("permission").containsOnly("group_permission1", "group_permission1", "group_permission2");
- }
-
@Test
public void should_select_permission_template_by_key() {
db.prepareDbUnit(getClass(), "selectPermissionTemplate.xml");
checkTemplateTables("addNullGroupPermissionToTemplate-result.xml");
}
- @Test
- public void new_permission_template_with_empty_user_group_characteristics() {
- PermissionTemplateDto template = underTest.insert(dbSession, newPermissionTemplateDto().setUuid("TEMPLATE_UUID"));
-
- PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "TEMPLATE_UUID");
-
- assertThat(result.getTemplate())
- .extracting(PermissionTemplateDto::getId, PermissionTemplateDto::getUuid, PermissionTemplateDto::getName, PermissionTemplateDto::getDescription)
- .containsExactly(template.getId(), template.getUuid(), template.getName(), template.getDescription());
-
- assertThat(result.getUserPermissions()).isEmpty();
- assertThat(result.getGroupPermissions()).isEmpty();
- assertThat(result.getCharacteristics()).isEmpty();
- }
-
- @Test
- public void unknown_permission_template() {
- PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "UNKNOWN_TEMPLATE_UUID");
-
- assertThat(result).isNull();
- }
-
- @Test
- public void permission_template_with_user_group_and_characteristics() {
- PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("TEMPLATE_UUID"));
- GroupDto group = db.users().insertGroup(newGroupDto());
- UserDto user = db.users().insertUser(newUserDto());
- templateDb.addGroupToTemplate(template.getId(), group.getId(), UserRole.ADMIN);
- templateDb.addGroupToTemplate(template.getId(), null, UserRole.USER);
- templateDb.addUserToTemplate(template.getId(), user.getId(), UserRole.CODEVIEWER);
- templateDb.addProjectCreatorToTemplate(template.getId(), UserRole.USER);
-
- PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "TEMPLATE_UUID");
- assertThat(result.getTemplate())
- .extracting(PermissionTemplateDto::getId, PermissionTemplateDto::getUuid, PermissionTemplateDto::getName, PermissionTemplateDto::getDescription)
- .containsExactly(template.getId(), template.getUuid(), template.getName(), template.getDescription());
- assertThat(result.getCharacteristics()).hasSize(1)
- .extracting(PermissionTemplateCharacteristicDto::getPermission, PermissionTemplateCharacteristicDto::getWithProjectCreator)
- .containsExactly(tuple(UserRole.USER, true));
- assertThat(result.getGroupPermissions())
- .extracting(PermissionTemplateGroupDto::getGroupId, PermissionTemplateGroupDto::getGroupName, PermissionTemplateGroupDto::getPermission)
- .containsOnly(
- tuple(group.getId(), group.getName(), UserRole.ADMIN),
- tuple(0L, ANYONE, UserRole.USER)
- );
- assertThat(result.getUserPermissions()).hasSize(1)
- .extracting(PermissionTemplateUserDto::getUserId, PermissionTemplateUserDto::getUserLogin, PermissionTemplateUserDto::getPermission)
- .containsExactly(tuple(user.getId(), user.getLogin(), UserRole.CODEVIEWER));
- }
-
- @Test
- public void should_fail_on_unmatched_template() {
- expectedException.expect(IllegalArgumentException.class);
-
- underTest.selectPermissionTemplateWithPermissions(db.getSession(), "unmatched");
- }
-
@Test
public void group_count_by_template_and_permission() {
PermissionTemplateDto template1 = templateDb.insertTemplate();
private String projectId;
private String projectKey;
private String templateId;
+ private String organization;
private String templateName;
@CheckForNull
return this;
}
+ @CheckForNull
+ public String getOrganization() {
+ return organization;
+ }
+
+ public ApplyTemplateWsRequest setOrganization(@Nullable String s) {
+ this.organization = s;
+ return this;
+ }
@CheckForNull
public String getTemplateName() {
return templateName;
public class BulkApplyTemplateWsRequest {
private String templateId;
+ private String organization;
private String templateName;
private String query;
private String qualifier;
return this;
}
+ @CheckForNull
+ public String getOrganization() {
+ return organization;
+ }
+
+ public BulkApplyTemplateWsRequest setOrganization(@Nullable String s) {
+ this.organization = s;
+ return this;
+ }
+
@CheckForNull
public String getTemplateName() {
return templateName;