]> source.dussan.org Git - sonarqube.git/blob
62df55b54b72cb096a03e813e5c3fe9c98b5b64b
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2023 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 3 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19  */
20 package org.sonar.server.permission.ws.template;
21
22 import java.util.Collection;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.stream.Collectors;
27 import javax.annotation.CheckForNull;
28 import javax.annotation.Nullable;
29 import org.sonar.api.resources.Qualifiers;
30 import org.sonar.api.resources.ResourceTypes;
31 import org.sonar.api.server.ws.Change;
32 import org.sonar.api.server.ws.Request;
33 import org.sonar.api.server.ws.Response;
34 import org.sonar.api.server.ws.WebService;
35 import org.sonar.api.server.ws.WebService.Param;
36 import org.sonar.core.i18n.I18n;
37 import org.sonar.db.DatabaseUtils;
38 import org.sonar.db.DbClient;
39 import org.sonar.db.DbSession;
40 import org.sonar.db.component.ComponentDto;
41 import org.sonar.db.component.ComponentQuery;
42 import org.sonar.db.entity.EntityDto;
43 import org.sonar.db.permission.template.PermissionTemplateDto;
44 import org.sonar.server.management.ManagedProjectService;
45 import org.sonar.server.permission.PermissionTemplateService;
46 import org.sonar.server.permission.ws.PermissionWsSupport;
47 import org.sonar.server.permission.ws.PermissionsWsAction;
48 import org.sonar.server.permission.ws.WsParameters;
49 import org.sonar.server.project.Visibility;
50 import org.sonar.server.user.UserSession;
51
52 import static java.lang.String.format;
53 import static java.util.Collections.singleton;
54 import static java.util.Objects.requireNonNull;
55 import static java.util.Optional.ofNullable;
56 import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
57 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
58 import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
59 import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
60 import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
61 import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
62 import static org.sonar.server.ws.WsParameterBuilder.createRootQualifiersParameter;
63 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
64 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
65 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
66 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
67 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
68 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
69 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
70
71 public class BulkApplyTemplateAction implements PermissionsWsAction {
72
73   private final DbClient dbClient;
74   private final UserSession userSession;
75   private final PermissionTemplateService permissionTemplateService;
76   private final PermissionWsSupport wsSupport;
77   private final I18n i18n;
78   private final ResourceTypes resourceTypes;
79   private final ManagedProjectService managedProjectService;
80
81   public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionTemplateService permissionTemplateService, PermissionWsSupport wsSupport, I18n i18n,
82     ResourceTypes resourceTypes, ManagedProjectService managedProjectService) {
83     this.dbClient = dbClient;
84     this.userSession = userSession;
85     this.permissionTemplateService = permissionTemplateService;
86     this.wsSupport = wsSupport;
87     this.i18n = i18n;
88     this.resourceTypes = resourceTypes;
89     this.managedProjectService = managedProjectService;
90   }
91
92   @Override
93   public void define(WebService.NewController context) {
94     WebService.NewAction action = context.createAction("bulk_apply_template")
95       .setDescription("Apply a permission template to several components. Managed projects will be ignored.<br />" +
96         "The template id or name must be provided.<br />" +
97         "Requires the following permission: 'Administer System'.")
98       .setPost(true)
99       .setSince("5.5")
100       .setChangelog(new Change("6.7.2", format("Parameter %s accepts maximum %d values", PARAM_PROJECTS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)))
101       .setHandler(this);
102
103     action.createParam(Param.TEXT_QUERY)
104       .setDescription("Limit search to: <ul>" +
105         "<li>project names that contain the supplied string</li>" +
106         "<li>project keys that are exactly the same as the supplied string</li>" +
107         "</ul>")
108       .setExampleValue("apac");
109
110     createRootQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes))
111       .setDefaultValue(Qualifiers.PROJECT);
112
113     WsParameters.createTemplateParameters(action);
114
115     action
116       .createParam(PARAM_PROJECTS)
117       .setDescription("Comma-separated list of project keys")
118       .setSince("6.6")
119       // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
120       // Restricting size of HTTP parameter allows to not fail with SQL error
121       .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
122       .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
123
124     action.createParam(PARAM_VISIBILITY)
125       .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
126           "If no visibility is specified, the default project visibility will be used.",
127         Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
128       .setRequired(false)
129       .setInternal(true)
130       .setSince("6.6")
131       .setPossibleValues(Visibility.getLabels());
132
133     action.createParam(PARAM_ANALYZED_BEFORE)
134       .setDescription("Filter the projects for which last analysis is older than the given date (exclusive).<br> " +
135         "Either a date (server timezone) or datetime can be provided.")
136       .setSince("6.6")
137       .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
138
139     action.createParam(PARAM_ON_PROVISIONED_ONLY)
140       .setDescription("Filter the projects that are provisioned")
141       .setBooleanPossibleValues()
142       .setDefaultValue("false")
143       .setSince("6.6");
144   }
145
146   @Override
147   public void handle(Request request, Response response) throws Exception {
148     doHandle(toBulkApplyTemplateWsRequest(request));
149     response.noContent();
150   }
151
152   private void doHandle(BulkApplyTemplateRequest request) {
153     try (DbSession dbSession = dbClient.openSession(false)) {
154       PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
155         request.getTemplateId(), request.getTemplateName()));
156       checkGlobalAdmin(userSession);
157
158       ComponentQuery componentQuery = buildDbQuery(request);
159       List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
160
161       Set<String> entityUuids = components.stream()
162         .map(ComponentDto::getKey)
163         .collect(Collectors.toSet());
164       List<EntityDto> entities = dbClient.entityDao().selectByKeys(dbSession, entityUuids).stream()
165         .filter(entity -> !managedProjectService.isProjectManaged(dbSession, entity.getUuid()))
166         .toList();
167
168       permissionTemplateService.applyAndCommit(dbSession, template, entities);
169     }
170   }
171
172   private static BulkApplyTemplateRequest toBulkApplyTemplateWsRequest(Request request) {
173     return new BulkApplyTemplateRequest()
174       .setTemplateId(request.param(PARAM_TEMPLATE_ID))
175       .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
176       .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
177       .setQuery(request.param(Param.TEXT_QUERY))
178       .setVisibility(request.param(PARAM_VISIBILITY))
179       .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
180       .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
181       .setProjects(request.paramAsStrings(PARAM_PROJECTS));
182   }
183
184   private static ComponentQuery buildDbQuery(BulkApplyTemplateRequest request) {
185     Collection<String> qualifiers = request.getQualifiers();
186     ComponentQuery.Builder query = ComponentQuery.builder()
187       .setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
188
189     ofNullable(request.getQuery()).ifPresent(q -> {
190       query.setNameOrKeyQuery(q);
191       query.setPartialMatchOnKey(true);
192     });
193     ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
194     ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAnalyzedBefore(parseDateOrDateTime(d).getTime()));
195     query.setOnProvisionedOnly(request.isOnProvisionedOnly());
196     ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
197
198     return query.build();
199   }
200
201   private static class BulkApplyTemplateRequest {
202     private String templateId;
203     private String templateName;
204     private String query;
205     private Collection<String> qualifiers = singleton(Qualifiers.PROJECT);
206     private String visibility;
207     private String analyzedBefore;
208     private boolean onProvisionedOnly = false;
209     private Collection<String> projects;
210
211     @CheckForNull
212     public String getTemplateId() {
213       return templateId;
214     }
215
216     public BulkApplyTemplateRequest setTemplateId(@Nullable String templateId) {
217       this.templateId = templateId;
218       return this;
219     }
220
221     @CheckForNull
222     public String getTemplateName() {
223       return templateName;
224     }
225
226     public BulkApplyTemplateRequest setTemplateName(@Nullable String templateName) {
227       this.templateName = templateName;
228       return this;
229     }
230
231     @CheckForNull
232     public String getQuery() {
233       return query;
234     }
235
236     public BulkApplyTemplateRequest setQuery(@Nullable String query) {
237       this.query = query;
238       return this;
239     }
240
241     public Collection<String> getQualifiers() {
242       return qualifiers;
243     }
244
245     public BulkApplyTemplateRequest setQualifiers(Collection<String> qualifiers) {
246       this.qualifiers = requireNonNull(qualifiers);
247       return this;
248     }
249
250     @CheckForNull
251     public String getVisibility() {
252       return visibility;
253     }
254
255     public BulkApplyTemplateRequest setVisibility(@Nullable String visibility) {
256       this.visibility = visibility;
257       return this;
258     }
259
260     @CheckForNull
261     public String getAnalyzedBefore() {
262       return analyzedBefore;
263     }
264
265     public BulkApplyTemplateRequest setAnalyzedBefore(@Nullable String analyzedBefore) {
266       this.analyzedBefore = analyzedBefore;
267       return this;
268     }
269
270     public boolean isOnProvisionedOnly() {
271       return onProvisionedOnly;
272     }
273
274     public BulkApplyTemplateRequest setOnProvisionedOnly(boolean onProvisionedOnly) {
275       this.onProvisionedOnly = onProvisionedOnly;
276       return this;
277     }
278
279     @CheckForNull
280     public Collection<String> getProjects() {
281       return projects;
282     }
283
284     public BulkApplyTemplateRequest setProjects(@Nullable Collection<String> projects) {
285       this.projects = projects;
286       return this;
287     }
288   }
289 }