You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SetAction.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 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.setting.ws;
  21. import com.google.common.collect.ArrayListMultimap;
  22. import com.google.common.collect.ListMultimap;
  23. import com.google.gson.Gson;
  24. import com.google.gson.JsonSyntaxException;
  25. import com.google.gson.reflect.TypeToken;
  26. import java.util.Collections;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Optional;
  30. import java.util.Set;
  31. import java.util.stream.Collector;
  32. import java.util.stream.Collectors;
  33. import java.util.stream.IntStream;
  34. import javax.annotation.CheckForNull;
  35. import javax.annotation.Nullable;
  36. import org.apache.commons.lang.StringUtils;
  37. import org.sonar.api.PropertyType;
  38. import org.sonar.api.config.PropertyDefinition;
  39. import org.sonar.api.config.PropertyDefinitions;
  40. import org.sonar.api.config.PropertyFieldDefinition;
  41. import org.sonar.api.server.ws.Change;
  42. import org.sonar.api.server.ws.Request;
  43. import org.sonar.api.server.ws.Response;
  44. import org.sonar.api.server.ws.WebService;
  45. import org.sonar.api.web.UserRole;
  46. import org.sonar.db.DbClient;
  47. import org.sonar.db.DbSession;
  48. import org.sonar.db.entity.EntityDto;
  49. import org.sonar.db.property.PropertyDto;
  50. import org.sonar.scanner.protocol.GsonHelper;
  51. import org.sonar.server.exceptions.BadRequestException;
  52. import org.sonar.server.exceptions.NotFoundException;
  53. import org.sonar.server.setting.SettingsChangeNotifier;
  54. import org.sonar.server.setting.ws.SettingValidations.SettingData;
  55. import org.sonar.server.user.UserSession;
  56. import static com.google.common.base.Preconditions.checkArgument;
  57. import static java.lang.String.format;
  58. import static org.sonar.server.exceptions.BadRequestException.checkRequest;
  59. import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_COMPONENT;
  60. import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_FIELD_VALUES;
  61. import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_KEY;
  62. import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUE;
  63. import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUES;
  64. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
  65. public class SetAction implements SettingsWsAction {
  66. private static final Collector<CharSequence, ?, String> COMMA_JOINER = Collectors.joining(",");
  67. private static final String MSG_NO_EMPTY_VALUE = "A non empty value must be provided";
  68. private static final int VALUE_MAXIMUM_LENGTH = 4000;
  69. private static final TypeToken<Map<String, String>> MAP_TYPE_TOKEN = new TypeToken<>() {
  70. };
  71. private final PropertyDefinitions propertyDefinitions;
  72. private final DbClient dbClient;
  73. private final UserSession userSession;
  74. private final SettingsUpdater settingsUpdater;
  75. private final SettingsChangeNotifier settingsChangeNotifier;
  76. private final SettingValidations validations;
  77. public SetAction(PropertyDefinitions propertyDefinitions, DbClient dbClient, UserSession userSession,
  78. SettingsUpdater settingsUpdater, SettingsChangeNotifier settingsChangeNotifier, SettingValidations validations) {
  79. this.propertyDefinitions = propertyDefinitions;
  80. this.dbClient = dbClient;
  81. this.userSession = userSession;
  82. this.settingsUpdater = settingsUpdater;
  83. this.settingsChangeNotifier = settingsChangeNotifier;
  84. this.validations = validations;
  85. }
  86. @Override
  87. public void define(WebService.NewController context) {
  88. WebService.NewAction action = context.createAction("set")
  89. .setDescription("Update a setting value.<br>" +
  90. "Either '%s' or '%s' must be provided.<br> " +
  91. "The settings defined in conf/sonar.properties are read-only and can't be changed.<br/>" +
  92. "Requires one of the following permissions: " +
  93. "<ul>" +
  94. "<li>'Administer System'</li>" +
  95. "<li>'Administer' rights on the specified component</li>" +
  96. "</ul>",
  97. PARAM_VALUE, PARAM_VALUES)
  98. .setSince("6.1")
  99. .setChangelog(
  100. new Change("10.1", "Param 'component' now only accept keys for projects, applications, portfolios or subportfolios"),
  101. new Change("10.1", format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)),
  102. new Change("8.8", "Deprecated parameter 'componentKey' has been removed"),
  103. new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)),
  104. new Change("7.1", "The settings defined in conf/sonar.properties are read-only and can't be changed"))
  105. .setPost(true)
  106. .setHandler(this);
  107. action.createParam(PARAM_KEY)
  108. .setDescription("Setting key")
  109. .setExampleValue("sonar.core.serverBaseURL")
  110. .setRequired(true);
  111. action.createParam(PARAM_VALUE)
  112. .setMaximumLength(VALUE_MAXIMUM_LENGTH)
  113. .setDescription("Setting value. To reset a value, please use the reset web service.")
  114. .setExampleValue("http://my-sonarqube-instance.com");
  115. action.createParam(PARAM_VALUES)
  116. .setDescription("Setting multi value. To set several values, the parameter must be called once for each value.")
  117. .setExampleValue("values=firstValue&values=secondValue&values=thirdValue");
  118. action.createParam(PARAM_FIELD_VALUES)
  119. .setDescription("Setting field values. To set several values, the parameter must be called once for each value.")
  120. .setExampleValue(PARAM_FIELD_VALUES + "={\"firstField\":\"first value\", \"secondField\":\"second value\", \"thirdField\":\"third value\"}");
  121. action.createParam(PARAM_COMPONENT)
  122. .setDescription("Component key. Only keys for projects, applications, portfolios or subportfolios are accepted.")
  123. .setExampleValue(KEY_PROJECT_EXAMPLE_001);
  124. }
  125. @Override
  126. public void handle(Request request, Response response) throws Exception {
  127. try (DbSession dbSession = dbClient.openSession(false)) {
  128. SetRequest wsRequest = toWsRequest(request);
  129. SettingsWsSupport.validateKey(wsRequest.getKey());
  130. doHandle(dbSession, wsRequest);
  131. }
  132. response.noContent();
  133. }
  134. private void doHandle(DbSession dbSession, SetRequest request) {
  135. Optional<EntityDto> component = searchEntity(dbSession, request);
  136. String projectKey = component.map(EntityDto::getKey).orElse(null);
  137. String projectName = component.map(EntityDto::getName).orElse(null);
  138. String qualifier = component.map(EntityDto::getQualifier).orElse(null);
  139. checkPermissions(component);
  140. PropertyDefinition definition = propertyDefinitions.get(request.getKey());
  141. String value;
  142. commonChecks(request, component);
  143. if (!request.getFieldValues().isEmpty()) {
  144. value = doHandlePropertySet(dbSession, request, definition, component);
  145. } else {
  146. validate(request);
  147. PropertyDto property = toProperty(request, component);
  148. value = property.getValue();
  149. dbClient.propertiesDao().saveProperty(dbSession, property, null, projectKey, projectName, qualifier);
  150. }
  151. dbSession.commit();
  152. if (!component.isPresent()) {
  153. settingsChangeNotifier.onGlobalPropertyChange(persistedKey(request), value);
  154. }
  155. }
  156. private String doHandlePropertySet(DbSession dbSession, SetRequest request, @Nullable PropertyDefinition definition, Optional<EntityDto> component) {
  157. validatePropertySet(request, definition);
  158. int[] fieldIds = IntStream.rangeClosed(1, request.getFieldValues().size()).toArray();
  159. String inlinedFieldKeys = IntStream.of(fieldIds).mapToObj(String::valueOf).collect(COMMA_JOINER);
  160. String key = persistedKey(request);
  161. String componentUuid = component.isPresent() ? component.get().getUuid() : null;
  162. String componentKey = component.isPresent() ? component.get().getKey() : null;
  163. String componentName = component.isPresent() ? component.get().getName() : null;
  164. String qualifier = component.isPresent() ? component.get().getQualifier() : null;
  165. deleteSettings(dbSession, component, key);
  166. dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey(key).setValue(inlinedFieldKeys)
  167. .setEntityUuid(componentUuid), null, componentKey, componentName, qualifier);
  168. List<String> fieldValues = request.getFieldValues();
  169. IntStream.of(fieldIds).boxed()
  170. .flatMap(i -> readOneFieldValues(fieldValues.get(i - 1), request.getKey()).entrySet().stream()
  171. .map(entry -> new KeyValue(key + "." + i + "." + entry.getKey(), entry.getValue())))
  172. .forEach(keyValue -> dbClient.propertiesDao().saveProperty(dbSession, toFieldProperty(keyValue, componentUuid),
  173. null, componentKey, componentName, qualifier));
  174. return inlinedFieldKeys;
  175. }
  176. private void deleteSettings(DbSession dbSession, Optional<EntityDto> component, String key) {
  177. if (component.isPresent()) {
  178. settingsUpdater.deleteComponentSettings(dbSession, component.get(), key);
  179. } else {
  180. settingsUpdater.deleteGlobalSettings(dbSession, key);
  181. }
  182. }
  183. private void commonChecks(SetRequest request, Optional<EntityDto> entity) {
  184. checkValueIsSet(request);
  185. String settingKey = request.getKey();
  186. SettingData settingData = new SettingData(settingKey, valuesFromRequest(request), entity.orElse(null));
  187. List.of(validations.scope(), validations.qualifier(), validations.valueType())
  188. .forEach(validation -> validation.accept(settingData));
  189. }
  190. private static void validatePropertySet(SetRequest request, @Nullable PropertyDefinition definition) {
  191. checkRequest(definition != null, "Setting '%s' is undefined", request.getKey());
  192. checkRequest(PropertyType.PROPERTY_SET.equals(definition.type()), "Parameter '%s' is used for setting of property set type only", PARAM_FIELD_VALUES);
  193. Set<String> fieldKeys = definition.fields().stream().map(PropertyFieldDefinition::key).collect(Collectors.toSet());
  194. ListMultimap<String, String> valuesByFieldKeys = ArrayListMultimap.create(fieldKeys.size(), request.getFieldValues().size() * fieldKeys.size());
  195. List<Map<String, String>> maps = request.getFieldValues().stream()
  196. .map(oneFieldValues -> readOneFieldValues(oneFieldValues, request.getKey()))
  197. .toList();
  198. for (Map<String, String> map : maps) {
  199. checkRequest(map.values().stream().anyMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE);
  200. }
  201. List<Map.Entry<String, String>> entries = maps.stream().flatMap(map -> map.entrySet().stream()).toList();
  202. entries.forEach(entry -> valuesByFieldKeys.put(entry.getKey(), entry.getValue()));
  203. entries.forEach(entry -> checkRequest(fieldKeys.contains(entry.getKey()), "Unknown field key '%s' for setting '%s'", entry.getKey(), request.getKey()));
  204. checkFieldType(request, definition, valuesByFieldKeys);
  205. }
  206. private void validate(SetRequest request) {
  207. PropertyDefinition definition = propertyDefinitions.get(request.getKey());
  208. if (definition == null) {
  209. return;
  210. }
  211. checkSingleOrMultiValue(request, definition);
  212. }
  213. private static void checkFieldType(SetRequest request, PropertyDefinition definition, ListMultimap<String, String> valuesByFieldKeys) {
  214. for (PropertyFieldDefinition fieldDefinition : definition.fields()) {
  215. for (String value : valuesByFieldKeys.get(fieldDefinition.key())) {
  216. PropertyDefinition.Result result = fieldDefinition.validate(value);
  217. checkRequest(result.isValid(),
  218. "Error when validating setting with key '%s'. Field '%s' has incorrect value '%s'.",
  219. request.getKey(), fieldDefinition.key(), value);
  220. }
  221. }
  222. }
  223. private static void checkSingleOrMultiValue(SetRequest request, PropertyDefinition definition) {
  224. checkRequest(definition.multiValues() ^ request.getValue() != null,
  225. "Parameter '%s' must be used for single value setting. Parameter '%s' must be used for multi value setting.", PARAM_VALUE, PARAM_VALUES);
  226. }
  227. private static void checkValueIsSet(SetRequest request) {
  228. checkRequest(
  229. request.getValue() != null
  230. ^ !request.getValues().isEmpty()
  231. ^ !request.getFieldValues().isEmpty(),
  232. "Either '%s', '%s' or '%s' must be provided", PARAM_VALUE, PARAM_VALUES, PARAM_FIELD_VALUES);
  233. checkRequest(request.getValues().stream().allMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE);
  234. checkRequest(request.getValue() == null || StringUtils.isNotBlank(request.getValue()), MSG_NO_EMPTY_VALUE);
  235. }
  236. private static List<String> valuesFromRequest(SetRequest request) {
  237. return request.getValue() == null ? request.getValues() : Collections.singletonList(request.getValue());
  238. }
  239. private String persistedKey(SetRequest request) {
  240. PropertyDefinition definition = propertyDefinitions.get(request.getKey());
  241. // handles deprecated key but persist the new key
  242. return definition == null ? request.getKey() : definition.key();
  243. }
  244. private static String persistedValue(SetRequest request) {
  245. return request.getValue() == null
  246. ? request.getValues().stream().map(value -> value.replace(",", "%2C")).collect(COMMA_JOINER)
  247. : request.getValue();
  248. }
  249. private void checkPermissions(Optional<EntityDto> entity) {
  250. if (entity.isPresent()) {
  251. userSession.checkEntityPermission(UserRole.ADMIN, entity.get());
  252. } else {
  253. userSession.checkIsSystemAdministrator();
  254. }
  255. }
  256. private static SetRequest toWsRequest(Request request) {
  257. SetRequest set = new SetRequest()
  258. .setKey(request.mandatoryParam(PARAM_KEY))
  259. .setValue(request.param(PARAM_VALUE))
  260. .setValues(request.multiParam(PARAM_VALUES))
  261. .setFieldValues(request.multiParam(PARAM_FIELD_VALUES))
  262. .setEntity(request.param(PARAM_COMPONENT));
  263. checkArgument(set.getValues() != null, "Setting values must not be null");
  264. checkArgument(set.getFieldValues() != null, "Setting fields values must not be null");
  265. return set;
  266. }
  267. private static Map<String, String> readOneFieldValues(String json, String key) {
  268. Gson gson = GsonHelper.create();
  269. try {
  270. return gson.fromJson(json, MAP_TYPE_TOKEN);
  271. } catch (JsonSyntaxException e) {
  272. throw BadRequestException.create(format("JSON '%s' does not respect expected format for setting '%s'. Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}", json, key));
  273. }
  274. }
  275. private Optional<EntityDto> searchEntity(DbSession dbSession, SetRequest request) {
  276. String entityKey = request.getEntity();
  277. if (entityKey == null) {
  278. return Optional.empty();
  279. }
  280. return Optional.of(dbClient.entityDao().selectByKey(dbSession, entityKey)
  281. .orElseThrow(() -> new NotFoundException(format("Component key '%s' not found", entityKey))));
  282. }
  283. private PropertyDto toProperty(SetRequest request, Optional<EntityDto> entity) {
  284. String key = persistedKey(request);
  285. String value = persistedValue(request);
  286. PropertyDto property = new PropertyDto()
  287. .setKey(key)
  288. .setValue(value);
  289. if (entity.isPresent()) {
  290. property.setEntityUuid(entity.get().getUuid());
  291. }
  292. return property;
  293. }
  294. private static PropertyDto toFieldProperty(KeyValue keyValue, @Nullable String componentUuid) {
  295. return new PropertyDto().setKey(keyValue.key).setValue(keyValue.value).setEntityUuid(componentUuid);
  296. }
  297. private static class KeyValue {
  298. private final String key;
  299. private final String value;
  300. private KeyValue(String key, String value) {
  301. this.key = key;
  302. this.value = value;
  303. }
  304. }
  305. private static class SetRequest {
  306. private String entity;
  307. private List<String> fieldValues;
  308. private String key;
  309. private String value;
  310. private List<String> values;
  311. public SetRequest setEntity(@Nullable String entity) {
  312. this.entity = entity;
  313. return this;
  314. }
  315. @CheckForNull
  316. public String getEntity() {
  317. return entity;
  318. }
  319. public SetRequest setFieldValues(List<String> fieldValues) {
  320. this.fieldValues = fieldValues;
  321. return this;
  322. }
  323. public List<String> getFieldValues() {
  324. return fieldValues;
  325. }
  326. public SetRequest setKey(String key) {
  327. this.key = key;
  328. return this;
  329. }
  330. public String getKey() {
  331. return key;
  332. }
  333. public SetRequest setValue(@Nullable String value) {
  334. this.value = value;
  335. return this;
  336. }
  337. @CheckForNull
  338. public String getValue() {
  339. return value;
  340. }
  341. public SetRequest setValues(@Nullable List<String> values) {
  342. this.values = values;
  343. return this;
  344. }
  345. public List<String> getValues() {
  346. return values;
  347. }
  348. }
  349. }