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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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.lang3.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. validations.validateScope(settingData);
  188. validations.validateQualifier(settingData);
  189. validations.validateValueType(settingData);
  190. }
  191. private static void validatePropertySet(SetRequest request, @Nullable PropertyDefinition definition) {
  192. checkRequest(definition != null, "Setting '%s' is undefined", request.getKey());
  193. checkRequest(PropertyType.PROPERTY_SET.equals(definition.type()), "Parameter '%s' is used for setting of property set type only", PARAM_FIELD_VALUES);
  194. Set<String> fieldKeys = definition.fields().stream().map(PropertyFieldDefinition::key).collect(Collectors.toSet());
  195. ListMultimap<String, String> valuesByFieldKeys = ArrayListMultimap.create(fieldKeys.size(), request.getFieldValues().size() * fieldKeys.size());
  196. List<Map<String, String>> maps = request.getFieldValues().stream()
  197. .map(oneFieldValues -> readOneFieldValues(oneFieldValues, request.getKey()))
  198. .toList();
  199. for (Map<String, String> map : maps) {
  200. checkRequest(map.values().stream().anyMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE);
  201. }
  202. List<Map.Entry<String, String>> entries = maps.stream().flatMap(map -> map.entrySet().stream()).toList();
  203. entries.forEach(entry -> valuesByFieldKeys.put(entry.getKey(), entry.getValue()));
  204. entries.forEach(entry -> checkRequest(fieldKeys.contains(entry.getKey()), "Unknown field key '%s' for setting '%s'", entry.getKey(), request.getKey()));
  205. checkFieldType(request, definition, valuesByFieldKeys);
  206. }
  207. private void validate(SetRequest request) {
  208. PropertyDefinition definition = propertyDefinitions.get(request.getKey());
  209. if (definition == null) {
  210. return;
  211. }
  212. checkSingleOrMultiValue(request, definition);
  213. }
  214. private static void checkFieldType(SetRequest request, PropertyDefinition definition, ListMultimap<String, String> valuesByFieldKeys) {
  215. for (PropertyFieldDefinition fieldDefinition : definition.fields()) {
  216. for (String value : valuesByFieldKeys.get(fieldDefinition.key())) {
  217. PropertyDefinition.Result result = fieldDefinition.validate(value);
  218. checkRequest(result.isValid(),
  219. "Error when validating setting with key '%s'. Field '%s' has incorrect value '%s'.",
  220. request.getKey(), fieldDefinition.key(), value);
  221. }
  222. }
  223. }
  224. private static void checkSingleOrMultiValue(SetRequest request, PropertyDefinition definition) {
  225. checkRequest(definition.multiValues() ^ request.getValue() != null,
  226. "Parameter '%s' must be used for single value setting. Parameter '%s' must be used for multi value setting.", PARAM_VALUE, PARAM_VALUES);
  227. }
  228. private static void checkValueIsSet(SetRequest request) {
  229. checkRequest(
  230. request.getValue() != null
  231. ^ !request.getValues().isEmpty()
  232. ^ !request.getFieldValues().isEmpty(),
  233. "Either '%s', '%s' or '%s' must be provided", PARAM_VALUE, PARAM_VALUES, PARAM_FIELD_VALUES);
  234. checkRequest(request.getValues().stream().allMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE);
  235. checkRequest(request.getValue() == null || StringUtils.isNotBlank(request.getValue()), MSG_NO_EMPTY_VALUE);
  236. }
  237. private static List<String> valuesFromRequest(SetRequest request) {
  238. return request.getValue() == null ? request.getValues() : Collections.singletonList(request.getValue());
  239. }
  240. private String persistedKey(SetRequest request) {
  241. PropertyDefinition definition = propertyDefinitions.get(request.getKey());
  242. // handles deprecated key but persist the new key
  243. return definition == null ? request.getKey() : definition.key();
  244. }
  245. private static String persistedValue(SetRequest request) {
  246. return request.getValue() == null
  247. ? request.getValues().stream().map(value -> value.replace(",", "%2C")).collect(COMMA_JOINER)
  248. : request.getValue();
  249. }
  250. private void checkPermissions(Optional<EntityDto> entity) {
  251. if (entity.isPresent()) {
  252. userSession.checkEntityPermission(UserRole.ADMIN, entity.get());
  253. } else {
  254. userSession.checkIsSystemAdministrator();
  255. }
  256. }
  257. private static SetRequest toWsRequest(Request request) {
  258. SetRequest set = new SetRequest()
  259. .setKey(request.mandatoryParam(PARAM_KEY))
  260. .setValue(request.param(PARAM_VALUE))
  261. .setValues(request.multiParam(PARAM_VALUES))
  262. .setFieldValues(request.multiParam(PARAM_FIELD_VALUES))
  263. .setEntity(request.param(PARAM_COMPONENT));
  264. checkArgument(set.getValues() != null, "Setting values must not be null");
  265. checkArgument(set.getFieldValues() != null, "Setting fields values must not be null");
  266. return set;
  267. }
  268. private static Map<String, String> readOneFieldValues(String json, String key) {
  269. Gson gson = GsonHelper.create();
  270. try {
  271. return gson.fromJson(json, MAP_TYPE_TOKEN);
  272. } catch (JsonSyntaxException e) {
  273. throw BadRequestException.create(format("JSON '%s' does not respect expected format for setting '%s'. Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}", json, key));
  274. }
  275. }
  276. private Optional<EntityDto> searchEntity(DbSession dbSession, SetRequest request) {
  277. String entityKey = request.getEntity();
  278. if (entityKey == null) {
  279. return Optional.empty();
  280. }
  281. return Optional.of(dbClient.entityDao().selectByKey(dbSession, entityKey)
  282. .orElseThrow(() -> new NotFoundException(format("Component key '%s' not found", entityKey))));
  283. }
  284. private PropertyDto toProperty(SetRequest request, Optional<EntityDto> entity) {
  285. String key = persistedKey(request);
  286. String value = persistedValue(request);
  287. PropertyDto property = new PropertyDto()
  288. .setKey(key)
  289. .setValue(value);
  290. if (entity.isPresent()) {
  291. property.setEntityUuid(entity.get().getUuid());
  292. }
  293. return property;
  294. }
  295. private static PropertyDto toFieldProperty(KeyValue keyValue, @Nullable String componentUuid) {
  296. return new PropertyDto().setKey(keyValue.key).setValue(keyValue.value).setEntityUuid(componentUuid);
  297. }
  298. private static class KeyValue {
  299. private final String key;
  300. private final String value;
  301. private KeyValue(String key, String value) {
  302. this.key = key;
  303. this.value = value;
  304. }
  305. }
  306. private static class SetRequest {
  307. private String entity;
  308. private List<String> fieldValues;
  309. private String key;
  310. private String value;
  311. private List<String> values;
  312. public SetRequest setEntity(@Nullable String entity) {
  313. this.entity = entity;
  314. return this;
  315. }
  316. @CheckForNull
  317. public String getEntity() {
  318. return entity;
  319. }
  320. public SetRequest setFieldValues(List<String> fieldValues) {
  321. this.fieldValues = fieldValues;
  322. return this;
  323. }
  324. public List<String> getFieldValues() {
  325. return fieldValues;
  326. }
  327. public SetRequest setKey(String key) {
  328. this.key = key;
  329. return this;
  330. }
  331. public String getKey() {
  332. return key;
  333. }
  334. public SetRequest setValue(@Nullable String value) {
  335. this.value = value;
  336. return this;
  337. }
  338. @CheckForNull
  339. public String getValue() {
  340. return value;
  341. }
  342. public SetRequest setValues(@Nullable List<String> values) {
  343. this.values = values;
  344. return this;
  345. }
  346. public List<String> getValues() {
  347. return values;
  348. }
  349. }
  350. }