repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.ui; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/page/CorePageDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.page; import org.sonar.api.ExtensionPoint; import org.sonar.api.server.ServerSide; import org.sonar.api.web.page.PageDefinition; /** * This class must be used by core extensions to declare {@link PageDefinition}(s). * <p> * This allows to distinguish {@link PageDefinition} provided by plugins from those provided by Core Extensions and * apply the appropriate security and consistency checks. */ @ServerSide @ExtensionPoint public interface CorePageDefinition { PageDefinition getPageDefinition(); }
1,382
35.394737
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/page/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.ui.page; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import com.google.common.collect.Lists; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.config.Configuration; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.resources.Scopes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.web.UserRole; import org.sonar.api.web.page.Page; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.project.Visibility; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.qualityprofile.QPMeasureData; import org.sonar.server.qualityprofile.QualityProfile; import org.sonar.server.ui.PageRepository; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Collections.emptySortedSet; import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY; import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_KEY; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; public class ComponentAction implements NavigationWsAction { private static final Set<String> MODULE_OR_DIR_QUALIFIERS = Set.of(Qualifiers.MODULE, Qualifiers.DIRECTORY); static final String PARAM_COMPONENT = "component"; private static final String PARAM_BRANCH = "branch"; private static final String PARAM_PULL_REQUEST = "pullRequest"; private static final String PROPERTY_CONFIGURABLE = "configurable"; private static final String PROPERTY_HAS_ROLE_POLICY = "hasRolePolicy"; private static final String PROPERTY_MODIFIABLE_HISTORY = "modifiable_history"; private static final String PROPERTY_UPDATABLE_KEY = "updatable_key"; /** * The concept of "visibility" will only be configured for these qualifiers. */ private static final Set<String> QUALIFIERS_WITH_VISIBILITY = Set.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP); private final DbClient dbClient; private final PageRepository pageRepository; private final ResourceTypes resourceTypes; private final UserSession userSession; private final ComponentFinder componentFinder; private final QualityGateFinder qualityGateFinder; private final Configuration config; public ComponentAction(DbClient dbClient, PageRepository pageRepository, ResourceTypes resourceTypes, UserSession userSession, ComponentFinder componentFinder, QualityGateFinder qualityGateFinder, Configuration config) { this.dbClient = dbClient; this.pageRepository = pageRepository; this.resourceTypes = resourceTypes; this.userSession = userSession; this.componentFinder = componentFinder; this.qualityGateFinder = qualityGateFinder; this.config = config; } @Override public void define(NewController context) { NewAction action = context.createAction("component") .setDescription("Get information concerning component navigation for the current user. " + "Requires the 'Browse' permission on the component's project. <br>" + "For applications, it also requires 'Browse' permission on its child projects.") .setHandler(this) .setInternal(true) .setResponseExample(getClass().getResource("component-example.json")) .setSince("5.2") .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("8.8", "Deprecated parameter 'componentKey' has been removed. Please use parameter 'component' instead"), new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)), new Change("7.3", "The 'almRepoUrl' and 'almId' fields are added"), new Change("6.4", "The 'visibility' field is added")); action.createParam(PARAM_COMPONENT) .setDescription("A component key.") .setExampleValue(KEY_PROJECT_EXAMPLE_001); action .createParam(PARAM_BRANCH) .setDescription("Branch key") .setExampleValue(KEY_BRANCH_EXAMPLE_001); action .createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { String componentKey = request.mandatoryParam(PARAM_COMPONENT); try (DbSession session = dbClient.openSession(false)) { String branch = request.param(PARAM_BRANCH); String pullRequest = request.param(PARAM_PULL_REQUEST); ComponentDto component = componentFinder.getByKeyAndOptionalBranchOrPullRequest(session, componentKey, branch, pullRequest); checkComponentNotAModuleAndNotADirectory(component); ComponentDto rootComponent = getRootProjectOrBranch(component, session); // will be empty for portfolios Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(session, rootComponent.branchUuid()); String projectOrPortfolioUuid = branchDto.map(BranchDto::getProjectUuid).orElse(rootComponent.branchUuid()); if (!userSession.hasComponentPermission(USER, component) && !userSession.hasComponentPermission(ADMIN, component) && !userSession.isSystemAdministrator()) { throw insufficientPrivilegesException(); } Optional<SnapshotDto> analysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, component.branchUuid()); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); boolean isFavourite = isFavourite(session, projectOrPortfolioUuid, component); writeComponent(json, component, analysis.orElse(null), isFavourite, branchDto.map(BranchDto::getBranchKey).orElse(null)); writeProfiles(json, session, component); writeQualityGate(json, session, projectOrPortfolioUuid); if (userSession.hasComponentPermission(ADMIN, component) || userSession.hasPermission(ADMINISTER_QUALITY_PROFILES) || userSession.hasPermission(ADMINISTER_QUALITY_GATES)) { writeConfiguration(json, component); } writeBreadCrumbs(json, session, component); json.endObject().close(); } } } private static void checkComponentNotAModuleAndNotADirectory(ComponentDto component) { BadRequestException.checkRequest(!MODULE_OR_DIR_QUALIFIERS.contains(component.qualifier()), "Operation not supported for module or directory components"); } private ComponentDto getRootProjectOrBranch(ComponentDto component, DbSession session) { if (!component.isRootProject()) { return dbClient.componentDao().selectOrFailByUuid(session, component.branchUuid()); } else { return component; } } private static void writeToJson(JsonWriter json, QualityProfile profile, boolean deleted) { json.beginObject() .prop("key", profile.getQpKey()) .prop("name", profile.getQpName()) .prop("language", profile.getLanguageKey()) .prop("deleted", deleted) .endObject(); } private static void writePage(JsonWriter json, Page page) { json.beginObject() .prop("key", page.getKey()) .prop("name", page.getName()) .endObject(); } private void writeComponent(JsonWriter json, ComponentDto component, @Nullable SnapshotDto analysis, boolean isFavourite, @Nullable String branchKey) { json.prop("key", component.getKey()) .prop("id", component.uuid()) .prop("name", component.name()) .prop("description", component.description()) .prop("isFavorite", isFavourite); if (branchKey != null) { json.prop("branch", branchKey); } if (Qualifiers.APP.equals(component.qualifier())) { json.prop("canBrowseAllChildProjects", userSession.hasChildProjectsPermission(USER, component)); } if (Qualifiers.VIEW.equals(component.qualifier()) || Qualifiers.SUBVIEW.equals(component.qualifier())) { json.prop("canBrowseAllChildProjects", userSession.hasPortfolioChildProjectsPermission(USER, component)); } if (QUALIFIERS_WITH_VISIBILITY.contains(component.qualifier())) { json.prop("visibility", Visibility.getLabel(component.isPrivate())); } List<Page> pages = pageRepository.getComponentPages(false, component.qualifier()); writeExtensions(json, component, pages); if (analysis != null) { json.prop("version", analysis.getProjectVersion()) .prop("analysisDate", formatDateTime(new Date(analysis.getCreatedAt()))); } } private boolean isFavourite(DbSession session, String projectOrPortfolioUuid, ComponentDto component) { PropertyQuery propertyQuery = PropertyQuery.builder() .setUserUuid(userSession.getUuid()) .setKey("favourite") .setEntityUuid(isSubview(component) ? component.uuid() : projectOrPortfolioUuid) .build(); List<PropertyDto> componentFavourites = dbClient.propertiesDao().selectByQuery(propertyQuery, session); return componentFavourites.size() == 1; } private static boolean isSubview(ComponentDto component) { return Qualifiers.SUBVIEW.equals(component.qualifier()) && Scopes.PROJECT.equals(component.scope()); } private void writeProfiles(JsonWriter json, DbSession dbSession, ComponentDto component) { Set<QualityProfile> qualityProfiles = dbClient.liveMeasureDao().selectMeasure(dbSession, component.branchUuid(), QUALITY_PROFILES_KEY) .map(LiveMeasureDto::getDataAsString) .map(data -> QPMeasureData.fromJson(data).getProfiles()) .orElse(emptySortedSet()); Map<String, QProfileDto> dtoByQPKey = dbClient.qualityProfileDao().selectByUuids(dbSession, qualityProfiles.stream().map(QualityProfile::getQpKey).toList()) .stream() .collect(Collectors.toMap(QProfileDto::getKee, Function.identity())); json.name("qualityProfiles").beginArray(); qualityProfiles.forEach(qp -> writeToJson(json, qp, !dtoByQPKey.containsKey(qp.getQpKey()))); json.endArray(); } private void writeQualityGate(JsonWriter json, DbSession session, String projectOrPortfolioUuid) { var qualityGateData = qualityGateFinder.getEffectiveQualityGate(session, projectOrPortfolioUuid); json.name("qualityGate").beginObject() .prop("key", qualityGateData.getUuid()) .prop("name", qualityGateData.getName()) .prop("isDefault", qualityGateData.isDefault()) .endObject(); } private void writeExtensions(JsonWriter json, ComponentDto component, List<Page> pages) { json.name("extensions").beginArray(); Predicate<Page> isAuthorized = page -> { String requiredPermission = page.isAdmin() ? UserRole.ADMIN : UserRole.USER; return userSession.hasComponentPermission(requiredPermission, component); }; pages.stream() .filter(isAuthorized) .forEach(page -> writePage(json, page)); json.endArray(); } private void writeConfiguration(JsonWriter json, ComponentDto component) { boolean isProjectAdmin = userSession.hasComponentPermission(ADMIN, component); json.name("configuration").beginObject(); writeConfigPageAccess(json, isProjectAdmin, component); if (isProjectAdmin) { json.name("extensions").beginArray(); List<Page> configPages = pageRepository.getComponentPages(true, component.qualifier()); configPages.forEach(page -> writePage(json, page)); json.endArray(); } json.endObject(); } private void writeConfigPageAccess(JsonWriter json, boolean isProjectAdmin, ComponentDto component) { boolean isProject = Qualifiers.PROJECT.equals(component.qualifier()); boolean showBackgroundTasks = isProjectAdmin && (isProject || Qualifiers.VIEW.equals(component.qualifier()) || Qualifiers.APP.equals(component.qualifier())); boolean isQualityProfileAdmin = userSession.hasPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); boolean isQualityGateAdmin = userSession.hasPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); boolean isGlobalAdmin = userSession.hasPermission(GlobalPermission.ADMINISTER); boolean canBrowseProject = userSession.hasComponentPermission(USER, component); boolean allowChangingPermissionsByProjectAdmins = config.getBoolean(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY) .orElse(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE); json.prop("showSettings", isProjectAdmin && componentTypeHasProperty(component, PROPERTY_CONFIGURABLE)); json.prop("showQualityProfiles", isProject && (isProjectAdmin || isQualityProfileAdmin)); json.prop("showQualityGates", isProject && (isProjectAdmin || isQualityGateAdmin)); json.prop("showLinks", isProjectAdmin && isProject); json.prop("showPermissions", isProjectAdmin && componentTypeHasProperty(component, PROPERTY_HAS_ROLE_POLICY) && (isGlobalAdmin || allowChangingPermissionsByProjectAdmins)); json.prop("showHistory", isProjectAdmin && componentTypeHasProperty(component, PROPERTY_MODIFIABLE_HISTORY)); json.prop("showUpdateKey", isProjectAdmin && componentTypeHasProperty(component, PROPERTY_UPDATABLE_KEY)); json.prop("showBackgroundTasks", showBackgroundTasks); json.prop("canApplyPermissionTemplate", isGlobalAdmin); json.prop("canBrowseProject", canBrowseProject); json.prop("canUpdateProjectVisibilityToPrivate", isProjectAdmin); } private boolean componentTypeHasProperty(ComponentDto component, String resourceTypeProperty) { ResourceType resourceType = resourceTypes.get(component.qualifier()); return resourceType != null && resourceType.getBooleanProperty(resourceTypeProperty); } private void writeBreadCrumbs(JsonWriter json, DbSession session, ComponentDto component) { json.name("breadcrumbs").beginArray(); List<ComponentDto> breadcrumb = Lists.newArrayList(); breadcrumb.addAll(dbClient.componentDao().selectAncestors(session, component)); breadcrumb.add(component); for (ComponentDto c : breadcrumb) { json.beginObject() .prop("key", c.getKey()) .prop("name", c.name()) .prop("qualifier", c.qualifier()) .endObject(); } json.endArray(); } }
16,618
47.031792
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/GlobalAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.platform.Server; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.web.page.Page; import org.sonar.core.documentation.DocumentationLinkGenerator; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.dialect.H2; import org.sonar.server.authentication.DefaultAdminCredentialsVerifier; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.platform.NodeInformation; import org.sonar.server.ui.PageRepository; import org.sonar.server.ui.VersionFormatter; import org.sonar.server.ui.WebAnalyticsLoader; import org.sonar.server.user.UserSession; import static org.sonar.api.CoreProperties.DEVELOPER_AGGREGATED_INFO_DISABLED; import static org.sonar.api.CoreProperties.RATING_GRID; import static org.sonar.core.config.WebConstants.SONAR_LF_ENABLE_GRAVATAR; import static org.sonar.core.config.WebConstants.SONAR_LF_GRAVATAR_SERVER_URL; import static org.sonar.core.config.WebConstants.SONAR_LF_LOGO_URL; import static org.sonar.core.config.WebConstants.SONAR_LF_LOGO_WIDTH_PX; import static org.sonar.process.ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE; public class GlobalAction implements NavigationWsAction, Startable { private static final Set<String> DYNAMIC_SETTING_KEYS = Set.of( SONAR_LF_LOGO_URL, SONAR_LF_LOGO_WIDTH_PX, SONAR_LF_ENABLE_GRAVATAR, SONAR_LF_GRAVATAR_SERVER_URL, RATING_GRID, DEVELOPER_AGGREGATED_INFO_DISABLED); private final Map<String, String> systemSettingValuesByKey; private final PageRepository pageRepository; private final Configuration config; private final ResourceTypes resourceTypes; private final Server server; private final NodeInformation nodeInformation; private final DbClient dbClient; private final UserSession userSession; private final PlatformEditionProvider editionProvider; private final WebAnalyticsLoader webAnalyticsLoader; private final IssueIndexSyncProgressChecker issueIndexSyncChecker; private final DefaultAdminCredentialsVerifier defaultAdminCredentialsVerifier; private final DocumentationLinkGenerator documentationLinkGenerator; public GlobalAction(PageRepository pageRepository, Configuration config, ResourceTypes resourceTypes, Server server, NodeInformation nodeInformation, DbClient dbClient, UserSession userSession, PlatformEditionProvider editionProvider, WebAnalyticsLoader webAnalyticsLoader, IssueIndexSyncProgressChecker issueIndexSyncChecker, DefaultAdminCredentialsVerifier defaultAdminCredentialsVerifier, DocumentationLinkGenerator documentationLinkGenerator) { this.pageRepository = pageRepository; this.config = config; this.resourceTypes = resourceTypes; this.server = server; this.nodeInformation = nodeInformation; this.dbClient = dbClient; this.userSession = userSession; this.editionProvider = editionProvider; this.webAnalyticsLoader = webAnalyticsLoader; this.systemSettingValuesByKey = new HashMap<>(); this.issueIndexSyncChecker = issueIndexSyncChecker; this.defaultAdminCredentialsVerifier = defaultAdminCredentialsVerifier; this.documentationLinkGenerator = documentationLinkGenerator; } @Override public void start() { this.systemSettingValuesByKey.put(SONAR_UPDATECENTER_ACTIVATE.getKey(), config.get(SONAR_UPDATECENTER_ACTIVATE.getKey()).orElse(null)); } @Override public void stop() { // Nothing to do } @Override public void define(NewController context) { context.createAction("global") .setDescription("Get information concerning global navigation for the current user.") .setHandler(this) .setInternal(true) .setResponseExample(getClass().getResource("global-example.json")) .setSince("5.2"); } @Override public void handle(Request request, Response response) throws Exception { try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); writeActions(json); writePages(json); writeSettings(json); writeDeprecatedLogoProperties(json); writeQualifiers(json); writeVersion(json); writeDatabaseProduction(json); writeInstanceUsesDefaultAdminCredentials(json); editionProvider.get().ifPresent(e -> json.prop("edition", e.name().toLowerCase(Locale.ENGLISH))); writeNeedIssueSync(json); json.prop("standalone", nodeInformation.isStandalone()); writeWebAnalytics(json); writeDocumentationUrl(json); json.endObject(); } } private void writeActions(JsonWriter json) { json.prop("canAdmin", userSession.isSystemAdministrator()); } private void writePages(JsonWriter json) { json.name("globalPages").beginArray(); for (Page page : pageRepository.getGlobalPages(false)) { json.beginObject() .prop("key", page.getKey()) .prop("name", page.getName()) .endObject(); } json.endArray(); } private void writeSettings(JsonWriter json) { json.name("settings").beginObject(); DYNAMIC_SETTING_KEYS.forEach(key -> json.prop(key, config.get(key).orElse(null))); systemSettingValuesByKey.forEach(json::prop); json.endObject(); } private void writeDeprecatedLogoProperties(JsonWriter json) { json.prop("logoUrl", config.get(SONAR_LF_LOGO_URL).orElse(null)); json.prop("logoWidth", config.get(SONAR_LF_LOGO_WIDTH_PX).orElse(null)); } private void writeQualifiers(JsonWriter json) { json.name("qualifiers").beginArray(); for (ResourceType rootType : resourceTypes.getRoots()) { json.value(rootType.getQualifier()); } json.endArray(); } private void writeVersion(JsonWriter json) { String displayVersion = VersionFormatter.format(server.getVersion()); json.prop("version", displayVersion); } private void writeDatabaseProduction(JsonWriter json) { json.prop("productionDatabase", !dbClient.getDatabase().getDialect().getId().equals(H2.ID)); } private void writeInstanceUsesDefaultAdminCredentials(JsonWriter json) { if (userSession.isSystemAdministrator()) { json.prop("instanceUsesDefaultAdminCredentials", defaultAdminCredentialsVerifier.hasDefaultCredentialUser()); } } private void writeNeedIssueSync(JsonWriter json) { try (DbSession dbSession = dbClient.openSession(false)) { json.prop("needIssueSync", issueIndexSyncChecker.isIssueSyncInProgress(dbSession)); } } private void writeWebAnalytics(JsonWriter json) { webAnalyticsLoader.getUrlPathToJs().ifPresent(p -> json.prop("webAnalyticsJsPath", p)); } private void writeDocumentationUrl(JsonWriter json) { json.prop("documentationUrl", documentationLinkGenerator.getDocumentationLink(null)); } }
8,118
38.412621
143
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/MarketplaceAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import org.sonar.api.platform.Server; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Navigation; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class MarketplaceAction implements NavigationWsAction { private final UserSession userSession; private final Server server; private final DbClient dbClient; public MarketplaceAction(UserSession userSession, Server server, DbClient dbClient) { this.userSession = userSession; this.server = server; this.dbClient = dbClient; } @Override public void define(WebService.NewController controller) { controller.createAction("marketplace") .setSince("7.2") .setPost(false) .setDescription("Provide data to prefill license request forms: the server ID and the total number of lines of code.") .setResponseExample(getClass().getResource("marketplace-example.json")) .setInternal(true) .setHandler(this); } @Override public void handle(Request request, Response response) { userSession .checkLoggedIn() .checkIsSystemAdministrator(); Navigation.MarketplaceResponse responsePayload = Navigation.MarketplaceResponse.newBuilder() .setNcloc(computeNcloc()) .setServerId(server.getId()) .build(); writeProtobuf(responsePayload, request, response); } private long computeNcloc() { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.projectDao().getNclocSum(dbSession); } } }
2,563
33.648649
124
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/NavigationWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import org.sonar.api.server.ws.WebService; public class NavigationWs implements WebService { private final NavigationWsAction[] actions; public NavigationWs(NavigationWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController navigation = context.createController("api/navigation") .setDescription("Get information required to build navigation UI components") .setSince("5.2"); for (NavigationWsAction action : actions) { action.define(navigation); } navigation.done(); } }
1,459
30.73913
83
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/NavigationWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import org.sonar.server.ws.WsAction; public interface NavigationWsAction extends WsAction { // Marker interface for navigation related actions }
1,024
36.962963
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/NavigationWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import org.sonar.core.platform.Module; public class NavigationWsModule extends Module { @Override protected void configureModule() { add( NavigationWs.class, ComponentAction.class, GlobalAction.class, MarketplaceAction.class, SettingsAction.class); } }
1,170
32.457143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/SettingsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ui.ws; import org.sonar.api.config.Configuration; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.web.page.Page; import org.sonar.process.ProcessProperties; import org.sonar.server.ui.PageRepository; import org.sonar.server.user.UserSession; public class SettingsAction implements NavigationWsAction { private final PageRepository pageRepository; private final Configuration config; private final UserSession userSession; public SettingsAction(PageRepository pageRepository, Configuration config, UserSession userSession) { this.pageRepository = pageRepository; this.config = config; this.userSession = userSession; } @Override public void define(NewController context) { context.createAction("settings") .setDescription("Get configuration information for the settings page:" + "<ul>" + " <li>List plugin-contributed pages</li>" + " <li>Show update center (or not)</li>" + "</ul>") .setHandler(this) .setInternal(true) .setResponseExample(getClass().getResource("settings-example.json")) .setSince("5.2"); } @Override public void handle(Request request, Response response) throws Exception { boolean isSysAdmin = userSession.isSystemAdministrator(); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); json.prop("showUpdateCenter", isSysAdmin && config.getBoolean(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey()).orElse(false)); json.name("extensions").beginArray(); if (isSysAdmin) { for (Page page : pageRepository.getGlobalPages(true)) { json.beginObject() .prop("key", page.getKey()) .prop("name", page.getName()) .endObject(); } } json.endArray().endObject(); } } }
2,849
35.075949
148
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.ui.ws; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/AnonymizeAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.user.UserSession; import static org.sonar.server.exceptions.NotFoundException.checkFound; public class AnonymizeAction implements UsersWsAction { private static final String PARAM_LOGIN = "login"; private final DbClient dbClient; private final UserSession userSession; private final UserAnonymizer userAnonymizer; public AnonymizeAction(DbClient dbClient, UserSession userSession, UserAnonymizer userAnonymizer) { this.userAnonymizer = userAnonymizer; this.dbClient = dbClient; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("anonymize") .setDescription("Anonymize a deactivated user. Requires Administer System permission") .setSince("9.7") .setPost(true) .setHandler(this); action.createParam(PARAM_LOGIN) .setDescription("User login") .setRequired(true) .setExampleValue("myuser"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); String login = request.mandatoryParam(PARAM_LOGIN); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); checkFound(user, "User '%s' doesn't exist", login); if (user.isActive()) { throw new IllegalArgumentException(String.format("User '%s' is not deactivated", login)); } userAnonymizer.anonymize(dbSession, user); dbClient.userDao().update(dbSession, user); dbSession.commit(); } response.noContent(); } }
2,847
34.160494
101
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/BaseUsersWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import org.sonar.api.server.ws.Definable; import org.sonar.api.server.ws.WebService; public interface BaseUsersWsAction extends Definable<WebService.NewController> { // Marker interface for UsersWs actions }
1,089
37.928571
80
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/ChangePasswordAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonWriter; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Optional; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.CredentialsLocalAuthentication; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UpdateUser; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; import org.sonar.server.ws.ServletFilterHandler; import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonar.server.user.ws.ChangePasswordAction.PasswordMessage.NEW_PASSWORD_SAME_AS_OLD; import static org.sonar.server.user.ws.ChangePasswordAction.PasswordMessage.OLD_PASSWORD_INCORRECT; import static org.sonarqube.ws.MediaTypes.JSON; import static org.sonarqube.ws.WsUtils.isNullOrEmpty; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_PASSWORD; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_PREVIOUS_PASSWORD; public class ChangePasswordAction extends HttpFilter implements BaseUsersWsAction { private static final Logger LOG = LoggerFactory.getLogger(ChangePasswordAction.class); private static final String CHANGE_PASSWORD = "change_password"; private static final String CHANGE_PASSWORD_URL = "/" + UsersWs.API_USERS + "/" + CHANGE_PASSWORD; private static final String MSG_PARAMETER_MISSING = "The '%s' parameter is missing"; private final DbClient dbClient; private final UserUpdater userUpdater; private final UserSession userSession; private final CredentialsLocalAuthentication localAuthentication; private final JwtHttpHandler jwtHttpHandler; public ChangePasswordAction(DbClient dbClient, UserUpdater userUpdater, UserSession userSession, CredentialsLocalAuthentication localAuthentication, JwtHttpHandler jwtHttpHandler) { this.dbClient = dbClient; this.userUpdater = userUpdater; this.userSession = userSession; this.localAuthentication = localAuthentication; this.jwtHttpHandler = jwtHttpHandler; } @Override public UrlPattern doGetPattern() { return UrlPattern.create(CHANGE_PASSWORD_URL); } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(CHANGE_PASSWORD) .setDescription("Update a user's password. Authenticated users can change their own password, " + "provided that the account is not linked to an external authentication system. " + "Administer System permission is required to change another user's password.") .setSince("5.2") .setPost(true) .setHandler(ServletFilterHandler.INSTANCE) .setChangelog(new Change("8.6", "It's no more possible for the password to be the same as the previous one")); action.createParam(PARAM_LOGIN) .setDescription("User login") .setRequired(true) .setExampleValue("myuser"); action.createParam(PARAM_PASSWORD) .setDescription("New password") .setRequired(true) .setExampleValue("mypassword"); action.createParam(PARAM_PREVIOUS_PASSWORD) .setDescription("Previous password. Required when changing one's own password.") .setRequired(false) .setExampleValue("oldpassword"); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) { userSession.checkLoggedIn(); try (DbSession dbSession = dbClient.openSession(false)) { String login = getParamOrThrow(request, PARAM_LOGIN); String newPassword = getParamOrThrow(request, PARAM_PASSWORD); UserDto user; if (login.equals(userSession.getLogin())) { user = getUserOrThrow(dbSession, login); String previousPassword = getParamOrThrow(request, PARAM_PREVIOUS_PASSWORD); checkPreviousPassword(dbSession, user, previousPassword); checkNewPasswordSameAsOld(newPassword, previousPassword); deleteTokensAndRefreshSession(request, response, dbSession, user); } else { userSession.checkIsSystemAdministrator(); user = getUserOrThrow(dbSession, login); dbClient.sessionTokensDao().deleteByUser(dbSession, user); } updatePassword(dbSession, user, newPassword); setResponseStatus(response, HTTP_NO_CONTENT); } catch (BadRequestException badRequestException) { setResponseStatus(response, HTTP_BAD_REQUEST); LOG.debug(badRequestException.getMessage(), badRequestException); } catch (PasswordException passwordException) { LOG.debug(passwordException.getMessage(), passwordException); setResponseStatus(response, HTTP_BAD_REQUEST); String message = passwordException.getPasswordMessage().map(pm -> pm.key).orElseGet(passwordException::getMessage); writeJsonResponse(message, response); } } private static String getParamOrThrow(HttpRequest request, String key) throws PasswordException { String value = request.getParameter(key); if (isNullOrEmpty(value)) { throw new PasswordException(format(MSG_PARAMETER_MISSING, key)); } return value; } private void checkPreviousPassword(DbSession dbSession, UserDto user, String password) throws PasswordException { try { localAuthentication.authenticate(dbSession, user, password, AuthenticationEvent.Method.BASIC); } catch (AuthenticationException ex) { throw new PasswordException(OLD_PASSWORD_INCORRECT, "Incorrect password"); } } private static void checkNewPasswordSameAsOld(String newPassword, String previousPassword) throws PasswordException { if (previousPassword.equals(newPassword)) { throw new PasswordException(NEW_PASSWORD_SAME_AS_OLD, "Password must be different from old password"); } } private UserDto getUserOrThrow(DbSession dbSession, String login) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); if (user == null || !user.isActive()) { throw new NotFoundException(format("User with login '%s' has not been found", login)); } return user; } private void deleteTokensAndRefreshSession(HttpRequest request, HttpResponse response, DbSession dbSession, UserDto user) { dbClient.sessionTokensDao().deleteByUser(dbSession, user); refreshJwtToken(request, response, user); } private void refreshJwtToken(HttpRequest request, HttpResponse response, UserDto user) { jwtHttpHandler.removeToken(request, response); jwtHttpHandler.generateToken(user, request, response); } private void updatePassword(DbSession dbSession, UserDto user, String newPassword) { UpdateUser updateUser = new UpdateUser().setPassword(newPassword); userUpdater.updateAndCommit(dbSession, user, updateUser, u -> { }); } private static void setResponseStatus(HttpResponse response, int newStatusCode) { response.setStatus(newStatusCode); } private static void writeJsonResponse(String msg, HttpResponse response) { Gson gson = new GsonBuilder() .disableHtmlEscaping() .create(); try (OutputStream output = response.getOutputStream(); JsonWriter writer = gson.newJsonWriter(new OutputStreamWriter(output, UTF_8))) { response.setContentType(JSON); writer.beginObject() .name("result").value(msg); writer.endObject(); } catch (Exception e) { throw new IllegalStateException("Error while writing message", e); } } enum PasswordMessage { OLD_PASSWORD_INCORRECT("old_password_incorrect"), NEW_PASSWORD_SAME_AS_OLD("new_password_same_as_old"); final String key; PasswordMessage(String key) { this.key = key; } } private static class PasswordException extends Exception { private final PasswordMessage passwordMessage; public PasswordException(PasswordMessage passwordMessage, String message) { super(message); this.passwordMessage = passwordMessage; } public PasswordException(String message) { super(message); this.passwordMessage = null; } public Optional<PasswordMessage> getPasswordMessage() { return Optional.ofNullable(passwordMessage); } } }
9,973
39.710204
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/CreateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.ExternalIdentity; import org.sonar.server.user.NewUser; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; import org.sonarqube.ws.Users.CreateWsResponse; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Strings.isNullOrEmpty; import static java.util.Collections.emptyList; import static java.util.Optional.ofNullable; import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY; import static org.sonar.server.user.UserUpdater.EMAIL_MAX_LENGTH; import static org.sonar.server.user.UserUpdater.LOGIN_MAX_LENGTH; import static org.sonar.server.user.UserUpdater.LOGIN_MIN_LENGTH; import static org.sonar.server.user.UserUpdater.NAME_MAX_LENGTH; import static org.sonar.server.user.ws.EmailValidator.isValidIfPresent; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_CREATE; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_EMAIL; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOCAL; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_NAME; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_PASSWORD; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_SCM_ACCOUNT; public class CreateAction implements UsersWsAction { private final DbClient dbClient; private final UserUpdater userUpdater; private final UserSession userSession; private final ManagedInstanceChecker managedInstanceChecker; public CreateAction(DbClient dbClient, UserUpdater userUpdater, UserSession userSession, ManagedInstanceChecker managedInstanceService) { this.dbClient = dbClient; this.userUpdater = userUpdater; this.userSession = userSession; this.managedInstanceChecker = managedInstanceService; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(ACTION_CREATE) .setDescription("Create a user.<br/>" + "If a deactivated user account exists with the given login, it will be reactivated.<br/>" + "Requires Administer System permission") .setSince("3.7") .setChangelog( new Change("6.3", "The password is only mandatory when creating local users, and should not be set on non local users"), new Change("6.3", "The 'infos' message is no more returned when a user is reactivated")) .setPost(true) .setResponseExample(getClass().getResource("create-example.json")) .setHandler(this); action.createParam(PARAM_LOGIN) .setRequired(true) .setMinimumLength(LOGIN_MIN_LENGTH) .setMaximumLength(LOGIN_MAX_LENGTH) .setDescription("User login") .setExampleValue("myuser"); action.createParam(PARAM_PASSWORD) .setDescription("User password. Only mandatory when creating local user, otherwise it should not be set") .setExampleValue("mypassword"); action.createParam(PARAM_NAME) .setRequired(true) .setMaximumLength(NAME_MAX_LENGTH) .setDescription("User name") .setExampleValue("My Name"); action.createParam(PARAM_EMAIL) .setMaximumLength(EMAIL_MAX_LENGTH) .setDescription("User email") .setExampleValue("myname@email.com"); action.createParam(PARAM_SCM_ACCOUNT) .setDescription("List of SCM accounts. To set several values, the parameter must be called once for each value.") .setExampleValue("scmAccount=firstValue&scmAccount=secondValue&scmAccount=thirdValue"); action.createParam(PARAM_LOCAL) .setDescription("Specify if the user should be authenticated from SonarQube server or from an external authentication system. " + "Password should not be set when local is set to false.") .setSince("6.3") .setDefaultValue("true") .setBooleanPossibleValues(); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); managedInstanceChecker.throwIfInstanceIsManaged(); CreateRequest createRequest = toWsRequest(request); checkArgument(isValidIfPresent(createRequest.getEmail()), "Email '%s' is not valid", createRequest.getEmail()); writeProtobuf(doHandle(createRequest), request, response); } private CreateWsResponse doHandle(CreateRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { String login = request.getLogin(); NewUser.Builder newUser = NewUser.builder() .setLogin(login) .setName(request.getName()) .setEmail(request.getEmail()) .setScmAccounts(request.getScmAccounts()) .setPassword(request.getPassword()); if (!request.isLocal()) { newUser.setExternalIdentity(new ExternalIdentity(SQ_AUTHORITY, login, login)); } UserDto existingUser = dbClient.userDao().selectByLogin(dbSession, login); if (existingUser == null) { return buildResponse(userUpdater.createAndCommit(dbSession, newUser.build(), u -> { })); } checkArgument(!existingUser.isActive(), "An active user with login '%s' already exists", login); return buildResponse(userUpdater.reactivateAndCommit(dbSession, existingUser, newUser.build(), u -> { })); } } private static CreateWsResponse buildResponse(UserDto userDto) { CreateWsResponse.User.Builder userBuilder = CreateWsResponse.User.newBuilder() .setLogin(userDto.getLogin()) .setName(userDto.getName()) .setActive(userDto.isActive()) .setLocal(userDto.isLocal()) .addAllScmAccounts(userDto.getSortedScmAccounts()); ofNullable(emptyToNull(userDto.getEmail())).ifPresent(userBuilder::setEmail); return CreateWsResponse.newBuilder().setUser(userBuilder).build(); } private static CreateRequest toWsRequest(Request request) { return CreateRequest.builder() .setLogin(request.mandatoryParam(PARAM_LOGIN)) .setName(request.mandatoryParam(PARAM_NAME)) .setPassword(request.param(PARAM_PASSWORD)) .setEmail(request.param(PARAM_EMAIL)) .setScmAccounts(parseScmAccounts(request)) .setLocal(request.mandatoryParamAsBoolean(PARAM_LOCAL)) .build(); } public static List<String> parseScmAccounts(Request request) { if (request.hasParam(PARAM_SCM_ACCOUNT)) { List<String> scmAccounts = request.multiParam(PARAM_SCM_ACCOUNT); validateScmAccounts(scmAccounts); return scmAccounts; } return emptyList(); } private static void validateScmAccounts(List<String> scmAccounts) { scmAccounts.forEach(CreateAction::validateScmAccountFormat); validateNoDuplicates(scmAccounts); } private static void validateScmAccountFormat(String scmAccount) { checkArgument(scmAccount.equals(scmAccount.strip()), "SCM account cannot start or end with whitespace: '%s'", scmAccount); } private static void validateNoDuplicates(List<String> scmAccounts) { Set<String> duplicateCheck = new HashSet<>(); for (String account : scmAccounts) { checkArgument(duplicateCheck.add(account), "Duplicate SCM account: '%s'", account); } } static class CreateRequest { private final String login; private final String password; private final String name; private final String email; private final List<String> scmAccounts; private final boolean local; private CreateRequest(Builder builder) { this.login = builder.login; this.password = builder.password; this.name = builder.name; this.email = builder.email; this.scmAccounts = builder.scmAccounts; this.local = builder.local; } public String getLogin() { return login; } @CheckForNull public String getPassword() { return password; } public String getName() { return name; } @CheckForNull public String getEmail() { return email; } public List<String> getScmAccounts() { return scmAccounts; } public boolean isLocal() { return local; } public static Builder builder() { return new Builder(); } } static class Builder { private String login; private String password; private String name; private String email; private List<String> scmAccounts = emptyList(); private boolean local = true; private Builder() { // enforce factory method use } public Builder setLogin(String login) { this.login = login; return this; } public Builder setPassword(@Nullable String password) { this.password = password; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setEmail(@Nullable String email) { this.email = email; return this; } public Builder setScmAccounts(List<String> scmAccounts) { this.scmAccounts = scmAccounts; return this; } public Builder setLocal(boolean local) { this.local = local; return this; } public CreateRequest build() { checkArgument(!isNullOrEmpty(login), "Login is mandatory and must not be empty"); checkArgument(!isNullOrEmpty(name), "Name is mandatory and must not be empty"); checkArgument(!local || !isNullOrEmpty(password), "Password is mandatory and must not be empty"); checkArgument(local || isNullOrEmpty(password), "Password should only be set on local user"); return new CreateRequest(this); } } }
11,097
35.748344
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/CurrentAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.Collection; import java.util.List; import java.util.Optional; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.property.PropertyQuery; import org.sonar.db.user.UserDto; import org.sonar.server.issue.AvatarResolver; import org.sonar.server.permission.PermissionService; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Users.CurrentWsResponse; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.emptyToNull; import static java.util.Collections.singletonList; import static java.util.Optional.empty; import static java.util.Optional.of; import static java.util.Optional.ofNullable; import static org.apache.commons.lang.StringUtils.EMPTY; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.user.ws.DismissNoticeAction.EDUCATION_PRINCIPLES; import static org.sonar.server.user.ws.DismissNoticeAction.SONARLINT_AD; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.Users.CurrentWsResponse.HomepageType.APPLICATION; import static org.sonarqube.ws.Users.CurrentWsResponse.HomepageType.PORTFOLIO; import static org.sonarqube.ws.Users.CurrentWsResponse.HomepageType.PROJECT; import static org.sonarqube.ws.Users.CurrentWsResponse.Permissions; import static org.sonarqube.ws.Users.CurrentWsResponse.newBuilder; import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_CURRENT; public class CurrentAction implements UsersWsAction { private final UserSession userSession; private final DbClient dbClient; private final AvatarResolver avatarResolver; private final HomepageTypes homepageTypes; private final PlatformEditionProvider editionProvider; private final PermissionService permissionService; public CurrentAction(UserSession userSession, DbClient dbClient, AvatarResolver avatarResolver, HomepageTypes homepageTypes, PlatformEditionProvider editionProvider, PermissionService permissionService) { this.userSession = userSession; this.dbClient = dbClient; this.avatarResolver = avatarResolver; this.homepageTypes = homepageTypes; this.editionProvider = editionProvider; this.permissionService = permissionService; } @Override public void define(NewController context) { context.createAction(ACTION_CURRENT) .setDescription("Get the details of the current authenticated user.") .setSince("5.2") .setInternal(true) .setHandler(this) .setResponseExample(getClass().getResource("current-example.json")) .setChangelog( new Change("6.5", "showOnboardingTutorial is now returned in the response"), new Change("7.1", "'parameter' is replaced by 'component' and 'organization' in the response"), new Change("9.2", "boolean 'usingSonarLintConnectedMode' and 'sonarLintAdSeen' fields are now returned in the response"), new Change("9.5", "showOnboardingTutorial is not returned anymore in the response"), new Change("9.6", "'sonarLintAdSeen' is removed and replaced by a 'dismissedNotices' map that support multiple values") ); } @Override public void handle(Request request, Response response) throws Exception { if (userSession.isLoggedIn()) { try (DbSession dbSession = dbClient.openSession(false)) { writeProtobuf(toWsResponse(dbSession, userSession.getLogin()), request, response); } } else { writeProtobuf(newBuilder() .setIsLoggedIn(false) .setPermissions(Permissions.newBuilder().addAllGlobal(getGlobalPermissions()).build()) .build(), request, response); } } private CurrentWsResponse toWsResponse(DbSession dbSession, String userLogin) { UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, userLogin); checkState(user != null, "User login '%s' cannot be found", userLogin); Collection<String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(userLogin)).get(userLogin); CurrentWsResponse.Builder builder = newBuilder() .setIsLoggedIn(true) .setLogin(user.getLogin()) .setName(user.getName()) .setLocal(user.isLocal()) .addAllGroups(groups) .addAllScmAccounts(user.getSortedScmAccounts()) .setPermissions(Permissions.newBuilder().addAllGlobal(getGlobalPermissions()).build()) .setHomepage(buildHomepage(dbSession, user)) .setUsingSonarLintConnectedMode(user.getLastSonarlintConnectionDate() != null) .putDismissedNotices(EDUCATION_PRINCIPLES, isNoticeDismissed(user, EDUCATION_PRINCIPLES)) .putDismissedNotices(SONARLINT_AD, isNoticeDismissed(user, SONARLINT_AD)); ofNullable(emptyToNull(user.getEmail())).ifPresent(builder::setEmail); ofNullable(emptyToNull(user.getEmail())).ifPresent(u -> builder.setAvatar(avatarResolver.create(user))); ofNullable(user.getExternalLogin()).ifPresent(builder::setExternalIdentity); ofNullable(user.getExternalIdentityProvider()).ifPresent(builder::setExternalProvider); return builder.build(); } private List<String> getGlobalPermissions() { return permissionService.getGlobalPermissions().stream() .filter(userSession::hasPermission) .map(GlobalPermission::getKey) .toList(); } private boolean isNoticeDismissed(UserDto user, String noticeName) { String paramKey = DismissNoticeAction.USER_DISMISS_CONSTANT + noticeName; PropertyQuery query = new PropertyQuery.Builder() .setUserUuid(user.getUuid()) .setKey(paramKey) .build(); try (DbSession dbSession = dbClient.openSession(false)) { return !dbClient.propertiesDao().selectByQuery(query, dbSession).isEmpty(); } } private CurrentWsResponse.Homepage buildHomepage(DbSession dbSession, UserDto user) { if (noHomepageSet(user)) { return defaultHomepage(); } return doBuildHomepage(dbSession, user).orElse(defaultHomepage()); } private Optional<CurrentWsResponse.Homepage> doBuildHomepage(DbSession dbSession, UserDto user) { if (PROJECT.toString().equals(user.getHomepageType())) { return projectHomepage(dbSession, user); } if (APPLICATION.toString().equals(user.getHomepageType()) || PORTFOLIO.toString().equals(user.getHomepageType())) { return applicationAndPortfolioHomepage(dbSession, user); } return of(CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .build()); } private Optional<CurrentWsResponse.Homepage> projectHomepage(DbSession dbSession, UserDto user) { Optional<BranchDto> branchOptional = ofNullable(user.getHomepageParameter()).flatMap(p -> dbClient.branchDao().selectByUuid(dbSession, p)); Optional<ProjectDto> projectOptional = branchOptional.flatMap(b -> dbClient.projectDao().selectByUuid(dbSession, b.getProjectUuid())); if (shouldCleanProjectHomepage(projectOptional, branchOptional)) { cleanUserHomepageInDb(dbSession, user); return empty(); } CurrentWsResponse.Homepage.Builder homepage = CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .setComponent(projectOptional.get().getKey()); if (!branchOptional.get().getProjectUuid().equals(branchOptional.get().getUuid())) { homepage.setBranch(branchOptional.get().getKey()); } return of(homepage.build()); } private boolean shouldCleanProjectHomepage(Optional<ProjectDto> projectOptional, Optional<BranchDto> branchOptional) { return !projectOptional.isPresent() || !branchOptional.isPresent() || !userSession.hasEntityPermission(USER, projectOptional.get()); } private Optional<CurrentWsResponse.Homepage> applicationAndPortfolioHomepage(DbSession dbSession, UserDto user) { Optional<ComponentDto> componentOptional = dbClient.componentDao().selectByUuid(dbSession, of(user.getHomepageParameter()).orElse(EMPTY)); if (shouldCleanApplicationOrPortfolioHomepage(componentOptional)) { cleanUserHomepageInDb(dbSession, user); return empty(); } return of(CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .setComponent(componentOptional.get().getKey()) .build()); } private boolean shouldCleanApplicationOrPortfolioHomepage(Optional<ComponentDto> componentOptional) { return !componentOptional.isPresent() || !hasValidEdition() || !userSession.hasComponentPermission(USER, componentOptional.get()); } private boolean hasValidEdition() { Optional<EditionProvider.Edition> edition = editionProvider.get(); if (!edition.isPresent()) { return false; } return switch (edition.get()) { case ENTERPRISE, DATACENTER -> true; default -> false; }; } private void cleanUserHomepageInDb(DbSession dbSession, UserDto user) { dbClient.userDao().cleanHomepage(dbSession, user); } private CurrentWsResponse.Homepage defaultHomepage() { return CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(homepageTypes.getDefaultType().name())) .build(); } private static boolean noHomepageSet(UserDto user) { return user.getHomepageType() == null; } }
10,695
42.836066
143
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/DeactivateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.HashSet; import java.util.Set; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.user.UserSession; import static java.util.Collections.singletonList; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.NotFoundException.checkFound; public class DeactivateAction implements UsersWsAction { private static final String PARAM_LOGIN = "login"; private static final String PARAM_ANONYMIZE = "anonymize"; private final DbClient dbClient; private final UserSession userSession; private final UserJsonWriter userWriter; private final UserDeactivator userDeactivator; private final ManagedInstanceService managedInstanceService; public DeactivateAction(DbClient dbClient, UserSession userSession, UserJsonWriter userWriter, UserDeactivator userDeactivator, ManagedInstanceService managedInstanceService) { this.dbClient = dbClient; this.userSession = userSession; this.userWriter = userWriter; this.userDeactivator = userDeactivator; this.managedInstanceService = managedInstanceService; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("deactivate") .setDescription("Deactivate a user. Requires Administer System permission") .setSince("3.7") .setPost(true) .setResponseExample(getClass().getResource("deactivate-example.json")) .setHandler(this); action.createParam(PARAM_LOGIN) .setDescription("User login") .setRequired(true) .setExampleValue("myuser"); action.createParam(PARAM_ANONYMIZE) .setDescription("Anonymize user in addition to deactivating it") .setBooleanPossibleValues() .setRequired(false) .setSince("9.7") .setDefaultValue(false); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); String login = request.mandatoryParam(PARAM_LOGIN); checkRequest(!login.equals(userSession.getLogin()), "Self-deactivation is not possible"); try (DbSession dbSession = dbClient.openSession(false)) { preventManagedUserDeactivationIfManagedInstance(dbSession, login); boolean shouldAnonymize = request.mandatoryParamAsBoolean(PARAM_ANONYMIZE); UserDto userDto = shouldAnonymize ? userDeactivator.deactivateUserWithAnonymization(dbSession, login) : userDeactivator.deactivateUser(dbSession, login); writeResponse(response, userDto.getLogin()); } } private void preventManagedUserDeactivationIfManagedInstance(DbSession dbSession, String login) { checkRequest(!managedInstanceService.isUserManaged(dbSession, login), "Operation not allowed when the instance is externally managed."); } private void writeResponse(Response response, String login) { try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); // safeguard. It exists as the check has already been done earlier // when deactivating user checkFound(user, "User '%s' doesn't exist", login); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); json.name("user"); Set<String> groups = new HashSet<>(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(login)).get(login)); userWriter.write(json, user, groups, UserJsonWriter.FIELDS); json.endObject(); } } } }
4,797
38.983333
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/DismissNoticeAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkState; public class DismissNoticeAction implements UsersWsAction { public static final String EDUCATION_PRINCIPLES = "educationPrinciples"; public static final String SONARLINT_AD = "sonarlintAd"; public static final String USER_DISMISS_CONSTANT = "user.dismissedNotices."; private final UserSession userSession; private final DbClient dbClient; public DismissNoticeAction(UserSession userSession, DbClient dbClient) { this.userSession = userSession; this.dbClient = dbClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("dismiss_notice") .setDescription("Dismiss a notice for the current user. Silently ignore if the notice is already dismissed.") .setSince("9.6") .setInternal(true) .setHandler(this) .setPost(true); action.createParam("notice") .setDescription("notice key to dismiss") .setExampleValue(EDUCATION_PRINCIPLES) .setPossibleValues(EDUCATION_PRINCIPLES, SONARLINT_AD); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String currentUserUuid = userSession.getUuid(); checkState(currentUserUuid != null, "User uuid should not be null"); String noticeKeyParam = request.mandatoryParam("notice"); dismissNotice(response, currentUserUuid, noticeKeyParam); } public void dismissNotice(Response response, String currentUserUuid, String noticeKeyParam) { try (DbSession dbSession = dbClient.openSession(false)) { String paramKey = USER_DISMISS_CONSTANT + noticeKeyParam; PropertyQuery query = new PropertyQuery.Builder() .setUserUuid(currentUserUuid) .setKey(paramKey) .build(); if (!dbClient.propertiesDao().selectByQuery(query, dbSession).isEmpty()) { // already dismissed response.noContent(); } PropertyDto property = new PropertyDto().setUserUuid(currentUserUuid).setKey(paramKey); dbClient.propertiesDao().saveProperty(dbSession, property); dbSession.commit(); response.noContent(); } } }
3,412
35.698925
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/EmailValidator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import javax.annotation.Nullable; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import static org.apache.commons.lang.StringUtils.isEmpty; public class EmailValidator { private EmailValidator() { // Hide constructor } static boolean isValidIfPresent(@Nullable String email) { return isEmpty(email) || isValidEmail(email); } public static boolean isValidEmail(String email) { try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); return true; } catch (AddressException ex) { return false; } } }
1,507
29.77551
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/GroupsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.server.ws.WebService.SelectionMode; import org.sonar.api.utils.Paging; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.db.user.GroupMembershipDto; import org.sonar.db.user.GroupMembershipQuery; import org.sonar.db.user.UserDto; import org.sonar.server.user.UserSession; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonarqube.ws.Users.GroupsWsResponse; import org.sonarqube.ws.Users.GroupsWsResponse.Group; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; import static java.util.Optional.ofNullable; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.SELECTED; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.utils.Paging.forPageIndex; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; public class GroupsAction implements UsersWsAction { private static final int MAX_PAGE_SIZE = 500; private final DbClient dbClient; private final UserSession userSession; private final DefaultGroupFinder defaultGroupFinder; public GroupsAction(DbClient dbClient, UserSession userSession, DefaultGroupFinder defaultGroupFinder) { this.dbClient = dbClient; this.userSession = userSession; this.defaultGroupFinder = defaultGroupFinder; } @Override public void define(NewController context) { NewAction action = context.createAction("groups") .setDescription("Lists the groups a user belongs to. <br/>" + "Requires Administer System permission.") .setHandler(this) .setResponseExample(getClass().getResource("groups-example.json")) .addSelectionModeParam() .addSearchQuery("users", "group names") .addPagingParams(25) .setChangelog(new Change("6.4", "Paging response fields moved to a Paging object"), new Change("6.4", "'default' response field has been added")) .setSince("5.2"); action.createParam(PARAM_LOGIN) .setDescription("A user login") .setExampleValue("admin") .setRequired(true); } @Override public void handle(Request request, Response response) throws Exception { GroupsWsResponse groupsWsResponse = doHandle(toGroupsRequest(request)); writeProtobuf(groupsWsResponse, request, response); } private GroupsWsResponse doHandle(GroupsRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkPermission(GlobalPermission.ADMINISTER); String login = request.getLogin(); GroupMembershipQuery query = GroupMembershipQuery.builder() .groupSearch(request.getQuery()) .membership(getMembership(request.getSelected())) .pageIndex(request.getPage()) .pageSize(request.getPageSize()) .build(); UserDto user = checkFound(dbClient.userDao().selectActiveUserByLogin(dbSession, login), "Unknown user: %s", login); int total = dbClient.groupMembershipDao().countGroups(dbSession, query, user.getUuid()); Paging paging = forPageIndex(query.pageIndex()).withPageSize(query.pageSize()).andTotal(total); List<GroupMembershipDto> groups = dbClient.groupMembershipDao().selectGroups(dbSession, query, user.getUuid(), paging.offset(), query.pageSize()); return buildResponse(groups, defaultGroupFinder.findDefaultGroup(dbSession), paging); } } private static GroupsRequest toGroupsRequest(Request request) { int pageSize = request.mandatoryParamAsInt(PAGE_SIZE); checkArgument(pageSize <= MAX_PAGE_SIZE, "The '%s' parameter must be less than %s", PAGE_SIZE, MAX_PAGE_SIZE); return GroupsRequest.builder() .setLogin(request.mandatoryParam(PARAM_LOGIN)) .setSelected(request.mandatoryParam(SELECTED)) .setQuery(request.param(TEXT_QUERY)) .setPage(request.mandatoryParamAsInt(PAGE)) .setPageSize(pageSize) .build(); } private static String getMembership(String selected) { SelectionMode selectionMode = SelectionMode.fromParam(selected); String membership = GroupMembershipQuery.ANY; if (SelectionMode.SELECTED == selectionMode) { membership = GroupMembershipQuery.IN; } else if (SelectionMode.DESELECTED == selectionMode) { membership = GroupMembershipQuery.OUT; } return membership; } private static GroupsWsResponse buildResponse(List<GroupMembershipDto> groups, GroupDto defaultGroup, Paging paging) { GroupsWsResponse.Builder responseBuilder = GroupsWsResponse.newBuilder(); groups.forEach(group -> responseBuilder.addGroups(toWsGroup(group, defaultGroup))); responseBuilder.getPagingBuilder() .setPageIndex(paging.pageIndex()) .setPageSize(paging.pageSize()) .setTotal(paging.total()) .build(); return responseBuilder.build(); } private static Group toWsGroup(GroupMembershipDto group, GroupDto defaultGroup) { Group.Builder groupBuilder = Group.newBuilder() .setId(group.getUuid()) .setName(group.getName()) .setSelected(group.getUserUuid() != null) .setDefault(defaultGroup.getUuid().equals(group.getUuid())); ofNullable(group.getDescription()).ifPresent(groupBuilder::setDescription); return groupBuilder.build(); } private static class GroupsRequest { private final String login; private final String query; private final String selected; private final Integer page; private final Integer pageSize; private GroupsRequest(Builder builder) { this.login = builder.login; this.query = builder.query; this.selected = builder.selected; this.page = builder.page; this.pageSize = builder.pageSize; } public String getLogin() { return login; } @CheckForNull public String getQuery() { return query; } @CheckForNull public String getSelected() { return selected; } @CheckForNull public Integer getPage() { return page; } @CheckForNull public Integer getPageSize() { return pageSize; } public static Builder builder() { return new Builder(); } } private static class Builder { private String login; private String query; private String selected; private Integer page; private Integer pageSize; private Builder() { // enforce factory method use } public Builder setLogin(String login) { this.login = login; return this; } public Builder setQuery(@Nullable String query) { this.query = query; return this; } public Builder setSelected(@Nullable String selected) { this.selected = selected; return this; } public Builder setPage(@Nullable Integer page) { this.page = page; return this; } public Builder setPageSize(@Nullable Integer pageSize) { this.pageSize = pageSize; return this; } public GroupsRequest build() { checkArgument(!isNullOrEmpty(login), "Login is mandatory and must not be empty"); return new GroupsRequest(this); } } }
8,665
34.08502
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/HomepageTypes.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.List; public interface HomepageTypes { enum Type { PROJECT, PROJECTS, ISSUES, PORTFOLIOS, PORTFOLIO, APPLICATION } List<Type> getTypes(); Type getDefaultType(); }
1,074
30.617647
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/HomepageTypesImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.List; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkState; import static org.sonar.server.user.ws.HomepageTypes.Type.PROJECTS; public class HomepageTypesImpl implements HomepageTypes { private List<Type> types; public HomepageTypesImpl() { types = Stream.of(HomepageTypes.Type.values()).toList(); } @Override public List<Type> getTypes() { checkState(types != null, "Homepage types have not been initialized yet"); return types; } @Override public Type getDefaultType() { return PROJECTS; } }
1,471
29.666667
78
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/IdentityProvidersAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.function.Function; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.server.authentication.IdentityProviderRepository; import org.sonarqube.ws.Users; import org.sonarqube.ws.Users.IdentityProvidersWsResponse; import static java.util.Optional.ofNullable; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class IdentityProvidersAction implements UsersWsAction { private final IdentityProviderRepository identityProviderRepository; public IdentityProvidersAction(IdentityProviderRepository identityProviderRepository) { this.identityProviderRepository = identityProviderRepository; } @Override public void define(WebService.NewController context) { context.createAction("identity_providers") .setDescription("List the external identity providers") .setResponseExample(getClass().getResource("identity_providers-example.json")) .setSince("5.5") .setInternal(true) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { writeProtobuf(buildResponse(), request, response); } private IdentityProvidersWsResponse buildResponse() { IdentityProvidersWsResponse.Builder response = IdentityProvidersWsResponse.newBuilder(); response.addAllIdentityProviders(identityProviderRepository.getAllEnabledAndSorted() .stream() .map(toWsIdentityProvider()) .toList()); return response.build(); } private static Function<IdentityProvider, Users.IdentityProvider> toWsIdentityProvider() { return input -> { Display display = input.getDisplay(); Users.IdentityProvider.Builder builder = Users.IdentityProvider.newBuilder() .setKey(input.getKey()) .setName(input.getName()) .setIconPath(display.getIconPath()) .setBackgroundColor(display.getBackgroundColor()); ofNullable(display.getHelpMessage()).ifPresent(builder::setHelpMessage); return builder.build(); }; } }
3,072
37.898734
92
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/SearchAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import com.google.common.collect.Multimap; import java.time.OffsetDateTime; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.Paging; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserQuery; import org.sonar.server.es.SearchOptions; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.issue.AvatarResolver; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Users; import org.sonarqube.ws.Users.SearchWsResponse; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.emptyToNull; import static java.lang.Boolean.TRUE; import static java.util.Comparator.comparing; import static java.util.Optional.ofNullable; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.utils.Paging.forPageIndex; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.Users.SearchWsResponse.Groups; import static org.sonarqube.ws.Users.SearchWsResponse.ScmAccounts; import static org.sonarqube.ws.Users.SearchWsResponse.User; import static org.sonarqube.ws.Users.SearchWsResponse.newBuilder; public class SearchAction implements UsersWsAction { private static final String DEACTIVATED_PARAM = "deactivated"; private static final String MANAGED_PARAM = "managed"; private static final int MAX_PAGE_SIZE = 500; static final String LAST_CONNECTION_DATE_FROM = "lastConnectedAfter"; static final String LAST_CONNECTION_DATE_TO = "lastConnectedBefore"; static final String SONAR_LINT_LAST_CONNECTION_DATE_FROM = "slLastConnectedAfter"; static final String SONAR_LINT_LAST_CONNECTION_DATE_TO = "slLastConnectedBefore"; private final UserSession userSession; private final DbClient dbClient; private final AvatarResolver avatarResolver; private final ManagedInstanceService managedInstanceService; public SearchAction(UserSession userSession, DbClient dbClient, AvatarResolver avatarResolver, ManagedInstanceService managedInstanceService) { this.userSession = userSession; this.dbClient = dbClient; this.avatarResolver = avatarResolver; this.managedInstanceService = managedInstanceService; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("search") .setDescription("Get a list of users. By default, only active users are returned.<br/>" + "The following fields are only returned when user has Administer System permission or for logged-in in user :" + "<ul>" + " <li>'email'</li>" + " <li>'externalIdentity'</li>" + " <li>'externalProvider'</li>" + " <li>'groups'</li>" + " <li>'lastConnectionDate'</li>" + " <li>'sonarLintLastConnectionDate'</li>" + " <li>'tokensCount'</li>" + "</ul>" + "Field 'lastConnectionDate' is only updated every hour, so it may not be accurate, for instance when a user authenticates many times in less than one hour.") .setSince("3.6") .setChangelog( new Change("10.1", "New optional parameters " + SONAR_LINT_LAST_CONNECTION_DATE_FROM + " and " + SONAR_LINT_LAST_CONNECTION_DATE_TO + " to filter users by SonarLint last connection date. Only available with Administer System permission."), new Change("10.1", "New optional parameters " + LAST_CONNECTION_DATE_FROM + " and " + LAST_CONNECTION_DATE_TO + " to filter users by SonarQube last connection date. Only available with Administer System permission."), new Change("10.1", "New field 'sonarLintLastConnectionDate' is added to response"), new Change("10.0", "'q' parameter values is now always performing a case insensitive match"), new Change("10.0", "New parameter 'managed' to optionally search by managed status"), new Change("10.0", "Response includes 'managed' field."), new Change("9.7", "New parameter 'deactivated' to optionally search for deactivated users"), new Change("7.7", "New field 'lastConnectionDate' is added to response"), new Change("7.4", "External identity is only returned to system administrators"), new Change("6.4", "Paging response fields moved to a Paging object"), new Change("6.4", "Avatar has been added to the response"), new Change("6.4", "Email is only returned when user has Administer System permission")) .setHandler(this) .setResponseExample(getClass().getResource("search-example.json")); action.addPagingParams(50, SearchOptions.MAX_PAGE_SIZE); final String dateExample = "2020-01-01T00:00:00+0100"; action.createParam(TEXT_QUERY) .setMinimumLength(2) .setDescription("Filter on login, name and email.<br />" + "This parameter can either perform an exact match, or a partial match (contains), it is case insensitive."); action.createParam(DEACTIVATED_PARAM) .setSince("9.7") .setDescription("Return deactivated users instead of active users") .setRequired(false) .setDefaultValue(false) .setBooleanPossibleValues(); action.createParam(MANAGED_PARAM) .setSince("10.0") .setDescription("Return managed or non-managed users. Only available for managed instances, throws for non-managed instances.") .setRequired(false) .setDefaultValue(null) .setBooleanPossibleValues(); action.createParam(LAST_CONNECTION_DATE_FROM) .setSince("10.1") .setDescription(""" Filter the users based on the last connection date field. Only users who interacted with this instance at or after the date will be returned. The format must be ISO 8601 datetime format (YYYY-MM-DDThh:mm:ss±hhmm)""") .setRequired(false) .setDefaultValue(null) .setExampleValue(dateExample); action.createParam(LAST_CONNECTION_DATE_TO) .setSince("10.1") .setDescription(""" Filter the users based on the last connection date field. Only users that never connected or who interacted with this instance at or before the date will be returned. The format must be ISO 8601 datetime format (YYYY-MM-DDThh:mm:ss±hhmm)""") .setRequired(false) .setDefaultValue(null) .setExampleValue(dateExample); action.createParam(SONAR_LINT_LAST_CONNECTION_DATE_FROM) .setSince("10.1") .setDescription(""" Filter the users based on the sonar lint last connection date field Only users who interacted with this instance using SonarLint at or after the date will be returned. The format must be ISO 8601 datetime format (YYYY-MM-DDThh:mm:ss±hhmm)""") .setRequired(false) .setDefaultValue(null) .setExampleValue(dateExample); action.createParam(SONAR_LINT_LAST_CONNECTION_DATE_TO) .setSince("10.1") .setDescription(""" Filter the users based on the sonar lint last connection date field. Only users that never connected or who interacted with this instance using SonarLint at or before the date will be returned. The format must be ISO 8601 datetime format (YYYY-MM-DDThh:mm:ss±hhmm)""") .setRequired(false) .setDefaultValue(null) .setExampleValue(dateExample); } @Override public void handle(Request request, Response response) throws Exception { Users.SearchWsResponse wsResponse = doHandle(toSearchRequest(request)); writeProtobuf(wsResponse, request, response); } private Users.SearchWsResponse doHandle(SearchRequest request) { UserQuery userQuery = buildUserQuery(request); try (DbSession dbSession = dbClient.openSession(false)) { List<UserDto> users = findUsersAndSortByLogin(request, dbSession, userQuery); int totalUsers = dbClient.userDao().countUsers(dbSession, userQuery); List<String> logins = users.stream().map(UserDto::getLogin).toList(); Multimap<String, String> groupsByLogin = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, logins); Map<String, Integer> tokenCountsByLogin = dbClient.userTokenDao().countTokensByUsers(dbSession, users); Map<String, Boolean> userUuidToIsManaged = managedInstanceService.getUserUuidToManaged(dbSession, getUserUuids(users)); Paging paging = forPageIndex(request.getPage()).withPageSize(request.getPageSize()).andTotal(totalUsers); return buildResponse(users, groupsByLogin, tokenCountsByLogin, userUuidToIsManaged, paging); } } private static Set<String> getUserUuids(List<UserDto> users) { return users.stream().map(UserDto::getUuid).collect(Collectors.toSet()); } private UserQuery buildUserQuery(SearchRequest request) { UserQuery.UserQueryBuilder builder = UserQuery.builder(); if(!userSession.isSystemAdministrator()) { request.getLastConnectionDateFrom().ifPresent(v -> throwForbiddenFor(LAST_CONNECTION_DATE_FROM)); request.getLastConnectionDateTo().ifPresent(v -> throwForbiddenFor(LAST_CONNECTION_DATE_TO)); request.getSonarLintLastConnectionDateFrom().ifPresent(v -> throwForbiddenFor(SONAR_LINT_LAST_CONNECTION_DATE_FROM)); request.getSonarLintLastConnectionDateTo().ifPresent(v -> throwForbiddenFor(SONAR_LINT_LAST_CONNECTION_DATE_TO)); } request.getLastConnectionDateFrom().ifPresent(builder::lastConnectionDateFrom); request.getLastConnectionDateTo().ifPresent(builder::lastConnectionDateTo); request.getSonarLintLastConnectionDateFrom().ifPresent(builder::sonarLintLastConnectionDateFrom); request.getSonarLintLastConnectionDateTo().ifPresent(builder::sonarLintLastConnectionDateTo); if (managedInstanceService.isInstanceExternallyManaged()) { String managedInstanceSql = Optional.ofNullable(request.isManaged()) .map(managedInstanceService::getManagedUsersSqlFilter) .orElse(null); builder.isManagedClause(managedInstanceSql); } else if (request.isManaged() != null) { throw BadRequestException.create("The 'managed' parameter is only available for managed instances."); } return builder .isActive(!request.isDeactivated()) .searchText(request.getQuery()) .build(); } private static void throwForbiddenFor(String parameterName) { throw new ServerException(403, "parameter " + parameterName + " requires Administer System permission."); } private List<UserDto> findUsersAndSortByLogin(SearchRequest request, DbSession dbSession, UserQuery userQuery) { return dbClient.userDao().selectUsers(dbSession, userQuery, request.getPage(), request.getPageSize()) .stream() .sorted(comparing(UserDto::getLogin)) .toList(); } private SearchWsResponse buildResponse(List<UserDto> users, Multimap<String, String> groupsByLogin, Map<String, Integer> tokenCountsByLogin, Map<String, Boolean> userUuidToIsManaged, Paging paging) { SearchWsResponse.Builder responseBuilder = newBuilder(); users.forEach(user -> responseBuilder.addUsers( towsUser(user, firstNonNull(tokenCountsByLogin.get(user.getUuid()), 0), groupsByLogin.get(user.getLogin()), userUuidToIsManaged.get(user.getUuid())) )); responseBuilder.getPagingBuilder() .setPageIndex(paging.pageIndex()) .setPageSize(paging.pageSize()) .setTotal(paging.total()) .build(); return responseBuilder.build(); } private User towsUser(UserDto user, @Nullable Integer tokensCount, Collection<String> groups, Boolean managed) { User.Builder userBuilder = User.newBuilder().setLogin(user.getLogin()); ofNullable(user.getName()).ifPresent(userBuilder::setName); if (userSession.isLoggedIn()) { ofNullable(emptyToNull(user.getEmail())).ifPresent(u -> userBuilder.setAvatar(avatarResolver.create(user))); userBuilder.setActive(user.isActive()); userBuilder.setLocal(user.isLocal()); ofNullable(user.getExternalIdentityProvider()).ifPresent(userBuilder::setExternalProvider); if (!user.getSortedScmAccounts().isEmpty()) { userBuilder.setScmAccounts(ScmAccounts.newBuilder().addAllScmAccounts(user.getSortedScmAccounts())); } } if (userSession.isSystemAdministrator() || Objects.equals(userSession.getUuid(), user.getUuid())) { ofNullable(user.getEmail()).ifPresent(userBuilder::setEmail); if (!groups.isEmpty()) { userBuilder.setGroups(Groups.newBuilder().addAllGroups(groups)); } ofNullable(user.getExternalLogin()).ifPresent(userBuilder::setExternalIdentity); ofNullable(tokensCount).ifPresent(userBuilder::setTokensCount); ofNullable(user.getLastConnectionDate()).map(DateUtils::formatDateTime).ifPresent(userBuilder::setLastConnectionDate); ofNullable(user.getLastSonarlintConnectionDate()) .map(DateUtils::formatDateTime).ifPresent(userBuilder::setSonarLintLastConnectionDate); userBuilder.setManaged(TRUE.equals(managed)); } return userBuilder.build(); } private static SearchRequest toSearchRequest(Request request) { int pageSize = request.mandatoryParamAsInt(PAGE_SIZE); checkArgument(pageSize <= MAX_PAGE_SIZE, "The '%s' parameter must be less than %s", PAGE_SIZE, MAX_PAGE_SIZE); return SearchRequest.builder() .setQuery(request.param(TEXT_QUERY)) .setDeactivated(request.mandatoryParamAsBoolean(DEACTIVATED_PARAM)) .setManaged(request.paramAsBoolean(MANAGED_PARAM)) .setLastConnectionDateFrom(request.param(LAST_CONNECTION_DATE_FROM)) .setLastConnectionDateTo(request.param(LAST_CONNECTION_DATE_TO)) .setSonarLintLastConnectionDateFrom(request.param(SONAR_LINT_LAST_CONNECTION_DATE_FROM)) .setSonarLintLastConnectionDateTo(request.param(SONAR_LINT_LAST_CONNECTION_DATE_TO)) .setPage(request.mandatoryParamAsInt(PAGE)) .setPageSize(pageSize) .build(); } private static class SearchRequest { private final Integer page; private final Integer pageSize; private final String query; private final boolean deactivated; private final Boolean managed; private final OffsetDateTime lastConnectionDateFrom; private final OffsetDateTime lastConnectionDateTo; private final OffsetDateTime sonarLintLastConnectionDateFrom; private final OffsetDateTime sonarLintLastConnectionDateTo; private SearchRequest(Builder builder) { this.page = builder.page; this.pageSize = builder.pageSize; this.query = builder.query; this.deactivated = builder.deactivated; this.managed = builder.managed; try { this.lastConnectionDateFrom = Optional.ofNullable(builder.lastConnectionDateFrom).map(DateUtils::parseOffsetDateTime).orElse(null); this.lastConnectionDateTo = Optional.ofNullable(builder.lastConnectionDateTo).map(DateUtils::parseOffsetDateTime).orElse(null); this.sonarLintLastConnectionDateFrom = Optional.ofNullable(builder.sonarLintLastConnectionDateFrom).map(DateUtils::parseOffsetDateTime).orElse(null); this.sonarLintLastConnectionDateTo = Optional.ofNullable(builder.sonarLintLastConnectionDateTo).map(DateUtils::parseOffsetDateTime).orElse(null); } catch (MessageException me) { throw new ServerException(400, me.getMessage()); } } public Integer getPage() { return page; } public Integer getPageSize() { return pageSize; } @CheckForNull public String getQuery() { return query; } public boolean isDeactivated() { return deactivated; } @CheckForNull private Boolean isManaged() { return managed; } public Optional<OffsetDateTime> getLastConnectionDateFrom() { return Optional.ofNullable(lastConnectionDateFrom); } public Optional<OffsetDateTime> getLastConnectionDateTo() { return Optional.ofNullable(lastConnectionDateTo); } public Optional<OffsetDateTime> getSonarLintLastConnectionDateFrom() { return Optional.ofNullable(sonarLintLastConnectionDateFrom); } public Optional<OffsetDateTime> getSonarLintLastConnectionDateTo() { return Optional.ofNullable(sonarLintLastConnectionDateTo); } public static Builder builder() { return new Builder(); } } private static class Builder { private Integer page; private Integer pageSize; private String query; private boolean deactivated; private Boolean managed; private String lastConnectionDateFrom; private String lastConnectionDateTo; private String sonarLintLastConnectionDateFrom; private String sonarLintLastConnectionDateTo; private Builder() { // enforce factory method use } public Builder setPage(Integer page) { this.page = page; return this; } public Builder setPageSize(Integer pageSize) { this.pageSize = pageSize; return this; } public Builder setQuery(@Nullable String query) { this.query = query; return this; } public Builder setDeactivated(boolean deactivated) { this.deactivated = deactivated; return this; } public Builder setManaged(@Nullable Boolean managed) { this.managed = managed; return this; } public Builder setLastConnectionDateFrom(@Nullable String lastConnectionDateFrom) { this.lastConnectionDateFrom = lastConnectionDateFrom; return this; } public Builder setLastConnectionDateTo(@Nullable String lastConnectionDateTo) { this.lastConnectionDateTo = lastConnectionDateTo; return this; } public Builder setSonarLintLastConnectionDateFrom(@Nullable String sonarLintLastConnectionDateFrom) { this.sonarLintLastConnectionDateFrom = sonarLintLastConnectionDateFrom; return this; } public Builder setSonarLintLastConnectionDateTo(@Nullable String sonarLintLastConnectionDateTo) { this.sonarLintLastConnectionDateTo = sonarLintLastConnectionDateTo; return this; } public SearchRequest build() { return new SearchRequest(this); } } }
19,744
43.875
165
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/SearchUsersRequest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public abstract class SearchUsersRequest { protected String selected; protected String query; protected Integer page; protected Integer pageSize; @CheckForNull public String getQuery() { return query; } public String getSelected() { return selected; } public Integer getPage() { return page; } public Integer getPageSize() { return pageSize; } public abstract static class Builder<T extends Builder<T>> { private String selected; private String query; private Integer page; private Integer pageSize; public String getSelected() { return selected; } public T setSelected(String selected) { this.selected = selected; return self(); } public String getQuery() { return query; } public T setQuery(@Nullable String query) { this.query = query; return self(); } public Integer getPage() { return page; } public T setPage(Integer page) { this.page = page; return self(); } public Integer getPageSize() { return pageSize; } public T setPageSize(Integer pageSize) { this.pageSize = pageSize; return self(); } @SuppressWarnings("unchecked") final T self() { return (T) this; } } }
2,252
22.46875
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/SetHomepageAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.sonar.server.user.ws.HomepageTypes.Type.PROJECT; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; public class SetHomepageAction implements UsersWsAction { private static final String ACTION = "set_homepage"; public static final String PARAM_TYPE = "type"; public static final String PARAM_COMPONENT = "component"; public static final String PARAM_BRANCH = "branch"; private static final String PARAMETER_REQUIRED = "Type %s requires a parameter '%s'"; private final UserSession userSession; private final DbClient dbClient; private final ComponentFinder componentFinder; public SetHomepageAction(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder) { this.userSession = userSession; this.dbClient = dbClient; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(ACTION) .setPost(true) .setInternal(true) .setDescription("Set homepage of current user.<br> " + "Requires authentication.") .setSince("7.0") .setChangelog( new Change("8.3", "Types: MY_PROJECTS, MY_ISSUES, ORGANIZATION removed"), new Change("8.3", "Parameter 'organization' removed"), new Change("7.1", "Parameter 'parameter' is replaced by 'component' and 'organization'")) .setHandler(this); action.createParam(PARAM_TYPE) .setDescription("Type of the requested page") .setRequired(true) .setPossibleValues(HomepageTypes.Type.values()); action.createParam(PARAM_COMPONENT) .setSince("7.1") .setDescription("Project key. It should only be used when parameter '%s' is set to '%s'", PARAM_TYPE, PROJECT) .setExampleValue(KEY_PROJECT_EXAMPLE_001); action.createParam(PARAM_BRANCH) .setDescription("Branch key. It can only be used when parameter '%s' is set to '%s'", PARAM_TYPE, PROJECT) .setExampleValue(KEY_BRANCH_EXAMPLE_001) .setSince("7.1"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); HomepageTypes.Type type = request.mandatoryParamAsEnum(PARAM_TYPE, HomepageTypes.Type.class); String componentParameter = request.param(PARAM_COMPONENT); try (DbSession dbSession = dbClient.openSession(false)) { String parameter = getHomepageParameter(dbSession, type, componentParameter, request.param(PARAM_BRANCH)); UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, userSession.getLogin()); checkState(user != null, "User login '%s' cannot be found", userSession.getLogin()); user.setHomepageType(type.name()); user.setHomepageParameter(parameter); dbClient.userDao().update(dbSession, user); dbSession.commit(); } response.noContent(); } @CheckForNull private String getHomepageParameter(DbSession dbSession, HomepageTypes.Type type, @Nullable String componentParameter, @Nullable String branchParameter) { switch (type) { case PROJECT: checkArgument(isNotBlank(componentParameter), PARAMETER_REQUIRED, type.name(), PARAM_COMPONENT); ProjectDto projectDto = componentFinder.getProjectByKey(dbSession, componentParameter); return componentFinder.getBranchOrPullRequest(dbSession, projectDto, branchParameter, null).getUuid(); case PORTFOLIO, APPLICATION: checkArgument(isNotBlank(componentParameter), PARAMETER_REQUIRED, type.name(), PARAM_COMPONENT); return componentFinder.getByKey(dbSession, componentParameter).uuid(); case PORTFOLIOS, PROJECTS, ISSUES: return null; default: throw new IllegalArgumentException(format("Unknown type '%s'", type.name())); } } }
5,485
40.877863
156
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UpdateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import com.google.common.base.Preconditions; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.UpdateUser; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Strings.isNullOrEmpty; import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.sonar.server.user.UserUpdater.EMAIL_MAX_LENGTH; import static org.sonar.server.user.UserUpdater.LOGIN_MAX_LENGTH; import static org.sonar.server.user.UserUpdater.NAME_MAX_LENGTH; import static org.sonar.server.user.ws.CreateAction.parseScmAccounts; import static org.sonar.server.user.ws.EmailValidator.isValidIfPresent; import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_UPDATE; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_EMAIL; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_NAME; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_SCM_ACCOUNT; public class UpdateAction implements UsersWsAction { private final UserUpdater userUpdater; private final UserSession userSession; private final UserJsonWriter userWriter; private final DbClient dbClient; private final ManagedInstanceChecker managedInstanceChecker; public UpdateAction(UserUpdater userUpdater, UserSession userSession, UserJsonWriter userWriter, DbClient dbClient, ManagedInstanceChecker managedInstanceChecker) { this.userUpdater = userUpdater; this.userSession = userSession; this.userWriter = userWriter; this.dbClient = dbClient; this.managedInstanceChecker = managedInstanceChecker; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(ACTION_UPDATE) .setDescription("Update a user.<br/>" + "Requires Administer System permission") .setSince("3.7") .setChangelog( new Change("5.2", "User's password can only be changed using the 'change_password' action.")) .setPost(true) .setHandler(this) .setResponseExample(getClass().getResource("update-example.json")); action.createParam(PARAM_LOGIN) .setRequired(true) .setMaximumLength(LOGIN_MAX_LENGTH) .setDescription("User login") .setExampleValue("myuser"); action.createParam(PARAM_NAME) .setMaximumLength(NAME_MAX_LENGTH) .setDescription("User name") .setExampleValue("My Name"); action.createParam(PARAM_EMAIL) .setMaximumLength(EMAIL_MAX_LENGTH) .setDescription("User email") .setExampleValue("myname@email.com"); action.createParam(PARAM_SCM_ACCOUNT) .setDescription("SCM accounts. To set several values, the parameter must be called once for each value.") .setExampleValue("scmAccount=firstValue&scmAccount=secondValue&scmAccount=thirdValue"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); managedInstanceChecker.throwIfInstanceIsManaged(); UpdateRequest updateRequest = toWsRequest(request); checkArgument(isValidIfPresent(updateRequest.getEmail()), "Email '%s' is not valid", updateRequest.getEmail()); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = getUser(dbSession, updateRequest.getLogin()); doHandle(dbSession, updateRequest); writeUser(dbSession, response, user.getUuid()); } } private void doHandle(DbSession dbSession, UpdateRequest request) { String login = request.getLogin(); UserDto user = getUser(dbSession, login); UpdateUser updateUser = new UpdateUser(); if (request.getName() != null) { Preconditions.checkArgument(user.isLocal(), "Name cannot be updated for a non-local user"); updateUser.setName(request.getName()); } if (request.getEmail() != null) { Preconditions.checkArgument(user.isLocal(), "Email cannot be updated for a non-local user"); updateUser.setEmail(emptyToNull(request.getEmail())); } if (!request.getScmAccounts().isEmpty()) { updateUser.setScmAccounts(request.getScmAccounts()); } userUpdater.updateAndCommit(dbSession, user, updateUser, u -> { }); } private UserDto getUser(DbSession dbSession, String login) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); if (user == null || !user.isActive()) { throw new NotFoundException(format("User '%s' doesn't exist", login)); } return user; } private void writeUser(DbSession dbSession, Response response, String uuid) { try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); json.name("user"); UserDto user = dbClient.userDao().selectByUuid(dbSession, uuid); checkState(user != null, "User with uuid '%s' doesn't exist", uuid); Set<String> groups = new HashSet<>(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(uuid)).get(uuid)); userWriter.write(json, user, groups, UserJsonWriter.FIELDS); json.endObject().close(); } } private static UpdateRequest toWsRequest(Request request) { return UpdateRequest.builder() .setLogin(request.mandatoryParam(PARAM_LOGIN)) .setName(request.param(PARAM_NAME)) .setEmail(request.param(PARAM_EMAIL)) .setScmAccounts(parseScmAccounts(request)) .build(); } private static class UpdateRequest { private final String login; private final String name; private final String email; private final List<String> scmAccounts; private UpdateRequest(Builder builder) { this.login = builder.login; this.name = builder.name; this.email = builder.email; this.scmAccounts = builder.scmAccounts; } public String getLogin() { return login; } @CheckForNull public String getName() { return name; } @CheckForNull public String getEmail() { return email; } public List<String> getScmAccounts() { return scmAccounts; } public static Builder builder() { return new Builder(); } } private static class Builder { private String login; private String name; private String email; private List<String> scmAccounts = emptyList(); private Builder() { // enforce factory method use } public Builder setLogin(String login) { this.login = login; return this; } public Builder setName(@Nullable String name) { this.name = name; return this; } public Builder setEmail(@Nullable String email) { this.email = email; return this; } public Builder setScmAccounts(List<String> scmAccounts) { this.scmAccounts = scmAccounts; return this; } public UpdateRequest build() { checkArgument(!isNullOrEmpty(login), "Login is mandatory and must not be empty"); return new UpdateRequest(this); } } }
8,730
34.782787
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UpdateIdentityProviderAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.IdentityProviderRepository; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.ExternalIdentity; import org.sonar.server.user.UpdateUser; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; import static java.lang.String.format; import static org.sonar.auth.ldap.LdapRealm.DEFAULT_LDAP_IDENTITY_PROVIDER_ID; import static org.sonar.auth.ldap.LdapRealm.LDAP_SECURITY_REALM; import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY; import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_UPDATE_IDENTITY_PROVIDER; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_NEW_EXTERNAL_IDENTITY; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_NEW_EXTERNAL_PROVIDER; public class UpdateIdentityProviderAction implements UsersWsAction { private final DbClient dbClient; private final IdentityProviderRepository identityProviderRepository; private final UserUpdater userUpdater; private final UserSession userSession; private final ManagedInstanceChecker managedInstanceChecker; public UpdateIdentityProviderAction(DbClient dbClient, IdentityProviderRepository identityProviderRepository, UserUpdater userUpdater, UserSession userSession, ManagedInstanceChecker managedInstanceChecker) { this.dbClient = dbClient; this.identityProviderRepository = identityProviderRepository; this.userUpdater = userUpdater; this.userSession = userSession; this.managedInstanceChecker = managedInstanceChecker; } @Override public void define(NewController controller) { WebService.NewAction action = controller.createAction(ACTION_UPDATE_IDENTITY_PROVIDER) .setDescription("Update identity provider information. <br/>" + "It's only possible to migrate to an installed identity provider. " + "Be careful that as soon as this information has been updated for a user, " + "the user will only be able to authenticate on the new identity provider. " + "It is not possible to migrate external user to local one.<br/>" + "Requires Administer System permission.") .setSince("8.7") .setInternal(false) .setPost(true) .setHandler(this); action.createParam(PARAM_LOGIN) .setDescription("User login") .setRequired(true); action.createParam(PARAM_NEW_EXTERNAL_PROVIDER) .setRequired(true) .setDescription("New external provider. Only authentication system installed are available. " + "Use 'LDAP' identity provider for single server LDAP setup." + "User 'LDAP_{serverKey}' identity provider for multiple LDAP server setup."); action.setChangelog( new Change("9.8", String.format("Use of 'sonarqube' for the value of '%s' is deprecated.", PARAM_NEW_EXTERNAL_PROVIDER))); action.createParam(PARAM_NEW_EXTERNAL_IDENTITY) .setDescription("New external identity, usually the login used in the authentication system. " + "If not provided previous identity will be used."); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); managedInstanceChecker.throwIfInstanceIsManaged(); UpdateIdentityProviderRequest wsRequest = toWsRequest(request); doHandle(wsRequest); response.noContent(); } private void doHandle(UpdateIdentityProviderRequest request) { checkEnabledIdentityProviders(request.newExternalProvider); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = getUser(dbSession, request.login); ExternalIdentity externalIdentity = getExternalIdentity(request, user); userUpdater.updateAndCommit(dbSession, user, new UpdateUser().setExternalIdentity(externalIdentity), u -> { }); } } private void checkEnabledIdentityProviders(String newExternalProvider) { List<String> allowedIdentityProviders = getAvailableIdentityProviders(); boolean isAllowedProvider = allowedIdentityProviders.contains(newExternalProvider) || isLdapIdentityProvider(newExternalProvider); checkArgument(isAllowedProvider, "Value of parameter 'newExternalProvider' (%s) must be one of: [%s] or [%s]", newExternalProvider, String.join(", ", allowedIdentityProviders), String.join(", ", "LDAP", "LDAP_{serverKey}")); } private List<String> getAvailableIdentityProviders() { return identityProviderRepository.getAllEnabledAndSorted() .stream() .map(IdentityProvider::getKey) .toList(); } private static boolean isLdapIdentityProvider(String identityProviderKey) { return identityProviderKey.startsWith(LDAP_SECURITY_REALM + "_"); } private UserDto getUser(DbSession dbSession, String login) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); if (user == null || !user.isActive()) { throw new NotFoundException(format("User '%s' doesn't exist", login)); } return user; } private static ExternalIdentity getExternalIdentity(UpdateIdentityProviderRequest request, UserDto user) { return new ExternalIdentity( request.newExternalProvider, request.newExternalIdentity != null ? request.newExternalIdentity : user.getExternalLogin(), null); } private static UpdateIdentityProviderRequest toWsRequest(Request request) { return UpdateIdentityProviderRequest.builder() .setLogin(request.mandatoryParam(PARAM_LOGIN)) .setNewExternalProvider(replaceDeprecatedSonarqubeIdentityProviderByLdapForSonar17508(request.mandatoryParam(PARAM_NEW_EXTERNAL_PROVIDER))) .setNewExternalIdentity(request.param(PARAM_NEW_EXTERNAL_IDENTITY)) .build(); } private static String replaceDeprecatedSonarqubeIdentityProviderByLdapForSonar17508(String newExternalProvider) { return newExternalProvider.equals(SQ_AUTHORITY) || newExternalProvider.equals(LDAP_SECURITY_REALM) ? DEFAULT_LDAP_IDENTITY_PROVIDER_ID : newExternalProvider; } static class UpdateIdentityProviderRequest { private final String login; private final String newExternalProvider; private final String newExternalIdentity; public UpdateIdentityProviderRequest(Builder builder) { this.login = builder.login; this.newExternalProvider = builder.newExternalProvider; this.newExternalIdentity = builder.newExternalIdentity; } public static UpdateIdentityProviderRequest.Builder builder() { return new UpdateIdentityProviderRequest.Builder(); } static class Builder { private String login; private String newExternalProvider; private String newExternalIdentity; private Builder() { // enforce factory method use } public Builder setLogin(String login) { this.login = login; return this; } public Builder setNewExternalProvider(String newExternalProvider) { this.newExternalProvider = newExternalProvider; return this; } public Builder setNewExternalIdentity(@Nullable String newExternalIdentity) { this.newExternalIdentity = newExternalIdentity; return this; } public UpdateIdentityProviderRequest build() { checkArgument(!isNullOrEmpty(login), "Login is mandatory and must not be empty"); checkArgument(!isNullOrEmpty(newExternalProvider), "New External Provider is mandatory and must not be empty"); return new UpdateIdentityProviderRequest(this); } } } }
9,126
41.649533
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UpdateLoginAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.UpdateUser; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; import static java.lang.String.format; import static org.sonar.server.user.UserUpdater.LOGIN_MAX_LENGTH; import static org.sonar.server.user.UserUpdater.LOGIN_MIN_LENGTH; public class UpdateLoginAction implements UsersWsAction { public static final String PARAM_LOGIN = "login"; public static final String PARAM_NEW_LOGIN = "newLogin"; private final DbClient dbClient; private final UserSession userSession; private final UserUpdater userUpdater; private final ManagedInstanceChecker managedInstanceChecker; public UpdateLoginAction(DbClient dbClient, UserSession userSession, UserUpdater userUpdater, ManagedInstanceChecker managedInstanceChecker) { this.dbClient = dbClient; this.userSession = userSession; this.userUpdater = userUpdater; this.managedInstanceChecker = managedInstanceChecker; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("update_login") .setDescription("Update a user login. A login can be updated many times.<br/>" + "Requires Administer System permission") .setSince("7.6") .setPost(true) .setHandler(this); action.createParam(PARAM_LOGIN) .setRequired(true) .setDescription("The current login (case-sensitive)") .setExampleValue("mylogin"); action.createParam(PARAM_NEW_LOGIN) .setRequired(true) .setMaximumLength(LOGIN_MAX_LENGTH) .setMinimumLength(LOGIN_MIN_LENGTH) .setDescription("The new login. It must not already exist.") .setExampleValue("mynewlogin"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); managedInstanceChecker.throwIfInstanceIsManaged(); String login = request.mandatoryParam(PARAM_LOGIN); String newLogin = request.mandatoryParam(PARAM_NEW_LOGIN); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = getUser(dbSession, login); userUpdater.updateAndCommit(dbSession, user, new UpdateUser().setLogin(newLogin), u -> { }); response.noContent(); } } private UserDto getUser(DbSession dbSession, String login) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); if (user == null || !user.isActive()) { throw new NotFoundException(format("User '%s' doesn't exist", login)); } return user; } }
3,805
36.683168
95
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UserAnonymizer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.function.Supplier; import javax.inject.Inject; import org.apache.commons.lang.RandomStringUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.user.ExternalIdentity; public class UserAnonymizer { private static final int LOGIN_RANDOM_LENGTH = 6; private final DbClient dbClient; private final Supplier<String> randomNameGenerator; @Inject public UserAnonymizer(DbClient dbClient) { this(dbClient, () -> "sq-removed-" + RandomStringUtils.randomAlphanumeric(LOGIN_RANDOM_LENGTH)); } public UserAnonymizer(DbClient dbClient, Supplier<String> randomNameGenerator) { this.dbClient = dbClient; this.randomNameGenerator = randomNameGenerator; } public void anonymize(DbSession session, UserDto user) { String newLogin = generateAnonymousLogin(session); user .setLogin(newLogin) .setName(newLogin) .setExternalIdentityProvider(ExternalIdentity.SQ_AUTHORITY) .setLocal(true) .setExternalId(newLogin) .setExternalLogin(newLogin); } private String generateAnonymousLogin(DbSession session) { for (int i = 0; i < 10; i++) { String candidate = randomNameGenerator.get(); if (dbClient.userDao().selectByLogin(session, candidate) == null) { return candidate; } } throw new IllegalStateException("Could not find a unique login"); } }
2,310
33.492537
100
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UserDeactivator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyQuery; import org.sonar.db.user.UserDto; import static org.sonar.api.CoreProperties.DEFAULT_ISSUE_ASSIGNEE; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.NotFoundException.checkFound; public class UserDeactivator { private final DbClient dbClient; private final UserAnonymizer userAnonymizer; public UserDeactivator(DbClient dbClient, UserAnonymizer userAnonymizer) { this.dbClient = dbClient; this.userAnonymizer = userAnonymizer; } public UserDto deactivateUser(DbSession dbSession, String login) { UserDto user = doBeforeDeactivation(dbSession, login); deactivateUser(dbSession, user); return user; } public UserDto deactivateUserWithAnonymization(DbSession dbSession, String login) { UserDto user = doBeforeDeactivation(dbSession, login); anonymizeUser(dbSession, user); deactivateUser(dbSession, user); return user; } private UserDto doBeforeDeactivation(DbSession dbSession, String login) { UserDto user = getUserOrThrow(dbSession, login); ensureNotLastAdministrator(dbSession, user); deleteRelatedData(dbSession, user); return user; } private UserDto getUserOrThrow(DbSession dbSession, String login) { UserDto user = dbClient.userDao().selectByLogin(dbSession, login); return checkFound(user, "User '%s' doesn't exist", login); } private void ensureNotLastAdministrator(DbSession dbSession, UserDto user) { boolean isLastAdmin = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingUser(dbSession, ADMINISTER.getKey(), user.getUuid()) == 0; checkRequest(!isLastAdmin, "User is last administrator, and cannot be deactivated"); } private void deleteRelatedData(DbSession dbSession, UserDto user) { String userUuid = user.getUuid(); dbClient.userTokenDao().deleteByUser(dbSession, user); dbClient.propertiesDao().deleteByKeyAndValue(dbSession, DEFAULT_ISSUE_ASSIGNEE, user.getLogin()); dbClient.propertiesDao().deleteByQuery(dbSession, PropertyQuery.builder().setUserUuid(userUuid).build()); dbClient.userGroupDao().deleteByUserUuid(dbSession, user); dbClient.userPermissionDao().deleteByUserUuid(dbSession, user); dbClient.permissionTemplateDao().deleteUserPermissionsByUserUuid(dbSession, userUuid, user.getLogin()); dbClient.qProfileEditUsersDao().deleteByUser(dbSession, user); dbClient.almPatDao().deleteByUser(dbSession, user); dbClient.sessionTokensDao().deleteByUser(dbSession, user); dbClient.userDismissedMessagesDao().deleteByUser(dbSession, user); dbClient.qualityGateUserPermissionDao().deleteByUser(dbSession, user); } private void anonymizeUser(DbSession dbSession, UserDto user) { userAnonymizer.anonymize(dbSession, user); dbClient.userDao().update(dbSession, user); dbClient.scimUserDao().deleteByUserUuid(dbSession, user.getUuid()); } private void deactivateUser(DbSession dbSession, UserDto user) { dbClient.userDao().deactivateUser(dbSession, user); dbSession.commit(); } }
4,116
41.443299
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UserJsonWriter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Collections; import java.util.Set; import javax.annotation.Nullable; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.user.UserDto; import org.sonar.server.user.UserSession; import static java.util.Optional.ofNullable; import static org.sonar.server.ws.JsonWriterUtils.isFieldNeeded; import static org.sonar.server.ws.JsonWriterUtils.writeIfNeeded; public class UserJsonWriter { static final String FIELD_LOGIN = "login"; static final String FIELD_NAME = "name"; static final String FIELD_EMAIL = "email"; static final String FIELD_AVATAR = "avatart"; static final String FIELD_SCM_ACCOUNTS = "scmAccounts"; static final String FIELD_GROUPS = "groups"; static final String FIELD_ACTIVE = "active"; static final String FIELD_TOKENS_COUNT = "tokensCount"; static final String FIELD_LOCAL = "local"; static final String FIELD_EXTERNAL_IDENTITY = "externalIdentity"; static final String FIELD_EXTERNAL_PROVIDER = "externalProvider"; public static final Set<String> FIELDS = ImmutableSet.of(FIELD_NAME, FIELD_EMAIL, FIELD_AVATAR, FIELD_SCM_ACCOUNTS, FIELD_GROUPS, FIELD_ACTIVE, FIELD_LOCAL, FIELD_EXTERNAL_IDENTITY, FIELD_EXTERNAL_PROVIDER); private static final Set<String> CONCISE_FIELDS = ImmutableSet.of(FIELD_NAME, FIELD_EMAIL, FIELD_ACTIVE); private final UserSession userSession; public UserJsonWriter(UserSession userSession) { this.userSession = userSession; } /** * Serializes a user to the passed JsonWriter. */ public void write(JsonWriter json, UserDto user, Collection<String> groups, @Nullable Collection<String> fields) { json.beginObject(); json.prop(FIELD_LOGIN, user.getLogin()); ofNullable(user.getName()).ifPresent(name -> writeIfNeeded(json, name, FIELD_NAME, fields)); if (userSession.isLoggedIn()) { writeIfNeeded(json, user.getEmail(), FIELD_EMAIL, fields); writeIfNeeded(json, user.isActive(), FIELD_ACTIVE, fields); writeIfNeeded(json, user.isLocal(), FIELD_LOCAL, fields); writeIfNeeded(json, user.getExternalLogin(), FIELD_EXTERNAL_IDENTITY, fields); writeIfNeeded(json, user.getExternalIdentityProvider(), FIELD_EXTERNAL_PROVIDER, fields); writeGroupsIfNeeded(json, groups, fields); writeScmAccountsIfNeeded(json, fields, user); } json.endObject(); } /** * A shortcut to {@link #write(JsonWriter, UserDto, Collection, Collection)} with preselected fields and without group information */ public void write(JsonWriter json, @Nullable UserDto user) { if (user == null) { json.beginObject().endObject(); } else { write(json, user, Collections.emptySet(), CONCISE_FIELDS); } } private void writeGroupsIfNeeded(JsonWriter json, Collection<String> groups, @Nullable Collection<String> fields) { if (isFieldNeeded(FIELD_GROUPS, fields) && userSession.isSystemAdministrator()) { json.name(FIELD_GROUPS).beginArray(); for (String groupName : groups) { json.value(groupName); } json.endArray(); } } private static void writeScmAccountsIfNeeded(JsonWriter json, Collection<String> fields, UserDto user) { if (isFieldNeeded(FIELD_SCM_ACCOUNTS, fields)) { json.name(FIELD_SCM_ACCOUNTS) .beginArray() .values(user.getSortedScmAccounts()) .endArray(); } } }
4,305
38.504587
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UsersWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import java.util.Collection; import org.sonar.api.server.ws.WebService; public class UsersWs implements WebService { static final String API_USERS = "api/users"; static final String DESCRIPTION = "Manage users."; static final String SINCE_VERSION = "3.6"; private final Collection<BaseUsersWsAction> usersWsActions; public UsersWs(Collection<BaseUsersWsAction> usersWsActions) { this.usersWsActions = usersWsActions; } @Override public void define(Context context) { NewController controller = context.createController(API_USERS) .setSince(SINCE_VERSION) .setDescription(DESCRIPTION); usersWsActions.forEach(action -> action.define(controller)); controller.done(); } }
1,599
33.042553
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UsersWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import org.sonar.server.ws.WsAction; public interface UsersWsAction extends WsAction, BaseUsersWsAction { // Marker interface for UsersWs actions }
1,029
37.148148
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/UsersWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.user.ws; import org.sonar.core.platform.Module; public class UsersWsModule extends Module { @Override protected void configureModule() { add( UsersWs.class, AnonymizeAction.class, CreateAction.class, UpdateAction.class, UpdateLoginAction.class, DeactivateAction.class, UserDeactivator.class, ChangePasswordAction.class, CurrentAction.class, SearchAction.class, GroupsAction.class, IdentityProvidersAction.class, UserJsonWriter.class, SetHomepageAction.class, HomepageTypesImpl.class, UserAnonymizer.class, UpdateIdentityProviderAction.class, DismissNoticeAction.class); } }
1,564
30.3
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.user.ws; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/AddUserAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserGroupDto; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_LOGIN; import static org.sonar.server.usergroups.ws.GroupWsSupport.defineGroupWsParameters; import static org.sonar.server.usergroups.ws.GroupWsSupport.defineLoginWsParameter; public class AddUserAction implements UserGroupsWsAction { private final DbClient dbClient; private final UserSession userSession; private final GroupWsSupport support; private final ManagedInstanceChecker managedInstanceChecker; public AddUserAction(DbClient dbClient, UserSession userSession, GroupWsSupport support, ManagedInstanceChecker managedInstanceChecker) { this.dbClient = dbClient; this.userSession = userSession; this.support = support; this.managedInstanceChecker = managedInstanceChecker; } @Override public void define(NewController context) { NewAction action = context.createAction("add_user") .setDescription(format("Add a user to a group.<br />" + "'%s' must be provided.<br />" + "Requires the following permission: 'Administer System'.", PARAM_GROUP_NAME)) .setHandler(this) .setPost(true) .setSince("5.2") .setChangelog( new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."), new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead.")); defineGroupWsParameters(action); defineLoginWsParameter(action); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(ADMINISTER); managedInstanceChecker.throwIfInstanceIsManaged(); GroupDto group = support.findGroupDto(dbSession, request); String login = request.mandatoryParam(PARAM_LOGIN); UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login); checkFound(user, "Could not find a user with login '%s'", login); support.checkGroupIsNotDefault(dbSession, group); if (!isMemberOf(dbSession, user, group)) { UserGroupDto membershipDto = new UserGroupDto().setGroupUuid(group.getUuid()).setUserUuid(user.getUuid()); dbClient.userGroupDao().insert(dbSession, membershipDto, group.getName(), login); dbSession.commit(); } response.noContent(); } } private boolean isMemberOf(DbSession dbSession, UserDto user, GroupDto group) { return dbClient.groupMembershipDao().selectGroupUuidsByUserUuid(dbSession, user.getUuid()).contains(group.getUuid()); } }
4,237
40.960396
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/CreateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.UserSession; import org.sonarqube.ws.UserGroups; import static java.lang.String.format; import static org.sonar.api.user.UserGroupValidation.GROUP_NAME_MAX_LENGTH; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.usergroups.ws.GroupWsSupport.DESCRIPTION_MAX_LENGTH; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_DESCRIPTION; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.toProtobuf; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class CreateAction implements UserGroupsWsAction { private final DbClient dbClient; private final UserSession userSession; private final GroupService groupService; private final ManagedInstanceChecker managedInstanceChecker; public CreateAction(DbClient dbClient, UserSession userSession, GroupService groupService, ManagedInstanceChecker managedInstanceService) { this.dbClient = dbClient; this.userSession = userSession; this.groupService = groupService; this.managedInstanceChecker = managedInstanceService; } @Override public void define(NewController controller) { NewAction action = controller.createAction("create") .setDescription("Create a group.<br>" + "Requires the following permission: 'Administer System'.") .setHandler(this) .setPost(true) .setResponseExample(getClass().getResource("create-example.json")) .setSince("5.2") .setChangelog( new Change("8.4", "Field 'id' format in the response changes from integer to string.")); action.createParam(PARAM_GROUP_NAME) .setRequired(true) .setMaximumLength(GROUP_NAME_MAX_LENGTH) .setDescription(format("Name for the new group. A group name cannot be larger than %d characters and must be unique. " + "The value 'anyone' (whatever the case) is reserved and cannot be used.", GROUP_NAME_MAX_LENGTH)) .setExampleValue("sonar-users"); action.createParam(PARAM_GROUP_DESCRIPTION) .setMaximumLength(DESCRIPTION_MAX_LENGTH) .setDescription(format("Description for the new group. A group description cannot be larger than %d characters.", DESCRIPTION_MAX_LENGTH)) .setExampleValue("Default group for new users"); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkPermission(ADMINISTER); managedInstanceChecker.throwIfInstanceIsManaged(); String groupName = request.mandatoryParam(PARAM_GROUP_NAME); String groupDescription = request.param(PARAM_GROUP_DESCRIPTION); GroupDto group = groupService.createGroup(dbSession, groupName, groupDescription); dbSession.commit(); writeResponse(request, response, group); } } private static void writeResponse(Request request, Response response, GroupDto group) { UserGroups.CreateWsResponse.Builder respBuilder = UserGroups.CreateWsResponse.newBuilder(); // 'default' is always false as it's not possible to create a default group respBuilder.setGroup(toProtobuf(group, 0, false)); writeProtobuf(respBuilder.build(), request, response); } }
4,589
43.563107
144
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/DeleteAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.Set; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.defineGroupWsParameters; public class DeleteAction implements UserGroupsWsAction { private final DbClient dbClient; private final UserSession userSession; private final GroupService groupService; private final ManagedInstanceService managedInstanceService; public DeleteAction(DbClient dbClient, UserSession userSession, GroupService groupService, ManagedInstanceService managedInstanceService) { this.dbClient = dbClient; this.userSession = userSession; this.groupService = groupService; this.managedInstanceService = managedInstanceService; } @Override public void define(NewController context) { WebService.NewAction action = context.createAction("delete") .setDescription(format("Delete a group. The default groups cannot be deleted.<br/>" + "'%s' must be provided.<br />" + "Requires the following permission: 'Administer System'.", PARAM_GROUP_NAME)) .setHandler(this) .setSince("5.2") .setPost(true) .setChangelog( new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."), new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead.")); defineGroupWsParameters(action); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkPermission(GlobalPermission.ADMINISTER); GroupDto group = findGroupOrThrow(request, dbSession); checkIfInstanceAndGroupAreManaged(dbSession, group); groupService.delete(dbSession, group); dbSession.commit(); response.noContent(); } } private void checkIfInstanceAndGroupAreManaged(DbSession dbSession, GroupDto group) { boolean isGroupManaged = managedInstanceService.getGroupUuidToManaged(dbSession, Set.of(group.getUuid())).getOrDefault(group.getUuid(), false); if (isGroupManaged) { throw BadRequestException.create("Deleting managed groups is not allowed."); } } private GroupDto findGroupOrThrow(Request request, DbSession dbSession) { String groupName = request.mandatoryParam(PARAM_GROUP_NAME); return groupService.findGroup(dbSession, groupName) .orElseThrow(() -> new NotFoundException(format("No group with name '%s'", groupName))); } }
4,008
40.329897
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/ExternalGroupService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.ExternalGroupDto; import org.sonar.db.user.GroupDto; public class ExternalGroupService { private static final Logger LOG = LoggerFactory.getLogger(ExternalGroupService.class); private final DbClient dbClient; private final GroupService groupService; public ExternalGroupService(DbClient dbClient, GroupService groupService) { this.dbClient = dbClient; this.groupService = groupService; } public void createOrUpdateExternalGroup(DbSession dbSession, GroupRegistration groupRegistration) { Optional<GroupDto> groupDto = retrieveGroupByExternalInformation(dbSession, groupRegistration); if (groupDto.isPresent()) { updateExternalGroup(dbSession, groupDto.get(), groupRegistration.name()); } else { createOrMatchExistingLocalGroup(dbSession, groupRegistration); } } private Optional<GroupDto> retrieveGroupByExternalInformation(DbSession dbSession, GroupRegistration groupRegistration) { Optional<ExternalGroupDto> externalGroupDto = dbClient.externalGroupDao().selectByExternalIdAndIdentityProvider(dbSession, groupRegistration.externalId(), groupRegistration.externalIdentityProvider()); return externalGroupDto.flatMap(existingExternalGroupDto -> Optional.ofNullable(dbClient.groupDao().selectByUuid(dbSession, existingExternalGroupDto.groupUuid()))); } private void updateExternalGroup(DbSession dbSession, GroupDto groupDto, String newName) { LOG.debug("Updating external group: {} with new name {}", groupDto.getName(), newName); groupService.updateGroup(dbSession, groupDto, newName); } private void createOrMatchExistingLocalGroup(DbSession dbSession, GroupRegistration groupRegistration) { GroupDto groupDto = findOrCreateLocalGroup(dbSession, groupRegistration); createExternalGroup(dbSession, groupDto.getUuid(), groupRegistration); } private GroupDto findOrCreateLocalGroup(DbSession dbSession, GroupRegistration groupRegistration) { Optional<GroupDto> groupDto = groupService.findGroup(dbSession, groupRegistration.name()); if (groupDto.isPresent()) { LOG.debug("Marking existing local group {} as managed group.", groupDto.get().getName()); return groupDto.get(); } else { LOG.debug("Creating new group {}", groupRegistration.name()); return groupService.createGroup(dbSession, groupRegistration.name(), null); } } private void createExternalGroup(DbSession dbSession, String groupUuid, GroupRegistration groupRegistration) { dbClient.externalGroupDao().insert(dbSession, new ExternalGroupDto(groupUuid, groupRegistration.externalId(), groupRegistration.externalIdentityProvider())); } }
3,707
43.674699
168
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/GroupRegistration.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; public record GroupRegistration(String externalId, String externalIdentityProvider, String name) { }
985
40.083333
98
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/GroupService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.api.security.DefaultGroups; import org.sonar.api.server.ServerSide; import org.sonar.api.user.UserGroupValidation; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.exceptions.BadRequestException.checkRequest; @ServerSide public class GroupService { private final DbClient dbClient; private final UuidFactory uuidFactory; public GroupService(DbClient dbClient, UuidFactory uuidFactory) { this.dbClient = dbClient; this.uuidFactory = uuidFactory; } public Optional<GroupDto> findGroup(DbSession dbSession, String groupName) { return dbClient.groupDao().selectByName(dbSession, groupName); } public void delete(DbSession dbSession, GroupDto group) { checkGroupIsNotDefault(dbSession, group); checkNotTryingToDeleteLastAdminGroup(dbSession, group); removeGroupPermissions(dbSession, group); removeGroupFromPermissionTemplates(dbSession, group); removeGroupMembers(dbSession, group); removeGroupFromQualityProfileEdit(dbSession, group); removeGroupFromQualityGateEdit(dbSession, group); removeGroupScimLink(dbSession, group); removeExternalGroupMapping(dbSession, group); removeGroup(dbSession, group); } public GroupDto updateGroup(DbSession dbSession, GroupDto group, @Nullable String newName) { checkGroupIsNotDefault(dbSession, group); return updateName(dbSession, group, newName); } public GroupDto updateGroup(DbSession dbSession, GroupDto group, @Nullable String newName, @Nullable String newDescription) { checkGroupIsNotDefault(dbSession, group); GroupDto withUpdatedName = updateName(dbSession, group, newName); return updateDescription(dbSession, withUpdatedName, newDescription); } public GroupDto createGroup(DbSession dbSession, String name, @Nullable String description) { validateGroupName(name); checkNameDoesNotExist(dbSession, name); GroupDto group = new GroupDto() .setUuid(uuidFactory.create()) .setName(name) .setDescription(description); return dbClient.groupDao().insert(dbSession, group); } private GroupDto updateName(DbSession dbSession, GroupDto group, @Nullable String newName) { if (newName != null && !newName.equals(group.getName())) { validateGroupName(newName); checkNameDoesNotExist(dbSession, newName); group.setName(newName); return dbClient.groupDao().update(dbSession, group); } return group; } private static void validateGroupName(String name) { try { UserGroupValidation.validateGroupName(name); } catch (IllegalArgumentException e) { BadRequestException.throwBadRequestException(e.getMessage()); } } private void checkNameDoesNotExist(DbSession dbSession, String name) { // There is no database constraint on column groups.name // because MySQL cannot create a unique index // on a UTF-8 VARCHAR larger than 255 characters on InnoDB checkRequest(!dbClient.groupDao().selectByName(dbSession, name).isPresent(), "Group '%s' already exists", name); } private GroupDto updateDescription(DbSession dbSession, GroupDto group, @Nullable String newDescription) { if (newDescription != null) { group.setDescription(newDescription); return dbClient.groupDao().update(dbSession, group); } return group; } private void checkGroupIsNotDefault(DbSession dbSession, GroupDto groupDto) { GroupDto defaultGroup = findDefaultGroup(dbSession); checkArgument(!defaultGroup.getUuid().equals(groupDto.getUuid()), "Default group '%s' cannot be used to perform this action", groupDto.getName()); } private GroupDto findDefaultGroup(DbSession dbSession) { return dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS) .orElseThrow(() -> new IllegalStateException("Default group cannot be found")); } private void checkNotTryingToDeleteLastAdminGroup(DbSession dbSession, GroupDto group) { int remaining = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroup(dbSession, GlobalPermission.ADMINISTER.getKey(), group.getUuid()); checkArgument(remaining > 0, "The last system admin group cannot be deleted"); } private void removeGroupPermissions(DbSession dbSession, GroupDto group) { dbClient.roleDao().deleteGroupRolesByGroupUuid(dbSession, group.getUuid()); } private void removeGroupFromPermissionTemplates(DbSession dbSession, GroupDto group) { dbClient.permissionTemplateDao().deleteByGroup(dbSession, group.getUuid(), group.getName()); } private void removeGroupMembers(DbSession dbSession, GroupDto group) { dbClient.userGroupDao().deleteByGroupUuid(dbSession, group.getUuid(), group.getName()); } private void removeGroupFromQualityProfileEdit(DbSession dbSession, GroupDto group) { dbClient.qProfileEditGroupsDao().deleteByGroup(dbSession, group); } private void removeGroupFromQualityGateEdit(DbSession dbSession, GroupDto group) { dbClient.qualityGateGroupPermissionsDao().deleteByGroup(dbSession, group); } private void removeGroupScimLink(DbSession dbSession, GroupDto group) { dbClient.scimGroupDao().deleteByGroupUuid(dbSession, group.getUuid()); } private void removeExternalGroupMapping(DbSession dbSession, GroupDto group) { dbClient.externalGroupDao().deleteByGroupUuid(dbSession, group.getUuid()); } private void removeGroup(DbSession dbSession, GroupDto group) { dbClient.groupDao().deleteByUuid(dbSession, group.getUuid(), group.getName()); } }
6,744
38.444444
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/GroupWsRef.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.security.DefaultGroups; import org.sonar.server.permission.GroupUuid; import org.sonar.server.permission.GroupUuidOrAnyone; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import static org.sonar.server.exceptions.BadRequestException.checkRequest; /** * Reference to a user group <b>as declared by web service requests</b>. It is one, and only one, * of these two options: * <ul> * <li>group uuid, for instance 1234</li> * <li>group name</li> * </ul> * * The reference is then converted to a {@link GroupUuid} or {@link GroupUuidOrAnyone}. */ @Immutable public class GroupWsRef { private final String uuid; private final String name; private GroupWsRef(@Nullable String uuid, @Nullable String name) { this.uuid = uuid; this.name = name; } /** * @return {@code true} if uuid is defined and {@link #getUuid()} can be called. If {@code false}, then * the name is defined and the method {@link #getName()} can be called. */ public boolean hasUuid() { return uuid != null; } /** * @return the group uuid * @throws IllegalStateException if {@link #hasUuid()} is {@code false} */ public String getUuid() { checkState(hasUuid(), "Id is not present. Please see hasUuid()."); return uuid; } /** * @return the non-null group name. Can be anyone. * @throws IllegalStateException if {@link #getUuid()} is {@code true} */ public String getName() { checkState(!hasUuid(), "Name is not present. Please see hasId()."); return name; } /** * Creates a reference to a group by its uuid. Virtual groups "Anyone" can't be returned * as they can't be referenced by an uuid. */ static GroupWsRef fromUuid(String uuid) { return new GroupWsRef(uuid, null); } /** * Creates a reference to a group by its name. Virtual groups "Anyone" are * supported. * * @param name non-null name. Can refer to anyone group (case-insensitive {@code "anyone"}). */ static GroupWsRef fromName(String name) { return new GroupWsRef(null, requireNonNull(name)); } public static GroupWsRef create(@Nullable String uuid, @Nullable String name) { if (uuid != null) { checkRequest(name == null, "Either group id or group name must be set"); return fromUuid(uuid); } checkRequest(name != null, "Group name or group id must be provided"); return fromName(name); } public boolean isAnyone() { return !hasUuid() && DefaultGroups.isAnyone(name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GroupWsRef that = (GroupWsRef) o; return Objects.equals(uuid, that.uuid) && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(uuid, name); } @Override public String toString() { return "GroupWsRef{uuid=" + uuid + ", name='" + name + "'}"; } }
4,043
29.179104
105
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/GroupWsSupport.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.Optional; import org.sonar.api.security.DefaultGroups; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.GroupUuid; import org.sonar.server.permission.GroupUuidOrAnyone; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonarqube.ws.UserGroups; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Optional.ofNullable; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; /** * Factorizes code about user groups between web services */ public class GroupWsSupport { static final String PARAM_GROUP_ID = "id"; static final String PARAM_GROUP_NAME = "name"; static final String PARAM_GROUP_CURRENT_NAME = "currentName"; static final String PARAM_GROUP_DESCRIPTION = "description"; static final String PARAM_LOGIN = "login"; // Database column size should be 500 (since migration #353), // but on some instances, column size is still 200, // hence the validation is done with 200 static final int DESCRIPTION_MAX_LENGTH = 200; private final DbClient dbClient; private final DefaultGroupFinder defaultGroupFinder; public GroupWsSupport(DbClient dbClient, DefaultGroupFinder defaultGroupFinder) { this.dbClient = dbClient; this.defaultGroupFinder = defaultGroupFinder; } /** * Find a group by its group name (parameter {@link #PARAM_GROUP_NAME}). The virtual * group "Anyone" is not supported. * * @throws NotFoundException if parameters are missing/incorrect, if the requested group does not exist * or if the virtual group "Anyone" is requested. */ public GroupUuid findGroup(DbSession dbSession, Request request) { return GroupUuid.from(findGroupDto(dbSession, request)); } public GroupDto findGroupDto(DbSession dbSession, Request request) { String groupName = request.mandatoryParam(PARAM_GROUP_NAME); return findGroupDto(dbSession, groupName); } public GroupDto findGroupDto(DbSession dbSession, String groupName) { Optional<GroupDto> group = dbClient.groupDao().selectByName(dbSession, groupName); checkFoundWithOptional(group, "No group with name '%s'", groupName); return group.get(); } public GroupUuidOrAnyone findGroupOrAnyone(DbSession dbSession, String groupName) { if (DefaultGroups.isAnyone(groupName)) { return GroupUuidOrAnyone.forAnyone(); } Optional<GroupDto> group = dbClient.groupDao().selectByName(dbSession, groupName); checkFoundWithOptional(group, "No group with name '%s'", groupName); return GroupUuidOrAnyone.from(group.get()); } void checkGroupIsNotDefault(DbSession dbSession, GroupDto groupDto) { GroupDto defaultGroup = defaultGroupFinder.findDefaultGroup(dbSession); checkArgument(!defaultGroup.getUuid().equals(groupDto.getUuid()), "Default group '%s' cannot be used to perform this action", groupDto.getName()); } static UserGroups.Group.Builder toProtobuf(GroupDto group, int membersCount, boolean isDefault) { UserGroups.Group.Builder wsGroup = UserGroups.Group.newBuilder() .setId(group.getUuid()) .setName(group.getName()) .setMembersCount(membersCount) .setDefault(isDefault); ofNullable(group.getDescription()).ifPresent(wsGroup::setDescription); return wsGroup; } static void defineGroupWsParameters(WebService.NewAction action) { defineGroupNameWsParameter(action); } private static void defineGroupNameWsParameter(WebService.NewAction action) { action.createParam(PARAM_GROUP_NAME) .setRequired(true) .setDescription("Group name") .setExampleValue("sonar-administrators"); } static WebService.NewParam defineLoginWsParameter(WebService.NewAction action) { return action.createParam(PARAM_LOGIN) .setDescription("User login") .setExampleValue("g.hopper"); } }
4,949
37.372093
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/RemoveUserAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_LOGIN; import static org.sonar.server.usergroups.ws.GroupWsSupport.defineGroupWsParameters; import static org.sonar.server.usergroups.ws.GroupWsSupport.defineLoginWsParameter; public class RemoveUserAction implements UserGroupsWsAction { private final DbClient dbClient; private final UserSession userSession; private final GroupWsSupport support; private final ManagedInstanceChecker managedInstanceChecker; public RemoveUserAction(DbClient dbClient, UserSession userSession, GroupWsSupport support, ManagedInstanceChecker managedInstanceChecker) { this.dbClient = dbClient; this.userSession = userSession; this.support = support; this.managedInstanceChecker = managedInstanceChecker; } @Override public void define(NewController context) { NewAction action = context.createAction("remove_user") .setDescription(format("Remove a user from a group.<br />" + "'%s' must be provided.<br>" + "Requires the following permission: 'Administer System'.", PARAM_GROUP_NAME)) .setHandler(this) .setPost(true) .setSince("5.2") .setChangelog( new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."), new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead.")); defineGroupWsParameters(action); defineLoginWsParameter(action); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkPermission(GlobalPermission.ADMINISTER); managedInstanceChecker.throwIfInstanceIsManaged(); GroupDto group = support.findGroupDto(dbSession, request); support.checkGroupIsNotDefault(dbSession, group); String login = request.mandatoryParam(PARAM_LOGIN); UserDto user = getUser(dbSession, login); ensureLastAdminIsNotRemoved(dbSession, group, user); dbClient.userGroupDao().delete(dbSession, group, user); dbSession.commit(); response.noContent(); } } /** * Ensure that there are still users with admin global permission if user is removed from the group. */ private void ensureLastAdminIsNotRemoved(DbSession dbSession, GroupDto group, UserDto user) { int remainingAdmins = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroupMember(dbSession, GlobalPermission.ADMINISTER.getKey(), group.getUuid(), user.getUuid()); checkRequest(remainingAdmins > 0, "The last administrator user cannot be removed"); } private UserDto getUser(DbSession dbSession, String userLogin) { return checkFound(dbClient.userDao().selectActiveUserByLogin(dbSession, userLogin), "User with login '%s' is not found'", userLogin); } }
4,559
40.081081
142
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/SearchAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.jetbrains.annotations.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.Paging; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; import org.sonar.db.user.GroupQuery; import org.sonar.server.es.SearchOptions; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.user.UserSession; import org.sonar.server.usergroups.DefaultGroupFinder; import static java.lang.Boolean.TRUE; import static java.util.Optional.ofNullable; import static org.sonar.api.utils.Paging.forPageIndex; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.UserGroups.Group; import static org.sonarqube.ws.UserGroups.SearchWsResponse; public class SearchAction implements UserGroupsWsAction { private static final String FIELD_NAME = "name"; private static final String FIELD_DESCRIPTION = "description"; private static final String FIELD_MEMBERS_COUNT = "membersCount"; private static final String FIELD_IS_MANAGED = "managed"; private static final String MANAGED_PARAM = "managed"; private static final List<String> ALL_FIELDS = Arrays.asList(FIELD_NAME, FIELD_DESCRIPTION, FIELD_MEMBERS_COUNT, FIELD_IS_MANAGED); private final DbClient dbClient; private final UserSession userSession; private final DefaultGroupFinder defaultGroupFinder; private final ManagedInstanceService managedInstanceService; public SearchAction(DbClient dbClient, UserSession userSession, DefaultGroupFinder defaultGroupFinder, ManagedInstanceService managedInstanceService) { this.dbClient = dbClient; this.userSession = userSession; this.defaultGroupFinder = defaultGroupFinder; this.managedInstanceService = managedInstanceService; } @Override public void define(NewController context) { WebService.NewAction action = context.createAction("search") .setDescription("Search for user groups.<br>" + "Requires the following permission: 'Administer System'.") .setHandler(this) .setResponseExample(getClass().getResource("search-example.json")) .setSince("5.2") .addFieldsParam(ALL_FIELDS) .addPagingParams(100, MAX_PAGE_SIZE) .addSearchQuery("sonar-users", "names") .setChangelog( new Change("10.0", "Field 'id' in the response has been removed"), new Change("10.0", "New parameter 'managed' to optionally search by managed status"), new Change("10.0", "Response includes 'managed' field."), new Change("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."), new Change("6.4", "Paging response fields moved to a Paging object"), new Change("6.4", "'default' response field has been added")); action.createParam(MANAGED_PARAM) .setSince("10.0") .setDescription("Return managed or non-managed groups. Only available for managed instances, throws for non-managed instances.") .setRequired(false) .setBooleanPossibleValues(); } @Override public void handle(Request request, Response response) throws Exception { int page = request.mandatoryParamAsInt(Param.PAGE); int pageSize = request.mandatoryParamAsInt(Param.PAGE_SIZE); SearchOptions options = new SearchOptions() .setPage(page, pageSize); GroupQuery query = buildGroupQuery(request); Set<String> fields = neededFields(request); try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(ADMINISTER); GroupDto defaultGroup = defaultGroupFinder.findDefaultGroup(dbSession); int limit = dbClient.groupDao().countByQuery(dbSession, query); Paging paging = forPageIndex(page).withPageSize(pageSize).andTotal(limit); List<GroupDto> groups = dbClient.groupDao().selectByQuery(dbSession, query, options.getOffset(), pageSize); List<String> groupUuids = extractGroupUuids(groups); Map<String, Boolean> groupUuidToIsManaged = managedInstanceService.getGroupUuidToManaged(dbSession, new HashSet<>(groupUuids)); Map<String, Integer> userCountByGroup = dbClient.groupMembershipDao().countUsersByGroups(dbSession, groupUuids); writeProtobuf(buildResponse(groups, userCountByGroup, groupUuidToIsManaged, fields, paging, defaultGroup), request, response); } } private GroupQuery buildGroupQuery(Request request) { String textQuery = request.param(Param.TEXT_QUERY); Boolean managed = request.paramAsBoolean(MANAGED_PARAM); GroupQuery.GroupQueryBuilder queryBuilder = GroupQuery.builder() .searchText(textQuery); if (managedInstanceService.isInstanceExternallyManaged()) { String managedInstanceSql = getManagedInstanceSql(managed); queryBuilder.isManagedClause(managedInstanceSql); } else if (TRUE.equals(managed)) { throw BadRequestException.create("The 'managed' parameter is only available for managed instances."); } return queryBuilder.build(); } @Nullable private String getManagedInstanceSql(@Nullable Boolean managed) { return Optional.ofNullable(managed) .map(managedInstanceService::getManagedGroupsSqlFilter) .orElse(null); } private static List<String> extractGroupUuids(List<GroupDto> groups) { return groups.stream().map(GroupDto::getUuid).toList(); } private static Set<String> neededFields(Request request) { Set<String> fields = new HashSet<>(); List<String> fieldsFromRequest = request.paramAsStrings(Param.FIELDS); if (fieldsFromRequest == null || fieldsFromRequest.isEmpty()) { fields.addAll(ALL_FIELDS); } else { fields.addAll(fieldsFromRequest); } return fields; } private static SearchWsResponse buildResponse(List<GroupDto> groups, Map<String, Integer> userCountByGroup, Map<String, Boolean> groupUuidToIsManaged, Set<String> fields, Paging paging, GroupDto defaultGroup) { SearchWsResponse.Builder responseBuilder = SearchWsResponse.newBuilder(); groups.forEach(group -> responseBuilder .addGroups(toWsGroup(group, userCountByGroup.get(group.getName()), groupUuidToIsManaged.get(group.getUuid()), fields, defaultGroup.getUuid().equals(group.getUuid())))); responseBuilder.getPagingBuilder() .setPageIndex(paging.pageIndex()) .setPageSize(paging.pageSize()) .setTotal(paging.total()) .build(); return responseBuilder.build(); } private static Group toWsGroup(GroupDto group, Integer memberCount, Boolean isManaged, Set<String> fields, boolean isDefault) { Group.Builder groupBuilder = Group.newBuilder() .setDefault(isDefault); if (fields.contains(FIELD_NAME)) { groupBuilder.setName(group.getName()); } if (fields.contains(FIELD_DESCRIPTION)) { ofNullable(group.getDescription()).ifPresent(groupBuilder::setDescription); } if (fields.contains(FIELD_MEMBERS_COUNT)) { groupBuilder.setMembersCount(memberCount); } if (fields.contains(FIELD_IS_MANAGED)) { groupBuilder.setManaged(TRUE.equals(isManaged)); } return groupBuilder.build(); } }
8,567
42.492386
174
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserMembershipQuery; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.user.UserSession; import org.sonarqube.ws.UserGroups; import static java.lang.String.format; import static org.sonar.api.user.UserGroupValidation.GROUP_NAME_MAX_LENGTH; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.usergroups.ws.GroupWsSupport.DESCRIPTION_MAX_LENGTH; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_CURRENT_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_DESCRIPTION; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.toProtobuf; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class UpdateAction implements UserGroupsWsAction { private final DbClient dbClient; private final UserSession userSession; private final GroupService groupService; private final ManagedInstanceChecker managedInstanceChecker; public UpdateAction(DbClient dbClient, UserSession userSession, GroupService groupService, ManagedInstanceChecker managedInstanceChecker) { this.dbClient = dbClient; this.userSession = userSession; this.groupService = groupService; this.managedInstanceChecker = managedInstanceChecker; } @Override public void define(NewController context) { NewAction action = context.createAction("update") .setDescription("Update a group.<br>" + "Requires the following permission: 'Administer System'.") .setHandler(this) .setPost(true) .setResponseExample(getClass().getResource("update.example.json")) .setSince("5.2") .setChangelog( new Change("10.0", "Parameter 'id' is removed in favor of 'currentName'"), new Change("8.5", "Parameter 'id' deprecated in favor of 'currentName'"), new Change("8.4", "Parameter 'id' format changes from integer to string"), new Change("6.4", "The default group is no longer editable")); action.createParam(PARAM_GROUP_CURRENT_NAME) .setDescription("Name of the group to be updated.") .setRequired(true) .setExampleValue(UUID_EXAMPLE_01) .setSince("8.5"); action.createParam(PARAM_GROUP_NAME) .setMaximumLength(GROUP_NAME_MAX_LENGTH) .setDescription(format("New optional name for the group. A group name cannot be larger than %d characters and must be unique. " + "Value 'anyone' (whatever the case) is reserved and cannot be used. If value is empty or not defined, then name is not changed.", GROUP_NAME_MAX_LENGTH)) .setExampleValue("my-group"); action.createParam(PARAM_GROUP_DESCRIPTION) .setMaximumLength(DESCRIPTION_MAX_LENGTH) .setDescription(format("New optional description for the group. A group description cannot be larger than %d characters. " + "If value is not defined, then description is not changed.", DESCRIPTION_MAX_LENGTH)) .setExampleValue("Default group for new users"); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkPermission(ADMINISTER); managedInstanceChecker.throwIfInstanceIsManaged(); String currentName = request.mandatoryParam(PARAM_GROUP_CURRENT_NAME); GroupDto group = dbClient.groupDao().selectByName(dbSession, currentName) .orElseThrow(() -> new NotFoundException(format("Could not find a user group with name '%s'.", currentName))); String newName = request.param(PARAM_GROUP_NAME); String description = request.param(PARAM_GROUP_DESCRIPTION); GroupDto updatedGroup = groupService.updateGroup(dbSession, group, newName, description); dbSession.commit(); writeResponse(dbSession, request, response, updatedGroup); } } private void writeResponse(DbSession dbSession, Request request, Response response, GroupDto group) { UserMembershipQuery query = UserMembershipQuery.builder() .groupUuid(group.getUuid()) .membership(UserMembershipQuery.IN) .build(); int membersCount = dbClient.groupMembershipDao().countMembers(dbSession, query); UserGroups.UpdateWsResponse.Builder respBuilder = UserGroups.UpdateWsResponse.newBuilder(); // 'default' is always false as it's not possible to update a default group respBuilder.setGroup(toProtobuf(group, membersCount, false)); writeProtobuf(respBuilder.build(), request, response); } }
5,917
44.523077
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UserGroupsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.core.platform.Module; import org.sonar.server.management.ManagedInstanceChecker; public class UserGroupsModule extends Module { @Override protected void configureModule() { add( UserGroupsWs.class, GroupWsSupport.class, ManagedInstanceChecker.class, GroupService.class, // actions SearchAction.class, CreateAction.class, DeleteAction.class, UpdateAction.class, UsersAction.class, AddUserAction.class, RemoveUserAction.class); } }
1,416
30.488889
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UserGroupsWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.api.server.ws.WebService; public class UserGroupsWs implements WebService { private UserGroupsWsAction[] actions; public UserGroupsWs(UserGroupsWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/user_groups") .setDescription("Manage user groups.") .setSince("5.2"); for (UserGroupsWsAction action : actions) { action.define(controller); } controller.done(); } }
1,423
29.956522
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UserGroupsWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.server.ws.WsAction; public interface UserGroupsWsAction extends WsAction { // Marker interface }
1,002
34.821429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UsersAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import java.util.List; import java.util.Map; import java.util.Set; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.server.ws.WebService.SelectionMode; import org.sonar.api.utils.Paging; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.UserMembershipDto; import org.sonar.db.user.UserMembershipQuery; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.permission.GroupUuid; import org.sonar.server.user.UserSession; import static java.lang.Boolean.TRUE; import static java.util.stream.Collectors.toSet; import static org.sonar.api.utils.Paging.forPageIndex; import static org.sonar.server.usergroups.ws.GroupWsSupport.defineGroupWsParameters; public class UsersAction implements UserGroupsWsAction { private static final String FIELD_SELECTED = "selected"; private static final String FIELD_NAME = "name"; private static final String FIELD_LOGIN = "login"; private static final String FIELD_MANAGED = "managed"; private final DbClient dbClient; private final UserSession userSession; private final ManagedInstanceService managedInstanceService; private final GroupWsSupport support; public UsersAction(DbClient dbClient, UserSession userSession, ManagedInstanceService managedInstanceService, GroupWsSupport support) { this.dbClient = dbClient; this.userSession = userSession; this.managedInstanceService = managedInstanceService; this.support = support; } @Override public void define(NewController context) { NewAction action = context.createAction("users") .setDescription("Search for users with membership information with respect to a group.<br>" + "Requires the following permission: 'Administer System'.") .setHandler(this) .setSince("5.2") .setResponseExample(getClass().getResource("users-example.json")) .addSelectionModeParam() .addSearchQuery("freddy", "names", "logins") .addPagingParams(25) .setChangelog( new Change("10.0", "Field 'managed' added to the payload."), new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."), new Change("9.8", "response fields 'total', 's', 'ps' have been deprecated, please use 'paging' object instead."), new Change("9.8", "The field 'paging' has been added to the response."), new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead.")); defineGroupWsParameters(action); } @Override public void handle(Request request, Response response) throws Exception { int pageSize = request.mandatoryParamAsInt(Param.PAGE_SIZE); int page = request.mandatoryParamAsInt(Param.PAGE); String queryString = request.param(Param.TEXT_QUERY); String selected = request.mandatoryParam(Param.SELECTED); try (DbSession dbSession = dbClient.openSession(false)) { GroupUuid group = support.findGroup(dbSession, request); userSession.checkPermission(GlobalPermission.ADMINISTER); UserMembershipQuery query = UserMembershipQuery.builder() .groupUuid(group.getUuid()) .memberSearch(queryString) .membership(getMembership(selected)) .pageIndex(page) .pageSize(pageSize) .build(); int total = dbClient.groupMembershipDao().countMembers(dbSession, query); Paging paging = forPageIndex(page).withPageSize(pageSize).andTotal(total); List<UserMembershipDto> users = dbClient.groupMembershipDao().selectMembers(dbSession, query, paging.offset(), paging.pageSize()); Map<String, Boolean> userUuidToIsManaged = managedInstanceService.getUserUuidToManaged(dbSession, getUserUuids(users)); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); writeMembers(json, users, userUuidToIsManaged); writePaging(json, paging); json.name("paging").beginObject() .prop("pageIndex", page) .prop("pageSize", pageSize) .prop("total", total) .endObject(); json.endObject(); } } } private static Set<String> getUserUuids(List<UserMembershipDto> users) { return users.stream().map(UserMembershipDto::getUuid).collect(toSet()); } private static void writeMembers(JsonWriter json, List<UserMembershipDto> users, Map<String, Boolean> userUuidToIsManaged) { json.name("users").beginArray(); for (UserMembershipDto user : users) { json.beginObject() .prop(FIELD_LOGIN, user.getLogin()) .prop(FIELD_NAME, user.getName()) .prop(FIELD_SELECTED, user.getGroupUuid() != null) .prop(FIELD_MANAGED, TRUE.equals(userUuidToIsManaged.get(user.getUuid()))) .endObject(); } json.endArray(); } /** * @deprecated since 9.8 - replaced by 'paging' object structure. */ @Deprecated(since = "9.8") private static void writePaging(JsonWriter json, Paging paging) { json.prop(Param.PAGE, paging.pageIndex()) .prop(Param.PAGE_SIZE, paging.pageSize()) .prop("total", paging.total()); } private static String getMembership(String selected) { SelectionMode selectionMode = SelectionMode.fromParam(selected); String membership = UserMembershipQuery.ANY; if (SelectionMode.SELECTED == selectionMode) { membership = UserMembershipQuery.IN; } else if (SelectionMode.DESELECTED == selectionMode) { membership = UserMembershipQuery.OUT; } return membership; } }
6,716
40.462963
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.usergroups.ws; import javax.annotation.ParametersAreNonnullByDefault;
970
39.458333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/GenerateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import org.jetbrains.annotations.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.TokenType; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ServerException; import org.sonar.server.usertoken.TokenGenerator; import org.sonarqube.ws.UserTokens; import org.sonarqube.ws.UserTokens.GenerateWsResponse; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.db.user.TokenType.GLOBAL_ANALYSIS_TOKEN; import static org.sonar.db.user.TokenType.PROJECT_ANALYSIS_TOKEN; import static org.sonar.db.user.TokenType.USER_TOKEN; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.usertoken.ws.GenerateActionValidation.validateParametersCombination; import static org.sonar.server.usertoken.ws.UserTokenSupport.ACTION_GENERATE; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_EXPIRATION_DATE; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_NAME; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_PROJECT_KEY; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_TYPE; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class GenerateAction implements UserTokensWsAction { private static final int MAX_TOKEN_NAME_LENGTH = 100; private final DbClient dbClient; private final System2 system; private final ComponentFinder componentFinder; private final TokenGenerator tokenGenerator; private final UserTokenSupport userTokenSupport; private final GenerateActionValidation validation; public GenerateAction(DbClient dbClient, System2 system, ComponentFinder componentFinder, TokenGenerator tokenGenerator, UserTokenSupport userTokenSupport, GenerateActionValidation validation) { this.dbClient = dbClient; this.system = system; this.componentFinder = componentFinder; this.tokenGenerator = tokenGenerator; this.userTokenSupport = userTokenSupport; this.validation = validation; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_GENERATE) .setSince("5.3") .setPost(true) .setDescription("Generate a user access token. <br />" + "Please keep your tokens secret. They enable to authenticate and analyze projects.<br />" + "It requires administration permissions to specify a 'login' and generate a token for another user. Otherwise, a token is generated for the current user.") .setChangelog( new Change("9.6", "Response field 'expirationDate' added")) .setResponseExample(getClass().getResource("generate-example.json")) .setHandler(this); action.createParam(PARAM_LOGIN) .setDescription("User login. If not set, the token is generated for the authenticated user.") .setExampleValue("g.hopper"); action.createParam(PARAM_NAME) .setRequired(true) .setMaximumLength(MAX_TOKEN_NAME_LENGTH) .setDescription("Token name") .setExampleValue("Project scan on Travis"); action.createParam(PARAM_TYPE) .setSince("9.5") .setDescription("Token Type. If this parameters is set to " + PROJECT_ANALYSIS_TOKEN.name() + ", it is necessary to provide the projectKey parameter too.") .setPossibleValues(USER_TOKEN.name(), GLOBAL_ANALYSIS_TOKEN.name(), PROJECT_ANALYSIS_TOKEN.name()) .setDefaultValue(USER_TOKEN.name()); action.createParam(PARAM_PROJECT_KEY) .setSince("9.5") .setDescription("The key of the only project that can be analyzed by the " + PROJECT_ANALYSIS_TOKEN.name() + " being generated."); action.createParam(PARAM_EXPIRATION_DATE) .setSince("9.6") .setDescription("The expiration date of the token being generated, in ISO 8601 format (YYYY-MM-DD). If not set, default to no expiration."); } @Override public void handle(Request request, Response response) throws Exception { UserTokens.GenerateWsResponse generateWsResponse = doHandle(request); writeProtobuf(generateWsResponse, request, response); } private UserTokens.GenerateWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { String token = generateToken(request, dbSession); String tokenHash = hashToken(dbSession, token); UserTokenDto userTokenDtoFromRequest = getUserTokenDtoFromRequest(dbSession, request); userTokenDtoFromRequest.setTokenHash(tokenHash); UserDto user = userTokenSupport.getUser(dbSession, request); userTokenDtoFromRequest.setUserUuid(user.getUuid()); UserTokenDto userTokenDto = insertTokenInDb(dbSession, user, userTokenDtoFromRequest); return buildResponse(userTokenDto, token, user); } } private UserTokenDto getUserTokenDtoFromRequest(DbSession dbSession, Request request) { LocalDate expirationDate = getExpirationDateFromRequest(request); validation.validateExpirationDate(expirationDate); UserTokenDto userTokenDtoFromRequest = new UserTokenDto() .setName(request.mandatoryParam(PARAM_NAME).trim()) .setCreatedAt(system.now()) .setType(getTokenTypeFromRequest(request).name()); if (expirationDate != null) { userTokenDtoFromRequest.setExpirationDate(expirationDate.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()); } setProjectFromRequest(dbSession, userTokenDtoFromRequest, request); return userTokenDtoFromRequest; } @Nullable private static LocalDate getExpirationDateFromRequest(Request request) { String expirationDateString = request.param(PARAM_EXPIRATION_DATE); if (expirationDateString != null) { try { return LocalDate.parse(expirationDateString, DateTimeFormatter.ISO_DATE); } catch (DateTimeParseException e) { throw new IllegalArgumentException(String.format("Supplied date format for parameter %s is wrong. Please supply date in the ISO 8601 " + "date format (YYYY-MM-DD)", PARAM_EXPIRATION_DATE)); } } return null; } private String generateToken(Request request, DbSession dbSession) { TokenType tokenType = getTokenTypeFromRequest(request); validateParametersCombination(userTokenSupport, dbSession, request, tokenType); return tokenGenerator.generate(tokenType); } public void setProjectFromRequest(DbSession session, UserTokenDto token, Request request) { if (!PROJECT_ANALYSIS_TOKEN.equals(getTokenTypeFromRequest(request))) { return; } String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY).trim(); ProjectDto project = componentFinder.getProjectByKey(session, projectKey); token.setProjectUuid(project.getUuid()); token.setProjectKey(project.getKey()); } private static TokenType getTokenTypeFromRequest(Request request) { String tokenTypeValue = request.mandatoryParam(PARAM_TYPE).trim(); return TokenType.valueOf(tokenTypeValue); } private String hashToken(DbSession dbSession, String token) { String tokenHash = tokenGenerator.hash(token); UserTokenDto userToken = dbClient.userTokenDao().selectByTokenHash(dbSession, tokenHash); if (userToken == null) { return tokenHash; } throw new ServerException(HTTP_INTERNAL_ERROR, "Error while generating token. Please try again."); } private UserTokenDto insertTokenInDb(DbSession dbSession, UserDto user, UserTokenDto userTokenDto) { checkTokenDoesNotAlreadyExists(dbSession, user, userTokenDto.getName()); dbClient.userTokenDao().insert(dbSession, userTokenDto, user.getLogin()); dbSession.commit(); return userTokenDto; } private void checkTokenDoesNotAlreadyExists(DbSession dbSession, UserDto user, String name) { UserTokenDto userTokenDto = dbClient.userTokenDao().selectByUserAndName(dbSession, user, name); checkRequest(userTokenDto == null, "A user token for login '%s' and name '%s' already exists", user.getLogin(), name); } private static GenerateWsResponse buildResponse(UserTokenDto userTokenDto, String token, UserDto user) { GenerateWsResponse.Builder responseBuilder = GenerateWsResponse.newBuilder() .setLogin(user.getLogin()) .setName(userTokenDto.getName()) .setCreatedAt(formatDateTime(userTokenDto.getCreatedAt())) .setToken(token) .setType(userTokenDto.getType()); if (userTokenDto.getProjectKey() != null) { responseBuilder.setProjectKey(userTokenDto.getProjectKey()); } if (userTokenDto.getExpirationDate() != null) { responseBuilder.setExpirationDate(formatDateTime(userTokenDto.getExpirationDate())); } return responseBuilder.build(); } }
10,204
42.425532
163
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/GenerateActionValidation.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.List; import org.jetbrains.annotations.Nullable; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import org.sonar.api.server.ws.Request; import org.sonar.core.config.MaxTokenLifetimeOption; import org.sonar.db.DbSession; import org.sonar.db.user.TokenType; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.api.SonarEdition.COMMUNITY; import static org.sonar.api.SonarEdition.DEVELOPER; import static org.sonar.core.config.MaxTokenLifetimeOption.NO_EXPIRATION; import static org.sonar.core.config.TokenExpirationConstants.MAX_ALLOWED_TOKEN_LIFETIME; import static org.sonar.db.user.TokenType.GLOBAL_ANALYSIS_TOKEN; import static org.sonar.db.user.TokenType.PROJECT_ANALYSIS_TOKEN; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_EXPIRATION_DATE; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_PROJECT_KEY; public final class GenerateActionValidation { private final Configuration configuration; private final SonarRuntime sonarRuntime; public GenerateActionValidation(Configuration configuration, SonarRuntime sonarRuntime) { this.configuration = configuration; this.sonarRuntime = sonarRuntime; } /** * <p>Returns the max allowed token lifetime property based on the Sonar Edition.</p> * <p> * <ul> * <li>COMMUNITY and DEVELOPER editions don't allow the selection of a max token lifetime, therefore it always defaults to NO_EXPIRATION</li> * <li>ENTERPRISE and DATACENTER editions support the selection of max token lifetime property and the value is searched in the enum</li> * </ul> * </p> * @return The max allowed token lifetime. */ public MaxTokenLifetimeOption getMaxTokenLifetimeOption() { if (List.of(COMMUNITY, DEVELOPER).contains(sonarRuntime.getEdition())) { return NO_EXPIRATION; } String maxTokenLifetimeProp = configuration.get(MAX_ALLOWED_TOKEN_LIFETIME).orElse(NO_EXPIRATION.getName()); return MaxTokenLifetimeOption.get(maxTokenLifetimeProp); } /** * <p>Validates if the expiration date of the token is between the minimum and maximum allowed values.</p> * * @param expirationDate The expiration date */ void validateExpirationDate(@Nullable LocalDate expirationDate) { MaxTokenLifetimeOption maxTokenLifetime = getMaxTokenLifetimeOption(); if (expirationDate != null) { validateMinExpirationDate(expirationDate); validateMaxExpirationDate(maxTokenLifetime, expirationDate); } else { validateMaxExpirationDate(maxTokenLifetime); } } static void validateMaxExpirationDate(MaxTokenLifetimeOption maxTokenLifetime, LocalDate expirationDate) { maxTokenLifetime.getDays() .ifPresent(days -> compareExpirationDateToMaxAllowedLifetime(expirationDate, LocalDate.now().plusDays(days))); } static void validateMaxExpirationDate(MaxTokenLifetimeOption maxTokenLifetime) { maxTokenLifetime.getDays() .ifPresent(days -> { throw new IllegalArgumentException( String.format("Tokens expiring after %s are not allowed. Please use an expiration date.", LocalDate.now().plusDays(days).format(DateTimeFormatter.ISO_DATE))); }); } static void compareExpirationDateToMaxAllowedLifetime(LocalDate expirationDate, LocalDate maxExpirationDate) { if (expirationDate.isAfter(maxExpirationDate)) { throw new IllegalArgumentException( String.format("Tokens expiring after %s are not allowed. Please use a valid expiration date.", maxExpirationDate.format(DateTimeFormatter.ISO_DATE))); } } static void validateMinExpirationDate(LocalDate localDate) { if (localDate.isBefore(LocalDate.now().plusDays(1))) { throw new IllegalArgumentException( String.format("The minimum value for parameter %s is %s.", PARAM_EXPIRATION_DATE, LocalDate.now().plusDays(1).format(DateTimeFormatter.ISO_DATE))); } } static void validateParametersCombination(UserTokenSupport userTokenSupport, DbSession dbSession, Request request, TokenType tokenType) { if (PROJECT_ANALYSIS_TOKEN.equals(tokenType)) { validateProjectAnalysisParameters(userTokenSupport, dbSession, request); } else if (GLOBAL_ANALYSIS_TOKEN.equals(tokenType)) { validateGlobalAnalysisParameters(userTokenSupport, request); } } private static void validateProjectAnalysisParameters(UserTokenSupport userTokenSupport, DbSession dbSession, Request request) { checkArgument(userTokenSupport.sameLoginAsConnectedUser(request), "A Project Analysis Token cannot be generated for another user."); checkArgument(request.param(PARAM_PROJECT_KEY) != null, "A projectKey is needed when creating Project Analysis Token"); userTokenSupport.validateProjectScanPermission(dbSession, request.param(PARAM_PROJECT_KEY)); } private static void validateGlobalAnalysisParameters(UserTokenSupport userTokenSupport, Request request) { checkArgument(userTokenSupport.sameLoginAsConnectedUser(request), "A Global Analysis Token cannot be generated for another user."); userTokenSupport.validateGlobalScanPermission(); } }
6,142
44.169118
155
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/RevokeAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import static org.sonar.server.usertoken.ws.UserTokenSupport.ACTION_REVOKE; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_NAME; public class RevokeAction implements UserTokensWsAction { private final DbClient dbClient; private final UserTokenSupport userTokenSupport; public RevokeAction(DbClient dbClient, UserTokenSupport userTokenSupport) { this.dbClient = dbClient; this.userTokenSupport = userTokenSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_REVOKE) .setDescription("Revoke a user access token. <br/>" + "It requires administration permissions to specify a 'login' and revoke a token for another user. Otherwise, the token for the current user is revoked.") .setSince("5.3") .setPost(true) .setHandler(this); action.createParam(PARAM_LOGIN) .setDescription("User login") .setExampleValue("g.hopper"); action.createParam(PARAM_NAME) .setRequired(true) .setDescription("Token name") .setExampleValue("Project scan on Travis"); } @Override public void handle(Request request, Response response) throws Exception { String name = request.mandatoryParam(PARAM_NAME); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = userTokenSupport.getUser(dbSession, request); dbClient.userTokenDao().deleteByUserAndName(dbSession, user, name); dbSession.commit(); } response.noContent(); } }
2,732
36.438356
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/SearchAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import java.util.List; import org.sonar.api.server.ws.Change; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; import org.sonarqube.ws.UserTokens.SearchWsResponse; import org.sonarqube.ws.UserTokens.SearchWsResponse.UserToken; import static java.util.Optional.ofNullable; import static org.elasticsearch.common.Strings.isNullOrEmpty; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.server.usertoken.ws.UserTokenSupport.ACTION_SEARCH; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.UserTokens.SearchWsResponse.UserToken.Project; import static org.sonarqube.ws.UserTokens.SearchWsResponse.UserToken.newBuilder; public class SearchAction implements UserTokensWsAction { private final DbClient dbClient; private final UserTokenSupport userTokenSupport; public SearchAction(DbClient dbClient, UserTokenSupport userTokenSupport) { this.dbClient = dbClient; this.userTokenSupport = userTokenSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_SEARCH) .setDescription("List the access tokens of a user.<br>" + "The login must exist and active.<br>" + "Field 'lastConnectionDate' is only updated every hour, so it may not be accurate, for instance when a user is using a token many times in less than one hour.<br> " + "It requires administration permissions to specify a 'login' and list the tokens of another user. Otherwise, tokens for the current user are listed. <br> " + "Authentication is required for this API endpoint") .setChangelog(new Change("9.6", "New field 'expirationDate' is added to response")) .setChangelog(new Change("7.7", "New field 'lastConnectionDate' is added to response")) .setResponseExample(getClass().getResource("search-example.json")) .setSince("5.3") .setHandler(this); action.createParam(PARAM_LOGIN) .setDescription("User login") .setExampleValue("g.hopper"); } @Override public void handle(Request request, Response response) throws Exception { SearchWsResponse searchWsResponse = doHandle(request); writeProtobuf(searchWsResponse, request, response); } private SearchWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = userTokenSupport.getUser(dbSession, request); List<UserTokenDto> userTokens = dbClient.userTokenDao().selectByUser(dbSession, user); return buildResponse(user, userTokens); } } private static SearchWsResponse buildResponse(UserDto user, List<UserTokenDto> userTokensDto) { SearchWsResponse.Builder searchWsResponse = SearchWsResponse.newBuilder(); UserToken.Builder userTokenBuilder = newBuilder(); searchWsResponse.setLogin(user.getLogin()); for (UserTokenDto userTokenDto : userTokensDto) { userTokenBuilder .clear() .setName(userTokenDto.getName()) .setCreatedAt(formatDateTime(userTokenDto.getCreatedAt())) .setType(userTokenDto.getType()); ofNullable(userTokenDto.getLastConnectionDate()).ifPresent(date -> userTokenBuilder.setLastConnectionDate(formatDateTime(date))); ofNullable(userTokenDto.getExpirationDate()).ifPresent(expirationDate -> { userTokenBuilder.setExpirationDate(formatDateTime(expirationDate)); userTokenBuilder.setIsExpired(userTokenDto.isExpired()); }); if (!isNullOrEmpty(userTokenDto.getProjectKey()) && !isNullOrEmpty(userTokenDto.getProjectName())) { Project.Builder projectBuilder = newBuilder().getProjectBuilder() .setKey(userTokenDto.getProjectKey()) .setName(userTokenDto.getProjectName()); userTokenBuilder.setProject(projectBuilder.build()); } searchWsResponse.addUserTokens(userTokenBuilder); } return searchWsResponse.build(); } }
5,122
43.547826
174
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/UserTokenSupport.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.api.server.ws.Request; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; public class UserTokenSupport { static final String CONTROLLER = "api/user_tokens"; static final String ACTION_SEARCH = "search"; static final String ACTION_REVOKE = "revoke"; static final String ACTION_GENERATE = "generate"; static final String PARAM_LOGIN = "login"; static final String PARAM_NAME = "name"; static final String PARAM_TYPE = "type"; static final String PARAM_PROJECT_KEY = "projectKey"; static final String PARAM_EXPIRATION_DATE = "expirationDate"; private final DbClient dbClient; private final UserSession userSession; public UserTokenSupport(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } UserDto getUser(DbSession dbSession, Request request) { String login = request.param(PARAM_LOGIN); login = login == null ? userSession.getLogin() : login; validate(userSession, login); UserDto user = dbClient.userDao().selectByLogin(dbSession, requireNonNull(login, "Login should not be null")); checkFound(user, "User with login '%s' doesn't exist", login); return user; } boolean sameLoginAsConnectedUser(Request request) { return request.param(PARAM_LOGIN) == null || isLoggedInUser(userSession, request.param(PARAM_LOGIN)); } private static void validate(UserSession userSession, @Nullable String requestLogin) { userSession.checkLoggedIn(); if (userSession.isSystemAdministrator() || isLoggedInUser(userSession, requestLogin)) { return; } throw insufficientPrivilegesException(); } private static boolean isLoggedInUser(UserSession userSession, @Nullable String requestLogin) { return requestLogin != null && requestLogin.equals(userSession.getLogin()); } public void validateGlobalScanPermission() { if (userSession.hasPermission(SCAN)){ return; } throw insufficientPrivilegesException(); } public void validateProjectScanPermission(DbSession dbSession, String projectKeyFromRequest) { Optional<ProjectDto> projectDto = dbClient.projectDao().selectProjectByKey(dbSession, projectKeyFromRequest); if (projectDto.isEmpty()) { throw new NotFoundException(format("Project key '%s' not found", projectKeyFromRequest)); } validateProjectScanPermission(projectDto.get()); } private void validateProjectScanPermission(ProjectDto projectDto) { if (userSession.hasEntityPermission(UserRole.SCAN, projectDto) || userSession.hasPermission(SCAN)) { return; } throw insufficientPrivilegesException(); } }
4,111
37.792453
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/UserTokenWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import org.sonar.core.platform.Module; public class UserTokenWsModule extends Module { @Override protected void configureModule() { add( UserTokensWs.class, UserTokenSupport.class, GenerateAction.class, RevokeAction.class, SearchAction.class, GenerateActionValidation.class ); } }
1,215
31.864865
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/UserTokensWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import org.sonar.api.server.ws.WebService; import static org.sonar.server.usertoken.ws.UserTokenSupport.CONTROLLER; public class UserTokensWs implements WebService { private final UserTokensWsAction[] actions; public UserTokensWs(UserTokensWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(CONTROLLER) .setDescription("List, create, and delete a user's access tokens.") .setSince("5.3"); for (UserTokensWsAction action : actions) { action.define(controller); } controller.done(); } }
1,522
32.108696
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/UserTokensWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; import org.sonar.server.ws.WsAction; public interface UserTokensWsAction extends WsAction { // marker interface }
1,000
36.074074
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/UserTokensWsParameters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usertoken.ws; public class UserTokensWsParameters { private UserTokensWsParameters() { // constants only } }
987
34.285714
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usertoken/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.usertoken.ws; import javax.annotation.ParametersAreNonnullByDefault;
970
37.84
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/CreateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import javax.annotation.Nullable; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.sonar.server.webhook.ws.WebhooksWsParameters.ACTION_CREATE; import static org.sonar.server.webhook.ws.WebhooksWsParameters.NAME_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.NAME_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.webhook.ws.WebhooksWsParameters.PROJECT_KEY_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.PROJECT_KEY_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.webhook.ws.WebhooksWsParameters.SECRET_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.SECRET_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.webhook.ws.WebhooksWsParameters.URL_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.URL_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.NAME_WEBHOOK_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.URL_WEBHOOK_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.Webhooks.CreateWsResponse.Webhook; import static org.sonarqube.ws.Webhooks.CreateWsResponse.newBuilder; public class CreateAction implements WebhooksWsAction { private static final int MAX_NUMBER_OF_WEBHOOKS = 10; private final DbClient dbClient; private final UserSession userSession; private final UuidFactory uuidFactory; private final WebhookSupport webhookSupport; private final ComponentFinder componentFinder; public CreateAction(DbClient dbClient, UserSession userSession, UuidFactory uuidFactory, WebhookSupport webhookSupport, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.uuidFactory = uuidFactory; this.webhookSupport = webhookSupport; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(ACTION_CREATE) .setPost(true) .setDescription("Create a Webhook.<br>" + "Requires 'Administer' permission on the specified project, or global 'Administer' permission.") .setSince("7.1") .setResponseExample(getClass().getResource("example-webhook-create.json")) .setHandler(this); action.createParam(NAME_PARAM) .setRequired(true) .setMaximumLength(NAME_PARAM_MAXIMUM_LENGTH) .setDescription("Name displayed in the administration console of webhooks") .setExampleValue(NAME_WEBHOOK_EXAMPLE_001); action.createParam(URL_PARAM) .setRequired(true) .setMaximumLength(URL_PARAM_MAXIMUM_LENGTH) .setDescription("Server endpoint that will receive the webhook payload, for example 'http://my_server/foo'." + " If HTTP Basic authentication is used, HTTPS is recommended to avoid man in the middle attacks." + " Example: 'https://myLogin:myPassword@my_server/foo'") .setExampleValue(URL_WEBHOOK_EXAMPLE_001); action.createParam(PROJECT_KEY_PARAM) .setRequired(false) .setMaximumLength(PROJECT_KEY_PARAM_MAXIMUM_LENGTH) .setDescription("The key of the project that will own the webhook") .setExampleValue(KEY_PROJECT_EXAMPLE_001); action.createParam(SECRET_PARAM) .setRequired(false) .setMinimumLength(1) .setMaximumLength(SECRET_PARAM_MAXIMUM_LENGTH) .setDescription("If provided, secret will be used as the key to generate the HMAC hex (lowercase) digest value in the 'X-Sonar-Webhook-HMAC-SHA256' header") .setExampleValue("your_secret") .setSince("7.8"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String name = request.mandatoryParam(NAME_PARAM); String url = request.mandatoryParam(URL_PARAM); String projectKey = request.param(PROJECT_KEY_PARAM); String secret = request.param(SECRET_PARAM); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto projectDto = null; if (isNotBlank(projectKey)) { projectDto = componentFinder.getProjectByKey(dbSession, projectKey); webhookSupport.checkPermission(projectDto); } else { webhookSupport.checkPermission(); } webhookSupport.checkUrlPattern(url, "Url parameter with value '%s' is not a valid url", url); WebhookDto dto = doHandle(dbSession, projectDto, name, url, secret); String projectName = projectDto == null ? null : projectDto.getName(); dbClient.webhookDao().insert(dbSession, dto, projectKey, projectName); dbSession.commit(); writeResponse(request, response, dto); } } private WebhookDto doHandle(DbSession dbSession, @Nullable ProjectDto project, String name, String url, @Nullable String secret) { WebhookDto dto = new WebhookDto() .setUuid(uuidFactory.create()) .setName(name) .setUrl(url) .setSecret(secret); if (project != null) { checkNumberOfWebhook(numberOfWebhookOf(dbSession, project), project.getKey()); dto.setProjectUuid(project.getUuid()); } else { checkNumberOfGlobalWebhooks(dbSession); } return dto; } private static void writeResponse(Request request, Response response, WebhookDto dto) { Webhook.Builder webhookBuilder = Webhook.newBuilder(); webhookBuilder .setKey(dto.getUuid()) .setName(dto.getName()) .setUrl(dto.getUrl()) .setHasSecret(dto.getSecret() != null); writeProtobuf(newBuilder().setWebhook(webhookBuilder).build(), request, response); } private static void checkNumberOfWebhook(int nbOfWebhooks, String projectKey) { if (nbOfWebhooks >= MAX_NUMBER_OF_WEBHOOKS) { throw new IllegalArgumentException(format("Maximum number of webhook reached for project '%s'", projectKey)); } } private int numberOfWebhookOf(DbSession dbSession, ProjectDto projectDto) { return dbClient.webhookDao().selectByProject(dbSession, projectDto).size(); } private void checkNumberOfGlobalWebhooks(DbSession dbSession) { int globalWebhooksCount = dbClient.webhookDao().selectGlobalWebhooks(dbSession).size(); if (globalWebhooksCount >= MAX_NUMBER_OF_WEBHOOKS) { throw new IllegalArgumentException("Maximum number of global webhooks reached"); } } }
7,743
41.78453
162
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/DeleteAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDto; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.webhook.ws.WebhooksWsParameters.DELETE_ACTION; import static org.sonar.server.webhook.ws.WebhooksWsParameters.KEY_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.KEY_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; public class DeleteAction implements WebhooksWsAction { private final DbClient dbClient; private final UserSession userSession; private final WebhookSupport webhookSupport; public DeleteAction(DbClient dbClient, UserSession userSession, WebhookSupport webhookSupport) { this.dbClient = dbClient; this.userSession = userSession; this.webhookSupport = webhookSupport; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(DELETE_ACTION) .setPost(true) .setDescription("Delete a Webhook.<br>" + "Requires 'Administer' permission on the specified project, or global 'Administer' permission.") .setSince("7.1") .setHandler(this); action.createParam(KEY_PARAM) .setRequired(true) .setMaximumLength(KEY_PARAM_MAXIMUM_LENGTH) .setDescription("The key of the webhook to be deleted, " + "auto-generated value can be obtained through api/webhooks/create or api/webhooks/list") .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String webhookKey = request.param(KEY_PARAM); try (DbSession dbSession = dbClient.openSession(false)) { Optional<WebhookDto> dtoOptional = dbClient.webhookDao().selectByUuid(dbSession, webhookKey); WebhookDto webhookDto = checkFoundWithOptional(dtoOptional, "No webhook with key '%s'", webhookKey); String projectUuid = webhookDto.getProjectUuid(); if (projectUuid != null) { Optional<ProjectDto> optionalDto = dbClient.projectDao().selectByUuid(dbSession, projectUuid); ProjectDto projectDto = optionalDto.orElseThrow(() -> new IllegalStateException(format("the requested project '%s' was not found", projectUuid))); webhookSupport.checkPermission(projectDto); deleteWebhook(dbSession, webhookDto); } else { webhookSupport.checkPermission(); deleteWebhook(dbSession, webhookDto); } dbSession.commit(); } response.noContent(); } private void deleteWebhook(DbSession dbSession, WebhookDto webhookDto) { dbClient.webhookDeliveryDao().deleteByWebhook(dbSession, webhookDto); dbClient.webhookDao().delete(dbSession, webhookDto.getUuid(), webhookDto.getName()); } }
4,047
39.079208
154
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/ListAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDeliveryLiteDto; import org.sonar.db.webhook.WebhookDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Webhooks; import org.sonarqube.ws.Webhooks.ListResponse; import org.sonarqube.ws.Webhooks.ListResponseElement; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.server.webhook.HttpUrlHelper.obfuscateCredentials; import static org.sonar.server.webhook.ws.WebhooksWsParameters.LIST_ACTION; import static org.sonar.server.webhook.ws.WebhooksWsParameters.PROJECT_KEY_PARAM; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListAction implements WebhooksWsAction { private final DbClient dbClient; private final UserSession userSession; private final WebhookSupport webhookSupport; private final ComponentFinder componentFinder; public ListAction(DbClient dbClient, UserSession userSession, WebhookSupport webhookSupport, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.webhookSupport = webhookSupport; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(LIST_ACTION) .setDescription("Search for global webhooks or project webhooks. Webhooks are ordered by name.<br>" + "Requires 'Administer' permission on the specified project, or global 'Administer' permission.") .setSince("7.1") .setResponseExample(getClass().getResource("example-webhooks-list.json")) .setHandler(this); action.createParam(PROJECT_KEY_PARAM) .setDescription("Project key") .setRequired(false) .setExampleValue(KEY_PROJECT_EXAMPLE_001); action.setChangelog(new Change("7.8", "Field 'secret' added to response")); action.setChangelog(new Change("10.1", "Field 'secret' replaced by flag 'hasSecret' in response")); } @Override public void handle(Request request, Response response) throws Exception { String projectKey = request.param(PROJECT_KEY_PARAM); userSession.checkLoggedIn(); try (DbSession dbSession = dbClient.openSession(true)) { List<WebhookDto> webhookDtos = doHandle(dbSession, projectKey); Map<String, WebhookDeliveryLiteDto> lastDeliveries = loadLastDeliveriesOf(dbSession, webhookDtos); writeResponse(request, response, webhookDtos, lastDeliveries); } } private Map<String, WebhookDeliveryLiteDto> loadLastDeliveriesOf(DbSession dbSession, List<WebhookDto> webhookDtos) { return dbClient.webhookDeliveryDao().selectLatestDeliveries(dbSession, webhookDtos); } private List<WebhookDto> doHandle(DbSession dbSession, @Nullable String projectKey) { if (isNotBlank(projectKey)) { ProjectDto projectDto = componentFinder.getProjectByKey(dbSession, projectKey); webhookSupport.checkPermission(projectDto); webhookSupport.checkPermission(projectDto); return dbClient.webhookDao().selectByProject(dbSession, projectDto); } else { webhookSupport.checkPermission(); return dbClient.webhookDao().selectGlobalWebhooks(dbSession); } } private static void writeResponse(Request request, Response response, List<WebhookDto> webhookDtos, Map<String, WebhookDeliveryLiteDto> lastDeliveries) { ListResponse.Builder responseBuilder = ListResponse.newBuilder(); webhookDtos .forEach(webhook -> { ListResponseElement.Builder responseElementBuilder = responseBuilder.addWebhooksBuilder(); responseElementBuilder .setKey(webhook.getUuid()) .setName(webhook.getName()) .setUrl(obfuscateCredentials(webhook.getUrl())) .setHasSecret(webhook.getSecret() != null); addLastDelivery(responseElementBuilder, webhook, lastDeliveries); }); writeProtobuf(responseBuilder.build(), request, response); } private static void addLastDelivery(ListResponseElement.Builder responseElementBuilder, WebhookDto webhook, Map<String, WebhookDeliveryLiteDto> lastDeliveries) { if (lastDeliveries.containsKey(webhook.getUuid())) { WebhookDeliveryLiteDto delivery = lastDeliveries.get(webhook.getUuid()); Webhooks.LatestDelivery.Builder builder = responseElementBuilder.getLatestDeliveryBuilder() .setId(delivery.getUuid()) .setAt(formatDateTime(delivery.getCreatedAt())) .setSuccess(delivery.isSuccess()); if (delivery.getHttpStatus() != null) { builder.setHttpStatus(delivery.getHttpStatus()); } if (delivery.getDurationMs() != null) { builder.setDurationMs(delivery.getDurationMs()); } builder.build(); } } }
6,127
42.460993
163
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/NetworkInterfaceProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.List; public class NetworkInterfaceProvider { public List<InetAddress> getNetworkInterfaceAddresses() throws SocketException { return Collections.list(NetworkInterface.getNetworkInterfaces()) .stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .toList(); } }
1,334
35.081081
82
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/UpdateAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import java.util.Optional; import javax.annotation.Nullable; 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.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.isBlank; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.webhook.ws.WebhooksWsParameters.KEY_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.KEY_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.webhook.ws.WebhooksWsParameters.NAME_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.NAME_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.webhook.ws.WebhooksWsParameters.SECRET_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.SECRET_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.webhook.ws.WebhooksWsParameters.UPDATE_ACTION; import static org.sonar.server.webhook.ws.WebhooksWsParameters.URL_PARAM; import static org.sonar.server.webhook.ws.WebhooksWsParameters.URL_PARAM_MAXIMUM_LENGTH; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.NAME_WEBHOOK_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.URL_WEBHOOK_EXAMPLE_001; public class UpdateAction implements WebhooksWsAction { private final DbClient dbClient; private final UserSession userSession; private final WebhookSupport webhookSupport; private final ComponentFinder componentFinder; public UpdateAction(DbClient dbClient, UserSession userSession, WebhookSupport webhookSupport, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.webhookSupport = webhookSupport; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(UPDATE_ACTION) .setPost(true) .setDescription("Update a Webhook.<br>" + "Requires 'Administer' permission on the specified project, or global 'Administer' permission.") .setSince("7.1") .setHandler(this); action.createParam(KEY_PARAM) .setRequired(true) .setMaximumLength(KEY_PARAM_MAXIMUM_LENGTH) .setDescription("The key of the webhook to be updated, " + "auto-generated value can be obtained through api/webhooks/create or api/webhooks/list") .setExampleValue(KEY_PROJECT_EXAMPLE_001); action.createParam(NAME_PARAM) .setRequired(true) .setMaximumLength(NAME_PARAM_MAXIMUM_LENGTH) .setDescription("new name of the webhook") .setExampleValue(NAME_WEBHOOK_EXAMPLE_001); action.createParam(URL_PARAM) .setRequired(true) .setMaximumLength(URL_PARAM_MAXIMUM_LENGTH) .setDescription("new url to be called by the webhook") .setExampleValue(URL_WEBHOOK_EXAMPLE_001); action.createParam(SECRET_PARAM) .setRequired(false) .setMaximumLength(SECRET_PARAM_MAXIMUM_LENGTH) .setDescription("If provided, secret will be used as the key to generate the HMAC hex (lowercase) digest value in the 'X-Sonar-Webhook-HMAC-SHA256' header. " + "If blank, any secret previously configured will be removed. If not set, the secret will remain unchanged.") .setExampleValue("your_secret") .setSince("7.8"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String webhookKey = request.mandatoryParam(KEY_PARAM); String name = request.mandatoryParam(NAME_PARAM); String url = request.mandatoryParam(URL_PARAM); String secret = request.param(SECRET_PARAM); webhookSupport.checkUrlPattern(url, "Url parameter with value '%s' is not a valid url", url); try (DbSession dbSession = dbClient.openSession(false)) { Optional<WebhookDto> dtoOptional = dbClient.webhookDao().selectByUuid(dbSession, webhookKey); WebhookDto webhookDto = checkFoundWithOptional(dtoOptional, "No webhook with key '%s'", webhookKey); String projectUuid = webhookDto.getProjectUuid(); if (projectUuid != null) { ProjectDto projectDto = componentFinder.getProjectByUuid(dbSession, projectUuid); webhookSupport.checkPermission(projectDto); updateWebhook(dbSession, webhookDto, name, url, secret, projectDto.getKey(), projectDto.getName()); } else { webhookSupport.checkPermission(); updateWebhook(dbSession, webhookDto, name, url, secret, null, null); } dbSession.commit(); } response.noContent(); } private void updateWebhook(DbSession dbSession, WebhookDto dto, String name, String url, @Nullable String secret, @Nullable String projectKey, @Nullable String projectName) { dto .setName(name) .setUrl(url); setSecret(dto, secret); dbClient.webhookDao().update(dbSession, dto, projectKey, projectName); } /** * <p>Sets the secret of the webhook. The secret is set according to the following rules: * <ul> * <li>If the secret is null, it will remain unchanged.</li> * <li>If the secret is blank (""), it will be removed.</li> * <li>If the secret is not null or blank, it will be set to the provided value.</li> * </ul> * </p> * @param dto The webhook to update. It holds the old secret value. * @param secret The new secret value. It can be null or blank. */ private static void setSecret(WebhookDto dto, @Nullable String secret) { if (secret != null) { if (isBlank(secret)) { dto.setSecret(null); } else { dto.setSecret(secret); } } } }
6,810
40.785276
165
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveriesAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDeliveryLiteDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Common; import org.sonarqube.ws.Webhooks; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.utils.Paging.offset; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02; import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE; import static org.sonar.server.webhook.ws.WebhookWsSupport.copyDtoToProtobuf; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class WebhookDeliveriesAction implements WebhooksWsAction { private static final String PARAM_COMPONENT = "componentKey"; private static final String PARAM_TASK = "ceTaskId"; private static final String PARAM_WEBHOOK = "webhook"; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public WebhookDeliveriesAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("deliveries") .setSince("6.2") .setDescription("Get the recent deliveries for a specified project or Compute Engine task.<br/>" + "Require 'Administer' permission on the related project.<br/>" + "Note that additional information are returned by api/webhooks/delivery.") .setResponseExample(getClass().getResource("example-deliveries.json")) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription("Key of the project") .setExampleValue("my-project"); action.createParam(PARAM_TASK) .setDescription("Id of the Compute Engine task") .setExampleValue(Uuids.UUID_EXAMPLE_01); action.createParam(PARAM_WEBHOOK) .setSince("7.1") .setDescription("Key of the webhook that triggered those deliveries, " + "auto-generated value that can be obtained through api/webhooks/create or api/webhooks/list") .setExampleValue(UUID_EXAMPLE_02); action.addPagingParamsSince(10, MAX_PAGE_SIZE, "7.1"); } @Override public void handle(Request request, Response response) throws Exception { // fail-fast if not logged in userSession.checkLoggedIn(); String ceTaskId = request.param(PARAM_TASK); String projectKey = request.param(PARAM_COMPONENT); String webhookUuid = request.param(PARAM_WEBHOOK); int page = request.mandatoryParamAsInt(PAGE); int pageSize = request.mandatoryParamAsInt(PAGE_SIZE); checkArgument(webhookUuid != null ^ (ceTaskId != null ^ projectKey != null), "Either '%s' or '%s' or '%s' must be provided", PARAM_TASK, PARAM_COMPONENT, PARAM_WEBHOOK); Data data = loadFromDatabase(webhookUuid, ceTaskId, projectKey, page, pageSize); data.ensureAdminPermission(userSession); data.writeTo(request, response); } private Data loadFromDatabase(@Nullable String webhookUuid, @Nullable String ceTaskId, @Nullable String projectKey, int page, int pageSize) { Map<String, ProjectDto> projectUuidMap; List<WebhookDeliveryLiteDto> deliveries; int totalElements; try (DbSession dbSession = dbClient.openSession(false)) { if (isNotBlank(webhookUuid)) { totalElements = dbClient.webhookDeliveryDao().countDeliveriesByWebhookUuid(dbSession, webhookUuid); deliveries = dbClient.webhookDeliveryDao().selectByWebhookUuid(dbSession, webhookUuid, offset(page, pageSize), pageSize); projectUuidMap = getProjectsDto(dbSession, deliveries); } else if (projectKey != null) { ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey); projectUuidMap = new HashMap<>(); projectUuidMap.put(project.getUuid(), project); totalElements = dbClient.webhookDeliveryDao().countDeliveriesByProjectUuid(dbSession, project.getUuid()); deliveries = dbClient.webhookDeliveryDao().selectOrderedByProjectUuid(dbSession, project.getUuid(), offset(page, pageSize), pageSize); } else { totalElements = dbClient.webhookDeliveryDao().countDeliveriesByCeTaskUuid(dbSession, ceTaskId); deliveries = dbClient.webhookDeliveryDao().selectOrderedByCeTaskUuid(dbSession, ceTaskId, offset(page, pageSize), pageSize); projectUuidMap = getProjectsDto(dbSession, deliveries); } } return new Data(projectUuidMap, deliveries).withPagingInfo(page, pageSize, totalElements); } private Map<String, ProjectDto> getProjectsDto(DbSession dbSession, List<WebhookDeliveryLiteDto> deliveries) { Map<String, String> deliveredComponentUuid = deliveries .stream() .collect(Collectors.toMap(WebhookDeliveryLiteDto::getUuid, WebhookDeliveryLiteDto::getProjectUuid)); if (!deliveredComponentUuid.isEmpty()) { return dbClient.projectDao().selectByUuids(dbSession, new HashSet<>(deliveredComponentUuid.values())) .stream() .collect(Collectors.toMap(ProjectDto::getUuid, Function.identity())); } else { return Collections.emptyMap(); } } private static class Data { private final Map<String, ProjectDto> projectUuidMap; private final List<WebhookDeliveryLiteDto> deliveryDtos; private int pageIndex; private int pageSize; private int totalElements; Data(Map<String, ProjectDto> projectUuidMap, List<WebhookDeliveryLiteDto> deliveries) { this.deliveryDtos = deliveries; if (deliveries.isEmpty()) { this.projectUuidMap = projectUuidMap; } else { checkArgument(!projectUuidMap.isEmpty()); this.projectUuidMap = projectUuidMap; } } void ensureAdminPermission(UserSession userSession) { if (!projectUuidMap.isEmpty()) { List<ProjectDto> projectsUserHasAccessTo = userSession.keepAuthorizedEntities(UserRole.ADMIN, projectUuidMap.values()); if (projectsUserHasAccessTo.size() != projectUuidMap.size()) { throw new ForbiddenException("Insufficient privileges"); } } } void writeTo(Request request, Response response) { Webhooks.DeliveriesWsResponse.Builder responseBuilder = Webhooks.DeliveriesWsResponse.newBuilder(); Webhooks.Delivery.Builder deliveryBuilder = Webhooks.Delivery.newBuilder(); for (WebhookDeliveryLiteDto dto : deliveryDtos) { ProjectDto project = projectUuidMap.get(dto.getProjectUuid()); copyDtoToProtobuf(project, dto, deliveryBuilder); responseBuilder.addDeliveries(deliveryBuilder); } responseBuilder.setPaging(buildPaging(pageIndex, pageSize, totalElements)); writeProtobuf(responseBuilder.build(), request, response); } static Common.Paging buildPaging(int pageIndex, int pageSize, int totalElements) { return Common.Paging.newBuilder() .setPageIndex(pageIndex) .setPageSize(pageSize) .setTotal(totalElements) .build(); } public Data withPagingInfo(int pageIndex, int pageSize, int totalElements) { this.pageIndex = pageIndex; this.pageSize = pageSize; this.totalElements = totalElements; return this; } } }
9,000
41.658768
143
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveryAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDeliveryDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Webhooks; import static java.util.Objects.requireNonNull; import static org.sonar.server.webhook.ws.WebhookWsSupport.copyDtoToProtobuf; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class WebhookDeliveryAction implements WebhooksWsAction { private static final String PARAM_ID = "deliveryId"; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public WebhookDeliveryAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("delivery") .setSince("6.2") .setDescription("Get a webhook delivery by its id.<br/>" + "Require 'Administer System' permission.<br/>" + "Note that additional information are returned by api/webhooks/delivery.") .setResponseExample(getClass().getResource("example-delivery.json")) .setHandler(this); action.createParam(PARAM_ID) .setDescription("Id of delivery") .setRequired(true) .setExampleValue(Uuids.UUID_EXAMPLE_06); } @Override public void handle(Request request, Response response) throws Exception { // fail-fast if not logged in userSession.checkLoggedIn(); Data data = loadFromDatabase(request.mandatoryParam(PARAM_ID)); data.ensureAdminPermission(userSession); data.writeTo(request, response); } private Data loadFromDatabase(String deliveryUuid) { try (DbSession dbSession = dbClient.openSession(false)) { WebhookDeliveryDto delivery = dbClient.webhookDeliveryDao().selectByUuid(dbSession, deliveryUuid) .orElseThrow(() -> new NotFoundException("Webhook delivery not found")); ProjectDto project = componentFinder.getProjectByUuid(dbSession, delivery.getProjectUuid()); return new Data(project, delivery); } } private static class Data { private final ProjectDto project; private final WebhookDeliveryDto deliveryDto; Data(ProjectDto component, WebhookDeliveryDto delivery) { this.deliveryDto = requireNonNull(delivery); this.project = requireNonNull(component); } void ensureAdminPermission(UserSession userSession) { userSession.checkEntityPermission(UserRole.ADMIN, project); } void writeTo(Request request, Response response) { Webhooks.DeliveryWsResponse.Builder responseBuilder = Webhooks.DeliveryWsResponse.newBuilder(); Webhooks.Delivery.Builder deliveryBuilder = Webhooks.Delivery.newBuilder(); copyDtoToProtobuf(project, deliveryDto, deliveryBuilder); responseBuilder.setDelivery(deliveryBuilder); writeProtobuf(responseBuilder.build(), request, response); } } }
4,299
37.392857
109
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhookSupport.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import okhttp3.HttpUrl; import org.sonar.api.config.Configuration; import org.sonar.api.web.UserRole; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.server.user.UserSession; import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY; public class WebhookSupport { private final UserSession userSession; private final Configuration configuration; private final NetworkInterfaceProvider networkInterfaceProvider; public WebhookSupport(UserSession userSession, Configuration configuration, NetworkInterfaceProvider networkInterfaceProvider) { this.userSession = userSession; this.configuration = configuration; this.networkInterfaceProvider = networkInterfaceProvider; } void checkPermission(ProjectDto projectDto) { userSession.checkEntityPermission(UserRole.ADMIN, projectDto); } void checkPermission() { userSession.checkPermission(GlobalPermission.ADMINISTER); } void checkUrlPattern(String url, String message, Object... messageArguments) { try { HttpUrl okUrl = HttpUrl.parse(url); if (okUrl == null) { throw new IllegalArgumentException(String.format(message, messageArguments)); } InetAddress address = InetAddress.getByName(okUrl.host()); if (configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY) .orElse(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE) && (address.isLoopbackAddress() || address.isAnyLocalAddress() || isLocalAddress(address))) { throw new IllegalArgumentException("Invalid URL: loopback and wildcard addresses are not allowed for webhooks."); } } catch (UnknownHostException e) { // if a host can not be resolved the deliveries will fail - no need to block it from being set // this will only happen for public URLs } catch (SocketException e) { throw new IllegalStateException("Can not retrieve a network interfaces", e); } } private boolean isLocalAddress(InetAddress address) throws SocketException { return networkInterfaceProvider.getNetworkInterfaceAddresses().stream() .anyMatch(a -> a != null && a.equals(address)); } }
3,254
39.185185
130
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhookWsSupport.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDeliveryDto; import org.sonar.db.webhook.WebhookDeliveryLiteDto; import org.sonarqube.ws.Webhooks; import static java.util.Optional.ofNullable; import static org.sonar.api.utils.DateUtils.formatDateTime; class WebhookWsSupport { private WebhookWsSupport() { // only statics } static Webhooks.Delivery.Builder copyDtoToProtobuf(ProjectDto project, WebhookDeliveryLiteDto dto, Webhooks.Delivery.Builder builder) { builder .clear() .setId(dto.getUuid()) .setAt(formatDateTime(dto.getCreatedAt())) .setName(dto.getName()) .setUrl(dto.getUrl()) .setSuccess(dto.isSuccess()) .setComponentKey(project.getKey()); ofNullable(dto.getCeTaskUuid()).ifPresent(builder::setCeTaskId); ofNullable(dto.getHttpStatus()).ifPresent(builder::setHttpStatus); ofNullable(dto.getDurationMs()).ifPresent(builder::setDurationMs); return builder; } static Webhooks.Delivery.Builder copyDtoToProtobuf(ProjectDto project, WebhookDeliveryDto dto, Webhooks.Delivery.Builder builder) { copyDtoToProtobuf(project, (WebhookDeliveryLiteDto) dto, builder); builder.setPayload(dto.getPayload()); ofNullable(dto.getErrorStacktrace()).ifPresent(builder::setErrorStacktrace); return builder; } }
2,210
37.789474
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhooksWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import org.sonar.api.server.ws.WebService; import static org.sonar.server.webhook.ws.WebhooksWsParameters.WEBHOOKS_CONTROLLER; public class WebhooksWs implements WebService { private final WebhooksWsAction[] actions; public WebhooksWs(WebhooksWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(WEBHOOKS_CONTROLLER); controller.setDescription("Webhooks allow to notify external services when a project analysis is done"); controller.setSince("6.2"); for (WebhooksWsAction action : actions) { action.define(controller); } controller.done(); } }
1,574
33.23913
108
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhooksWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import org.sonar.server.ws.WsAction; interface WebhooksWsAction extends WsAction { // Marker interface }
989
35.666667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhooksWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; import org.sonar.core.platform.Module; public class WebhooksWsModule extends Module { @Override protected void configureModule() { add( WebhookSupport.class, WebhooksWs.class, ListAction.class, CreateAction.class, UpdateAction.class, DeleteAction.class, WebhookDeliveryAction.class, WebhookDeliveriesAction.class, NetworkInterfaceProvider.class); } }
1,297
32.282051
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/WebhooksWsParameters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.webhook.ws; class WebhooksWsParameters { static final String WEBHOOKS_CONTROLLER = "api/webhooks"; static final String LIST_ACTION = "list"; static final String ACTION_CREATE = "create"; static final String UPDATE_ACTION = "update"; static final String DELETE_ACTION = "delete"; static final String PROJECT_KEY_PARAM = "project"; static final int PROJECT_KEY_PARAM_MAXIMUM_LENGTH = 400; static final String NAME_PARAM = "name"; static final int NAME_PARAM_MAXIMUM_LENGTH = 100; static final String URL_PARAM = "url"; static final int URL_PARAM_MAXIMUM_LENGTH = 512; static final String KEY_PARAM = "webhook"; static final int KEY_PARAM_MAXIMUM_LENGTH = 40; static final String SECRET_PARAM = "secret"; static final int SECRET_PARAM_MAXIMUM_LENGTH = 200; private WebhooksWsParameters() { // prevent instantiation } }
1,727
36.565217
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/webhook/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.webhook.ws; import javax.annotation.ParametersAreNonnullByDefault;
967
39.333333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ws/ws/ListAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws.ws; import com.google.common.collect.Ordering; import java.util.Comparator; import java.util.List; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.Version; import org.sonar.api.utils.text.JsonWriter; import static com.google.common.base.Preconditions.checkState; import static java.util.Optional.ofNullable; public class ListAction implements WebServicesWsAction { private WebService.Context context; @Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction("list") .setSince("4.2") .setDescription("List web services") .setResponseExample(getClass().getResource("list-example.json")) .setHandler(this); action .createParam("include_internals") .setDescription("Include web services that are implemented for internal use only. Their forward-compatibility is not assured") .setBooleanPossibleValues() .setDefaultValue("false"); } @Override public void handle(Request request, Response response) throws Exception { checkState(context != null && !context.controllers().isEmpty(), "Web service controllers must be loaded before calling the action"); boolean includeInternals = request.mandatoryParamAsBoolean("include_internals"); JsonWriter writer = response.newJsonWriter(); writer.beginObject(); writer.name("webServices").beginArray(); // sort controllers by path Ordering<WebService.Controller> ordering = Ordering.natural().onResultOf(WebService.Controller::path); for (WebService.Controller controller : ordering.sortedCopy(context.controllers())) { writeController(writer, controller, includeInternals); } writer.endArray(); writer.endObject(); writer.close(); } @Override public void setContext(WebService.Context context) { this.context = context; } private static void writeController(JsonWriter writer, WebService.Controller controller, boolean includeInternals) { if (includeInternals || !controller.isInternal()) { writer.beginObject(); writer.prop("path", controller.path()); writer.prop("since", controller.since()); writer.prop("description", controller.description()); // sort actions by key Ordering<WebService.Action> ordering = Ordering.natural().onResultOf(WebService.Action::key); writer.name("actions").beginArray(); for (WebService.Action action : ordering.sortedCopy(controller.actions())) { writeAction(writer, action, includeInternals); } writer.endArray(); writer.endObject(); } } private static void writeAction(JsonWriter writer, WebService.Action action, boolean includeInternals) { if (includeInternals || !action.isInternal()) { writer.beginObject(); writer.prop("key", action.key()); writer.prop("description", action.description()); writer.prop("since", action.since()); writer.prop("deprecatedSince", action.deprecatedSince()); writer.prop("internal", action.isInternal()); writer.prop("post", action.isPost()); writer.prop("hasResponseExample", action.responseExample() != null); writeChangelog(writer, action); writeParameters(writer, action, includeInternals); writer.endObject(); } } private static void writeParameters(JsonWriter writer, WebService.Action action, boolean includeInternals) { List<WebService.Param> params = action.params().stream().filter(p -> includeInternals || !p.isInternal()).toList(); if (!params.isEmpty()) { // sort parameters by key Ordering<WebService.Param> ordering = Ordering.natural().onResultOf(WebService.Param::key); writer.name("params").beginArray(); for (WebService.Param param : ordering.sortedCopy(params)) { writeParam(writer, param); } writer.endArray(); } } private static void writeParam(JsonWriter writer, WebService.Param param) { writer.beginObject(); writer.prop("key", param.key()); writer.prop("description", param.description()); writer.prop("since", param.since()); writer.prop("required", param.isRequired()); writer.prop("internal", param.isInternal()); writer.prop("defaultValue", param.defaultValue()); writer.prop("exampleValue", param.exampleValue()); writer.prop("deprecatedSince", param.deprecatedSince()); writer.prop("deprecatedKey", param.deprecatedKey()); writer.prop("deprecatedKeySince", param.deprecatedKeySince()); writer.prop("maxValuesAllowed", param.maxValuesAllowed()); ofNullable(param.possibleValues()).ifPresent(possibleValues -> writer.name("possibleValues").beginArray().values(possibleValues).endArray()); ofNullable(param.maximumLength()).ifPresent(maximumLength -> writer.prop("maximumLength", maximumLength)); ofNullable(param.minimumLength()).ifPresent(minimumLength -> writer.prop("minimumLength", minimumLength)); ofNullable(param.maximumValue()).ifPresent(maximumValue -> writer.prop("maximumValue", maximumValue)); writer.endObject(); } private static void writeChangelog(JsonWriter writer, WebService.Action action) { writer.name("changelog").beginArray(); action.changelog().stream() .sorted(Comparator.comparing((Change change) -> Version.parse(change.getVersion())).reversed()) .forEach(changelog -> { writer.beginObject(); writer.prop("description", changelog.getDescription()); writer.prop("version", changelog.getVersion()); writer.endObject(); }); writer.endArray(); } }
6,592
40.727848
145
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ws/ws/ResponseExampleAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.text.JsonWriter; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; public class ResponseExampleAction implements WebServicesWsAction { private WebService.Context context; @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("response_example") .setDescription("Display web service response example") .setResponseExample(getClass().getResource("response_example-example.json")) .setSince("4.4") .setHandler(this); action.createParam("controller") .setRequired(true) .setDescription("Controller of the web service") .setExampleValue("api/issues"); action.createParam("action") .setRequired(true) .setDescription("Action of the web service") .setExampleValue("search"); } @Override public void handle(Request request, Response response) throws Exception { checkState(context != null, "Webservice global context must be loaded before calling the action"); String controllerKey = request.mandatoryParam("controller"); WebService.Controller controller = context.controller(controllerKey); checkArgument(controller != null, "Controller does not exist: %s", controllerKey); String actionKey = request.mandatoryParam("action"); WebService.Action action = controller.action(actionKey); checkArgument(action != null, "Action does not exist: %s", actionKey); if (action.responseExample() == null) { response.noContent(); return; } try (JsonWriter json = response.newJsonWriter()) { json.beginObject() .prop("format", action.responseExampleFormat()) .prop("example", action.responseExampleAsString()) .endObject(); } } @Override public void setContext(WebService.Context context) { this.context = context; } }
2,973
34.404762
102
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ws/ws/WebServicesWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws.ws; import java.util.List; import org.sonar.api.server.ws.WebService; /** * This web service lists all the existing web services, including itself, * for documentation usage. * * @since 4.2 */ public class WebServicesWs implements WebService { private final List<WebServicesWsAction> actions; public WebServicesWs(List<WebServicesWsAction> actions) { this.actions = actions; } @Override public void define(final Context context) { NewController controller = context .createController("api/webservices") .setSince("4.2") .setDescription("Get information on the web api supported on this instance."); actions.forEach(action -> { action.define(controller); action.setContext(context); }); controller.done(); } }
1,653
30.207547
84
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ws/ws/WebServicesWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws.ws; import org.sonar.api.server.ws.WebService; import org.sonar.server.ws.WsAction; public interface WebServicesWsAction extends WsAction { // marker interface void setContext(WebService.Context context); }
1,085
35.2
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ws/ws/WebServicesWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws.ws; import org.sonar.core.platform.Module; public class WebServicesWsModule extends Module { @Override protected void configureModule() { add( WebServicesWs.class, ListAction.class, ResponseExampleAction.class); } }
1,117
32.878788
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ws/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.ws.ws; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/AlmIntegrationsWSModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almintegration.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class AlmIntegrationsWSModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new AlmIntegrationsWSModule().configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,290
35.885714
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/AlmIntegrationsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almintegration.ws; import java.util.Collections; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class AlmIntegrationsWsTest { private final AlmIntegrationsWs underTest = new AlmIntegrationsWs(Collections.singletonList(new AlmIntegrationsWsAction() { @Override public void handle(Request request, Response response) { // nothing to do } @Override public void define(WebService.NewController controller) { controller.createAction("foo") .setHandler((request, response) -> { throw new UnsupportedOperationException("not implemented"); }); } })); @Test public void define_ws() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/alm_integrations"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(1); WebService.Action fooAction = controller.action("foo"); assertThat(fooAction).isNotNull(); assertThat(fooAction.handler()).isNotNull(); } }
2,157
33.806452
125
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/CredentialsEncoderHelperTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almintegration.ws; import java.util.Base64; import org.junit.Test; import org.sonar.db.alm.setting.ALM; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; public class CredentialsEncoderHelperTest { private static final String PAT = "pat"; private static final String USERNAME = "user"; @Test public void encodes_credential_returns_just_pat_for_non_bitbucketcloud() { assertThat(CredentialsEncoderHelper.encodeCredentials(ALM.GITHUB, PAT, null)) .isEqualTo("pat"); } @Test public void encodes_credential_returns_username_and_encoded_pat_for_bitbucketcloud() { String encodedPat = Base64.getEncoder().encodeToString((USERNAME + ":" + PAT).getBytes(UTF_8)); String encodedCredential = CredentialsEncoderHelper.encodeCredentials(ALM.BITBUCKET_CLOUD, PAT, USERNAME); assertThat(encodedCredential) .doesNotContain(USERNAME) .doesNotContain(PAT) .contains(encodedPat); } }
1,860
35.490196
110
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/ProjectKeyGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almintegration.ws; import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.core.util.UuidFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.sonar.server.almintegration.ws.ProjectKeyGenerator.MAX_PROJECT_KEY_SIZE; import static org.sonar.server.almintegration.ws.ProjectKeyGenerator.PROJECT_KEY_SEPARATOR; @RunWith(MockitoJUnitRunner.class) public class ProjectKeyGeneratorTest { private static final int MAX_UUID_SIZE = 40; private static final String UUID_STRING = RandomStringUtils.randomAlphanumeric(MAX_UUID_SIZE); @Mock private UuidFactory uuidFactory; @InjectMocks private ProjectKeyGenerator projectKeyGenerator; @Before public void setUp() { when(uuidFactory.create()).thenReturn(UUID_STRING); } @Test public void generateUniqueProjectKey_shortProjectName_shouldAppendUuid() { String fullProjectName = RandomStringUtils.randomAlphanumeric(10); assertThat(projectKeyGenerator.generateUniqueProjectKey(fullProjectName)) .isEqualTo(generateExpectedKeyName(fullProjectName)); } @Test public void generateUniqueProjectKey_projectNameEqualsToMaximumSize_shouldTruncateProjectNameAndPreserveUUID() { String fullProjectName = RandomStringUtils.randomAlphanumeric(MAX_PROJECT_KEY_SIZE); String projectKey = projectKeyGenerator.generateUniqueProjectKey(fullProjectName); assertThat(projectKey) .hasSize(MAX_PROJECT_KEY_SIZE) .isEqualTo(generateExpectedKeyName(fullProjectName.substring(fullProjectName.length() + UUID_STRING.length() + 1 - MAX_PROJECT_KEY_SIZE))); } @Test public void generateUniqueProjectKey_projectNameBiggerThanMaximumSize_shouldTruncateProjectNameAndPreserveUUID() { String fullProjectName = RandomStringUtils.randomAlphanumeric(MAX_PROJECT_KEY_SIZE + 50); String projectKey = projectKeyGenerator.generateUniqueProjectKey(fullProjectName); assertThat(projectKey) .hasSize(MAX_PROJECT_KEY_SIZE) .isEqualTo(generateExpectedKeyName(fullProjectName.substring(fullProjectName.length() + UUID_STRING.length() + 1 - MAX_PROJECT_KEY_SIZE))); } @Test public void generateUniqueProjectKey_projectNameContainsSlashes_shouldBeEscaped() { String fullProjectName = "a/b/c"; assertThat(projectKeyGenerator.generateUniqueProjectKey(fullProjectName)) .isEqualTo(generateExpectedKeyName(fullProjectName.replace("/", "_"))); } private String generateExpectedKeyName(String truncatedProjectName) { return truncatedProjectName + PROJECT_KEY_SEPARATOR + UUID_STRING; } }
3,650
38.258065
145
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/github/GithubProvisioningWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almintegration.ws.github; import java.util.Set; import org.junit.Test; import org.sonar.api.server.ws.WebService; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class GithubProvisioningWsTest { @Test public void define_createsOneController() { WebService.Context context = mock(WebService.Context.class); GithubProvisioningAction action = mock(GithubProvisioningAction.class); WebService.NewController controller = mock(WebService.NewController.class); GithubProvisioningWs scimWs = new GithubProvisioningWs(Set.of(action)); when(context.createController("api/github_provisioning")).thenReturn(controller); when(controller.setDescription(any())).thenReturn(controller); when(controller.setSince(any())).thenReturn(controller); scimWs.define(context); verify(context, only()).createController("api/github_provisioning"); verify(action, only()).define(any()); } }
1,952
38.06
85
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/AlmSettingsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almsettings.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class AlmSettingsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new AlmSettingsWsModule().configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,279
35.571429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.authentication.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class AuthenticationWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new AuthenticationWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(4); } }
1,286
35.771429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.authentication.ws; import java.util.Collections; import org.junit.Test; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class AuthenticationWsTest { private AuthenticationWs underTest = new AuthenticationWs(Collections.singletonList(new AuthenticationWsAction() { @Override public void define(WebService.NewController controller) { controller.createAction("foo") .setHandler((request, response) -> { throw new UnsupportedOperationException("not implemented"); }); } })); @Test public void define_ws() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/authentication"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(1); WebService.Action fooAction = controller.action("foo"); assertThat(fooAction).isNotNull(); assertThat(fooAction.handler()).isNotNull(); } }
1,959
34.636364
116
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LogoutActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.authentication.ws; import java.util.Collections; import java.util.Optional; import org.junit.Test; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.FilterChain; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.ws.ServletFilterHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.server.authentication.event.AuthenticationEvent.Source.sso; public class LogoutActionTest { private static final UserDto USER = newUserDto().setLogin("john"); private final HttpRequest request = mock(HttpRequest.class); private final HttpResponse response = mock(HttpResponse.class); private final FilterChain chain = mock(FilterChain.class); private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class); private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class); private final LogoutAction underTest = new LogoutAction(jwtHttpHandler, authenticationEvent); @Test public void verify_definition() { String controllerKey = "foo"; WebService.Context context = new WebService.Context(); WebService.NewController newController = context.createController(controllerKey); underTest.define(newController); newController.done(); WebService.Action logout = context.controller(controllerKey).action("logout"); assertThat(logout).isNotNull(); assertThat(logout.handler()).isInstanceOf(ServletFilterHandler.class); assertThat(logout.isPost()).isTrue(); assertThat(logout.params()).isEmpty(); } @Test public void do_get_pattern() { assertThat(underTest.doGetPattern().matches("/api/authentication/logout")).isTrue(); assertThat(underTest.doGetPattern().matches("/api/authentication/login")).isFalse(); assertThat(underTest.doGetPattern().matches("/api/authentication/logou")).isFalse(); assertThat(underTest.doGetPattern().matches("/api/authentication/logoutthing")).isFalse(); assertThat(underTest.doGetPattern().matches("/foo")).isFalse(); } @Test public void return_400_on_get_request() { when(request.getMethod()).thenReturn("GET"); underTest.doFilter(request, response, chain); verifyNoInteractions(jwtHttpHandler, chain); verify(response).setStatus(400); } @Test public void logout_logged_user() { setUser(USER); executeRequest(); verify(jwtHttpHandler).removeToken(request, response); verifyNoInteractions(chain); verify(authenticationEvent).logoutSuccess(request, "john"); } @Test public void logout_unlogged_user() { setNoUser(); executeRequest(); verify(jwtHttpHandler).removeToken(request, response); verifyNoInteractions(chain); verify(authenticationEvent).logoutSuccess(request, null); } @Test public void generate_auth_event_on_failure() { setUser(USER); AuthenticationException exception = AuthenticationException.newBuilder().setMessage("error!").setSource(sso()).build(); doThrow(exception).when(jwtHttpHandler).getToken(any(HttpRequest.class), any(HttpResponse.class)); executeRequest(); verify(authenticationEvent).logoutFailure(request, "error!"); verify(jwtHttpHandler).removeToken(any(HttpRequest.class), any(HttpResponse.class)); verifyNoInteractions(chain); } private void executeRequest() { when(request.getMethod()).thenReturn("POST"); underTest.doFilter(request, response, chain); } private void setUser(UserDto user) { when(jwtHttpHandler.getToken(any(HttpRequest.class), any(HttpResponse.class))) .thenReturn(Optional.of(new JwtHttpHandler.Token(user, Collections.emptyMap()))); } private void setNoUser() { when(jwtHttpHandler.getToken(any(HttpRequest.class), any(HttpResponse.class))).thenReturn(Optional.empty()); } }
5,254
36.007042
123
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/ValidateActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.authentication.ws; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.FilterChain; import org.sonar.server.authentication.BasicAuthentication; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.ws.ServletFilterHandler; import org.sonar.test.JsonAssert; import org.sonarqube.ws.MediaTypes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.user.UserTesting.newUserDto; public class ValidateActionTest { private final StringWriter stringWriter = new StringWriter(); private final HttpRequest request = mock(HttpRequest.class); private final HttpResponse response = mock(HttpResponse.class); private final FilterChain chain = mock(FilterChain.class); private final BasicAuthentication basicAuthentication = mock(BasicAuthentication.class); private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class); private final MapSettings settings = new MapSettings(); private final ValidateAction underTest = new ValidateAction(settings.asConfig(), basicAuthentication, jwtHttpHandler); @Before public void setUp() throws Exception { PrintWriter writer = new PrintWriter(stringWriter); when(response.getWriter()).thenReturn(writer); } @Test public void verify_definition() { String controllerKey = "foo"; WebService.Context context = new WebService.Context(); WebService.NewController newController = context.createController(controllerKey); underTest.define(newController); newController.done(); WebService.Action validate = context.controller(controllerKey).action("validate"); assertThat(validate).isNotNull(); assertThat(validate.handler()).isInstanceOf(ServletFilterHandler.class); assertThat(validate.responseExampleAsString()).isNotEmpty(); assertThat(validate.params()).isEmpty(); } @Test public void return_true_when_jwt_token_is_set() throws Exception { when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.of(newUserDto())); when(basicAuthentication.authenticate(request)).thenReturn(Optional.empty()); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":true}"); } @Test public void return_true_when_basic_auth() throws Exception { when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); when(basicAuthentication.authenticate(request)).thenReturn(Optional.of(newUserDto())); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":true}"); } @Test public void return_true_when_no_jwt_nor_basic_auth_and_no_force_authentication() throws Exception { settings.setProperty("sonar.forceAuthentication", "false"); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); when(basicAuthentication.authenticate(request)).thenReturn(Optional.empty()); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":true}"); } @Test public void return_false_when_no_jwt_nor_basic_auth_and_force_authentication_is_true() throws Exception { settings.setProperty("sonar.forceAuthentication", "true"); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); when(basicAuthentication.authenticate(request)).thenReturn(Optional.empty()); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":false}"); } @Test public void return_false_when_no_jwt_nor_basic_auth_and_force_authentication_fallback_to_default() throws Exception { when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); when(basicAuthentication.authenticate(request)).thenReturn(Optional.empty()); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":false}"); } @Test public void return_false_when_jwt_throws_unauthorized_exception() throws Exception { doThrow(AuthenticationException.class).when(jwtHttpHandler).validateToken(request, response); when(basicAuthentication.authenticate(request)).thenReturn(Optional.empty()); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":false}"); } @Test public void return_false_when_basic_authenticator_throws_unauthorized_exception() throws Exception { when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); doThrow(AuthenticationException.class).when(basicAuthentication).authenticate(request); underTest.doFilter(request, response, chain); verify(response).setContentType(MediaTypes.JSON); JsonAssert.assertJson(stringWriter.toString()).isSimilarTo("{\"valid\":false}"); } }
6,669
40.428571
120
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ETagUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.badge.ws; import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; public class ETagUtilsTest { @Test public void getETag_should_start_with_W_SLASH() { assertThat(ETagUtils.getETag(randomAlphanumeric(15))).startsWith("W/"); } @Test public void getETag_should_return_same_value_for_same_input() { String input = randomAlphanumeric(200); assertThat(ETagUtils.getETag(input)).isEqualTo(ETagUtils.getETag(input)); } }
1,412
33.463415
77
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ProjectBadgesWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.badge.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class ProjectBadgesWsModuleTest { private final ProjectBadgesWsModule underTest = new ProjectBadgesWsModule(); @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,339
35.216216
78
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ProjectBadgesWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.badge.ws; import java.util.Collections; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class ProjectBadgesWsTest { @Test public void test_definition() { ProjectBadgesWsAction action = createFakeAction(); WebService.Context context = new WebService.Context(); ProjectBadgesWs underTest = new ProjectBadgesWs(Collections.singletonList(action)); underTest.define(context); WebService.Controller controller = context.controller("api/project_badges"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("7.1"); } private ProjectBadgesWsAction createFakeAction() { return new ProjectBadgesWsAction() { @Override public void define(WebService.NewController context) { context.createAction("fake").setHandler(this); } @Override public void handle(Request request, Response response) { // nothing to do } }; } }
2,023
32.733333
87
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgFormatterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.badge.ws; import org.junit.Test; import org.sonar.test.TestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.badge.ws.SvgFormatter.formatDuration; import static org.sonar.server.badge.ws.SvgFormatter.formatNumeric; import static org.sonar.server.badge.ws.SvgFormatter.formatPercent; public class SvgFormatterTest { private static final int HOURS_IN_DAY = 8; private static final long ONE_MINUTE = 1L; private static final long ONE_HOUR = ONE_MINUTE * 60; private static final long ONE_DAY = HOURS_IN_DAY * ONE_HOUR; @Test public void format_numeric() { assertThat(formatNumeric(0L)).isEqualTo("0"); assertThat(formatNumeric(5L)).isEqualTo("5"); assertThat(formatNumeric(950L)).isEqualTo("950"); assertThat(formatNumeric(1_000L)).isEqualTo("1k"); assertThat(formatNumeric(1_010L)).isEqualTo("1k"); assertThat(formatNumeric(1_100L)).isEqualTo("1.1k"); assertThat(formatNumeric(1_690L)).isEqualTo("1.7k"); assertThat(formatNumeric(950_000L)).isEqualTo("950k"); assertThat(formatNumeric(1_000_000L)).isEqualTo("1m"); assertThat(formatNumeric(1_010_000L)).isEqualTo("1m"); assertThat(formatNumeric(1_000_000_000L)).isEqualTo("1b"); assertThat(formatNumeric(1_000_000_000_000L)).isEqualTo("1t"); } @Test public void format_percent() { assertThat(formatPercent(0d)).isEqualTo("0%"); assertThat(formatPercent(12.345)).isEqualTo("12.3%"); assertThat(formatPercent(12.56)).isEqualTo("12.6%"); } @Test public void format_duration() { assertThat(formatDuration(0)).isEqualTo("0"); assertThat(formatDuration(ONE_DAY)).isEqualTo("1d"); assertThat(formatDuration(ONE_HOUR)).isEqualTo("1h"); assertThat(formatDuration(ONE_MINUTE)).isEqualTo("1min"); assertThat(formatDuration(5 * ONE_DAY)).isEqualTo("5d"); assertThat(formatDuration(2 * ONE_HOUR)).isEqualTo("2h"); assertThat(formatDuration(ONE_MINUTE)).isEqualTo("1min"); assertThat(formatDuration(5 * ONE_DAY + 3 * ONE_HOUR)).isEqualTo("5d"); assertThat(formatDuration(3 * ONE_HOUR + 25 * ONE_MINUTE)).isEqualTo("3h"); assertThat(formatDuration(5 * ONE_DAY + 3 * ONE_HOUR + 40 * ONE_MINUTE)).isEqualTo("5d"); } @Test public void format_duration_is_rounding_result() { // When starting to add more than 4 hours, the result will be rounded to the next day (as 4 hour is a half day) assertThat(formatDuration(5 * ONE_DAY + 4 * ONE_HOUR)).isEqualTo("6d"); assertThat(formatDuration(5 * ONE_DAY + 5 * ONE_HOUR)).isEqualTo("6d"); // When starting to add more than 30 minutes, the result will be rounded to the next hour assertThat(formatDuration(3 * ONE_HOUR + 30 * ONE_MINUTE)).isEqualTo("4h"); assertThat(formatDuration(3 * ONE_HOUR + 40 * ONE_MINUTE)).isEqualTo("4h"); // When duration is close to next unit (0.9), the result is rounded to next unit assertThat(formatDuration(7 * ONE_HOUR + 20 + ONE_MINUTE)).isEqualTo("1d"); assertThat(formatDuration(55 * ONE_MINUTE)).isEqualTo("1h"); } @Test public void only_statics() { assertThat(TestUtils.hasOnlyPrivateConstructors(SvgFormatter.class)).isTrue(); } }
4,051
38.72549
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.badge.ws; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.sonar.api.measures.Metric; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.server.badge.ws.SvgGenerator.Color.DEFAULT; public class SvgGeneratorTest { private SvgGenerator underTest; @Test public void generate_badge() { initSvgGenerator(); String result = underTest.generateBadge("label", "10", DEFAULT); checkBadge(result, "label", "10", DEFAULT); } @Test public void generate_quality_gate() { initSvgGenerator(); String result = underTest.generateQualityGate(ERROR); checkQualityGate(result, ERROR); } @Test public void generate_deprecated_warning_quality_gate() { initSvgGenerator(); String result = underTest.generateQualityGate(WARN); assertThat(result).isEqualTo(readTemplate("quality_gate_warn.svg")); } @Test public void generate_error() { initSvgGenerator(); String result = underTest.generateError("Error"); assertThat(result).contains("<text", ">Error</text>"); } @Test public void fail_when_unknown_character() { initSvgGenerator(); assertThatThrownBy(() -> underTest.generateError("Méssage with accent")) .hasMessage("Invalid character 'é'"); } private void initSvgGenerator() { underTest = new SvgGenerator(); } private void checkBadge(String svg, String expectedLabel, String expectedValue, SvgGenerator.Color expectedColorValue) { assertThat(svg).contains( "<text", expectedLabel + "</text>", "<text", expectedValue + "</text>", "rect fill=\"" + expectedColorValue.getValue() + "\""); } private void checkQualityGate(String response, Metric.Level status) { switch (status) { case OK: assertThat(response).isEqualTo(readTemplate("quality_gate_passed.svg")); break; case ERROR: assertThat(response).isEqualTo(readTemplate("quality_gate_failed.svg")); break; } } private String readTemplate(String template) { try { return IOUtils.toString(getClass().getResource("templates/sonarqube/" + template), UTF_8); } catch (IOException e) { throw new IllegalStateException(String.format("Can't read svg template '%s'", template), e); } } }
3,426
29.327434
122
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/BatchIndexTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.batch; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.CharUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.platform.ServerFileSystem; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class BatchIndexTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File jar; private ServerFileSystem fs = mock(ServerFileSystem.class); @Before public void prepare_fs() throws IOException { File homeDir = temp.newFolder(); when(fs.getHomeDir()).thenReturn(homeDir); File batchDir = new File(homeDir, "lib/scanner"); FileUtils.forceMkdir(batchDir); jar = new File(batchDir, "sonar-batch.jar"); FileUtils.writeStringToFile(new File(batchDir, "sonar-batch.jar"), "foo"); } @Test public void get_index() { BatchIndex batchIndex = new BatchIndex(fs); batchIndex.start(); String index = batchIndex.getIndex(); assertThat(index).isEqualTo("sonar-batch.jar|acbd18db4cc2f85cedef654fccc4a4d8" + CharUtils.LF); batchIndex.stop(); } @Test public void get_file() { BatchIndex batchIndex = new BatchIndex(fs); batchIndex.start(); File file = batchIndex.getFile("sonar-batch.jar"); assertThat(file).isEqualTo(jar); } /** * Do not allow to download files located outside the directory lib/batch, for example * /etc/passwd */ @Test public void check_location_of_file() { assertThatThrownBy(() -> { BatchIndex batchIndex = new BatchIndex(fs); batchIndex.start(); batchIndex.getFile("../sonar-batch.jar"); }) .isInstanceOf(NotFoundException.class) .hasMessage("Bad filename: ../sonar-batch.jar"); } @Test public void file_does_not_exist() { assertThatThrownBy(() -> { BatchIndex batchIndex = new BatchIndex(fs); batchIndex.start(); batchIndex.getFile("other.jar"); }) .isInstanceOf(NotFoundException.class) .hasMessage("Bad filename: other.jar"); } }
3,192
28.841121
99
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/BatchWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.batch; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class BatchWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new BatchWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(6); } }
1,257
33.944444
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/ProjectActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.batch; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.scanner.protocol.input.FileData; import org.sonar.scanner.protocol.input.ProjectRepositories; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Batch.WsProjectResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; public class ProjectActionTest { private final ProjectDataLoader projectDataLoader = mock(ProjectDataLoader.class); private final WsActionTester ws = new WsActionTester(new ProjectAction(projectDataLoader)); @Test public void project_referentials() { String projectKey = "org.codehaus.sonar:sonar"; ProjectRepositories projectReferentials = mock(ProjectRepositories.class); ArgumentCaptor<ProjectDataQuery> queryArgumentCaptor = ArgumentCaptor.forClass(ProjectDataQuery.class); when(projectDataLoader.load(queryArgumentCaptor.capture())).thenReturn(projectReferentials); TestResponse response = ws.newRequest() .setParam("key", projectKey) .setParam("branch", "my_branch") .setParam("profile", "Default") .setParam("preview", "false") .execute(); assertJson(response.getInput()).isSimilarTo("{\"fileDataByPath\": {}}"); assertThat(queryArgumentCaptor.getValue().getProjectKey()).isEqualTo(projectKey); assertThat(queryArgumentCaptor.getValue().getProfileName()).isEqualTo("Default"); assertThat(queryArgumentCaptor.getValue().getBranch()).isEqualTo("my_branch"); } /** * SONAR-7084 */ @Test public void do_not_fail_when_a_path_is_null() { String projectKey = "org.codehaus.sonar:sonar"; ProjectRepositories projectRepositories = new ProjectRepositories() .addFileData(null, new FileData(null, null)); when(projectDataLoader.load(any(ProjectDataQuery.class))).thenReturn(projectRepositories); WsProjectResponse wsProjectResponse = ws.newRequest() .setParam("key", projectKey) .setParam("profile", "Default") .executeProtobuf(WsProjectResponse.class); assertThat(wsProjectResponse.getFileDataByModuleAndPathMap()).isEmpty(); } @Test public void use_new_file_structure_for_projects_without_submodules() { String projectKey = "org.codehaus.sonar:sonar"; ProjectRepositories projectRepositories = new ProjectRepositories() .addFileData("src/main/java/SomeClass.java", new FileData("789456", "123456789")); when(projectDataLoader.load(any(ProjectDataQuery.class))).thenReturn(projectRepositories); WsProjectResponse wsProjectResponse = ws.newRequest() .setParam("key", projectKey) .setParam("profile", "Default") .executeProtobuf(WsProjectResponse.class); assertThat(wsProjectResponse.getFileDataByModuleAndPathMap()).isEmpty(); assertThat(wsProjectResponse.getFileDataByPathCount()).isOne(); assertThat(wsProjectResponse.getFileDataByPathMap().get("src/main/java/SomeClass.java")).isNotNull(); } }
4,014
40.391753
107
java