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-auth/src/main/java/org/sonar/server/permission/PermissionService.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.permission; import java.util.List; import org.sonar.db.permission.GlobalPermission; public interface PermissionService { List<GlobalPermission> getGlobalPermissions(); List<String> getAllProjectPermissions(); }
1,087
34.096774
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/PermissionServiceImpl.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.permission; import java.util.List; import javax.annotation.concurrent.Immutable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.web.UserRole; import org.sonar.db.permission.GlobalPermission; @Immutable public class PermissionServiceImpl implements PermissionService { private static final List<String> ALL_PROJECT_PERMISSIONS = List.of( UserRole.ADMIN, UserRole.CODEVIEWER, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, UserRole.SCAN, UserRole.USER ); private static final List<GlobalPermission> ALL_GLOBAL_PERMISSIONS = List.of(GlobalPermission.values()); private final List<GlobalPermission> globalPermissions; private final List<String> projectPermissions; public PermissionServiceImpl(ResourceTypes resourceTypes) { globalPermissions = List.copyOf(ALL_GLOBAL_PERMISSIONS.stream() .filter(s -> !s.equals(GlobalPermission.APPLICATION_CREATOR) || resourceTypes.isQualifierPresent(Qualifiers.APP)) .filter(s -> !s.equals(GlobalPermission.PORTFOLIO_CREATOR) || resourceTypes.isQualifierPresent(Qualifiers.VIEW)) .toList()); projectPermissions = List.copyOf(ALL_PROJECT_PERMISSIONS.stream() .filter(s -> !s.equals(GlobalPermission.APPLICATION_CREATOR.getKey()) || resourceTypes.isQualifierPresent(Qualifiers.APP)) .filter(s -> !s.equals(GlobalPermission.PORTFOLIO_CREATOR.getKey()) || resourceTypes.isQualifierPresent(Qualifiers.VIEW)) .toList()); } /** * Return an immutable Set of all permissions */ @Override public List<GlobalPermission> getGlobalPermissions() { return globalPermissions; } /** * Return an immutable Set of all project permissions */ @Override public List<String> getAllProjectPermissions() { return projectPermissions; } }
2,707
36.611111
128
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/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.permission; import javax.annotation.ParametersAreNonnullByDefault;
968
37.76
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/AbstractUserSession.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; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.web.UserRole; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.UnauthorizedException; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.server.user.UserSession.IdentityProvider.SONARQUBE; public abstract class AbstractUserSession implements UserSession { private static final Set<String> PUBLIC_PERMISSIONS = Set.of(UserRole.USER, UserRole.CODEVIEWER); private static final String INSUFFICIENT_PRIVILEGES_MESSAGE = "Insufficient privileges"; private static final String AUTHENTICATION_IS_REQUIRED_MESSAGE = "Authentication is required"; protected static Identity computeIdentity(UserDto userDto) { IdentityProvider identityProvider = IdentityProvider.getFromKey(userDto.getExternalIdentityProvider()); ExternalIdentity externalIdentity = identityProvider == SONARQUBE ? null : externalIdentityOf(userDto); return new Identity(identityProvider, externalIdentity); } private static ExternalIdentity externalIdentityOf(UserDto userDto) { String externalId = userDto.getExternalId(); String externalLogin = userDto.getExternalLogin(); return new ExternalIdentity(externalId, externalLogin); } protected static final class Identity { private final IdentityProvider identityProvider; private final ExternalIdentity externalIdentity; private Identity(IdentityProvider identityProvider, @Nullable ExternalIdentity externalIdentity) { this.identityProvider = identityProvider; this.externalIdentity = externalIdentity; } public IdentityProvider getIdentityProvider() { return identityProvider; } @CheckForNull public ExternalIdentity getExternalIdentity() { return externalIdentity; } } @Override @CheckForNull public Long getLastSonarlintConnectionDate() { return null; } @Override public final boolean hasPermission(GlobalPermission permission) { return hasPermissionImpl(permission); } protected abstract boolean hasPermissionImpl(GlobalPermission permission); @Override public boolean hasComponentPermission(String permission, ComponentDto component) { Optional<String> projectUuid1 = componentUuidToEntityUuid(component.uuid()); return projectUuid1 .map(projectUuid -> hasEntityUuidPermission(permission, projectUuid)) .orElse(false); } @Override public final boolean hasEntityPermission(String permission, EntityDto entity) { return hasEntityUuidPermission(permission, entity.getAuthUuid()); } @Override public final boolean hasEntityPermission(String permission, String entityUuid) { return hasEntityUuidPermission(permission, entityUuid); } @Override public final boolean hasChildProjectsPermission(String permission, ComponentDto component) { return componentUuidToEntityUuid(component.uuid()) .map(applicationUuid -> hasChildProjectsPermission(permission, applicationUuid)).orElse(false); } @Override public final boolean hasChildProjectsPermission(String permission, EntityDto application) { return hasChildProjectsPermission(permission, application.getUuid()); } @Override public final boolean hasPortfolioChildProjectsPermission(String permission, ComponentDto portfolio) { return hasPortfolioChildProjectsPermission(permission, portfolio.uuid()); } @Override public boolean hasComponentUuidPermission(String permission, String componentUuid) { Optional<String> entityUuid = componentUuidToEntityUuid(componentUuid); return entityUuid .map(s -> hasEntityUuidPermission(permission, s)) .orElse(false); } protected abstract Optional<String> componentUuidToEntityUuid(String componentUuid); protected abstract boolean hasEntityUuidPermission(String permission, String entityUuid); protected abstract boolean hasChildProjectsPermission(String permission, String applicationUuid); protected abstract boolean hasPortfolioChildProjectsPermission(String permission, String portfolioUuid); @Override public final List<ComponentDto> keepAuthorizedComponents(String permission, Collection<ComponentDto> components) { return doKeepAuthorizedComponents(permission, components); } @Override public <T extends EntityDto> List<T> keepAuthorizedEntities(String permission, Collection<T> projects) { return doKeepAuthorizedEntities(permission, projects); } /** * Naive implementation, to be overridden if needed */ protected <T extends EntityDto> List<T> doKeepAuthorizedEntities(String permission, Collection<T> entities) { boolean allowPublicComponent = PUBLIC_PERMISSIONS.contains(permission); return entities.stream() .filter(c -> (allowPublicComponent && !c.isPrivate()) || hasEntityPermission(permission, c.getUuid())) .toList(); } /** * Naive implementation, to be overridden if needed */ protected List<ComponentDto> doKeepAuthorizedComponents(String permission, Collection<ComponentDto> components) { boolean allowPublicComponent = PUBLIC_PERMISSIONS.contains(permission); return components.stream() .filter(c -> (allowPublicComponent && !c.isPrivate()) || hasComponentPermission(permission, c)) .toList(); } @Override public final UserSession checkLoggedIn() { if (!isLoggedIn()) { throw new UnauthorizedException(AUTHENTICATION_IS_REQUIRED_MESSAGE); } return this; } @Override public final UserSession checkPermission(GlobalPermission permission) { if (!hasPermission(permission)) { throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } return this; } @Override public final UserSession checkComponentPermission(String projectPermission, ComponentDto component) { if (!hasComponentPermission(projectPermission, component)) { throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } return this; } @Override public UserSession checkEntityPermission(String projectPermission, EntityDto entity) { if (hasEntityPermission(projectPermission, entity)) { return this; } throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } @Override public UserSession checkChildProjectsPermission(String projectPermission, ComponentDto component) { if (!APP.equals(component.qualifier()) || hasChildProjectsPermission(projectPermission, component)) { return this; } throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } @Override public UserSession checkChildProjectsPermission(String projectPermission, EntityDto application) { if (!APP.equals(application.getQualifier()) || hasChildProjectsPermission(projectPermission, application)) { return this; } throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } @Override public final UserSession checkComponentUuidPermission(String permission, String componentUuid) { if (!hasComponentUuidPermission(permission, componentUuid)) { throw new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } return this; } public static ForbiddenException insufficientPrivilegesException() { return new ForbiddenException(INSUFFICIENT_PRIVILEGES_MESSAGE); } @Override public final UserSession checkIsSystemAdministrator() { if (!isSystemAdministrator()) { throw insufficientPrivilegesException(); } return this; } }
8,647
35.033333
116
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/BearerPasscode.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; import java.util.Optional; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; import org.sonar.api.server.ws.Request; import static org.sonar.process.ProcessProperties.Property.WEB_SYSTEM_PASS_CODE; public class BearerPasscode { public static final String PASSCODE_HTTP_HEADER = "Authorization"; private final Configuration configuration; public BearerPasscode(Configuration configuration) { this.configuration = configuration; } public boolean isValid(Request request) { Optional<String> passcodeOpt = configuration.get(WEB_SYSTEM_PASS_CODE.getKey()).map(StringUtils::trimToNull); if (passcodeOpt.isEmpty()) { return false; } String configuredPasscode = passcodeOpt.get(); return request.header(PASSCODE_HTTP_HEADER) .map(s -> s.replace("Bearer ", "")) .map(configuredPasscode::equals) .orElse(false); } }
1,787
32.111111
113
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/CompatibilityRealm.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; import org.sonar.api.security.LoginPasswordAuthenticator; import org.sonar.api.security.SecurityRealm; /** * Provides backward compatibility for {@link org.sonar.api.CoreProperties#CORE_AUTHENTICATOR_CLASS}. * * @since 2.14 */ class CompatibilityRealm extends SecurityRealm { private final LoginPasswordAuthenticator authenticator; public CompatibilityRealm(LoginPasswordAuthenticator authenticator) { this.authenticator = authenticator; } @Override public void init() { authenticator.init(); } @Override public String getName() { return "CompatibilityRealm[" + authenticator.getClass().getName() + "]"; } @Override public LoginPasswordAuthenticator getLoginPasswordAuthenticator() { return authenticator; } }
1,634
30.442308
101
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/DoPrivileged.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; import java.util.Collection; import java.util.Collections; import java.util.Optional; import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; /** * Allow code to be executed with the highest privileges possible, as if executed by a {@link GlobalPermission#ADMINISTER} account. * @since 4.3 */ public final class DoPrivileged { private DoPrivileged() { // Only static stuff } /** * Executes the task's <code>{@link Task#doPrivileged() doPrivileged}</code> method in a privileged environment. * @param task */ public static void execute(Task task) { try { task.start(); task.doPrivileged(); } finally { task.stop(); } } /** * Define a task that will be executed using the highest privileges available. The privileged section is restricted * to the execution of the {@link #doPrivileged()} method. */ public abstract static class Task { private final ThreadLocalUserSession threadLocalUserSession; private UserSession oldUserSession; protected Task(ThreadLocalUserSession threadLocalUserSession) { this.threadLocalUserSession = threadLocalUserSession; } /** * Code placed in this method will be executed in a privileged environment. */ protected abstract void doPrivileged(); private static class PrivilegedUserSession extends AbstractUserSession { @Override public String getLogin() { return null; } @Override public String getUuid() { return null; } @Override public String getName() { return null; } @Override public Collection<GroupDto> getGroups() { return Collections.emptyList(); } @Override public boolean shouldResetPassword() { return false; } @Override public boolean isLoggedIn() { return false; } @Override public Optional<IdentityProvider> getIdentityProvider() { return Optional.empty(); } @Override public Optional<ExternalIdentity> getExternalIdentity() { return Optional.empty(); } @Override protected boolean hasPermissionImpl(GlobalPermission permission) { return true; } @Override public boolean hasComponentPermission(String permission, ComponentDto component) { return true; } @Override protected Optional<String> componentUuidToEntityUuid(String componentUuid) { // always root return Optional.of(componentUuid); } @Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { return true; } @Override protected boolean hasChildProjectsPermission(String permission, String applicationUuid) { return true; } @Override protected boolean hasPortfolioChildProjectsPermission(String permission, String applicationUuid) { return true; } @Override public boolean isSystemAdministrator() { return true; } @Override public boolean isActive() { return true; } } private void start() { oldUserSession = threadLocalUserSession.hasSession() ? threadLocalUserSession.get() : null; threadLocalUserSession.set(new PrivilegedUserSession()); } private void stop() { threadLocalUserSession.unload(); if (oldUserSession != null) { threadLocalUserSession.set(oldUserSession); } } } }
4,483
26.012048
131
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ExternalIdentity.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; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public class ExternalIdentity { public static final String SQ_AUTHORITY = "sonarqube"; private String provider; private String login; private String id; public ExternalIdentity(String provider, String login, @Nullable String id) { this.provider = requireNonNull(provider, "Identity provider cannot be null"); this.login = requireNonNull(login, "Identity login cannot be null"); this.id = id == null ? login : id; } public String getProvider() { return provider; } public String getLogin() { return login; } public String getId() { return id; } }
1,559
29
81
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/GithubWebhookUserSession.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; import java.util.Collection; import java.util.Optional; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import static java.util.Collections.emptySet; public class GithubWebhookUserSession extends AbstractUserSession { public static final String GITHUB_WEBHOOK_USER_NAME = "github-webhook"; @Override public String getLogin() { return GITHUB_WEBHOOK_USER_NAME; } @Override public String getUuid() { throw new IllegalStateException("GithubWebhookUserSession does not contain a uuid."); } @Override public String getName() { return GITHUB_WEBHOOK_USER_NAME; } @Override public Collection<GroupDto> getGroups() { return emptySet(); } @Override public boolean shouldResetPassword() { return false; } @Override public Optional<IdentityProvider> getIdentityProvider() { return Optional.empty(); } @Override public Optional<ExternalIdentity> getExternalIdentity() { return Optional.empty(); } @Override public boolean isLoggedIn() { return true; } @Override public boolean isSystemAdministrator() { return false; } @Override public boolean isActive() { return true; } @Override protected boolean hasPermissionImpl(GlobalPermission permission) { return false; } @Override protected Optional<String> componentUuidToEntityUuid(String componentUuid) { return Optional.empty(); } @Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { return false; } @Override protected boolean hasChildProjectsPermission(String permission, String applicationUuid) { return false; } @Override protected boolean hasPortfolioChildProjectsPermission(String permission, String portfolioUuid) { return false; } @Override public boolean hasComponentUuidPermission(String permission, String componentUuid) { return true; } }
2,819
23.736842
98
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/NewUser.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; import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkState; public class NewUser { private String login; private String password; private String name; private String email; private List<String> scmAccounts; private ExternalIdentity externalIdentity; private NewUser(Builder builder) { this.login = builder.login; this.password = builder.password; this.name = builder.name; this.email = builder.email; this.scmAccounts = builder.scmAccounts; this.externalIdentity = builder.externalIdentity; } @CheckForNull public String login() { return login; } public String name() { return name; } @CheckForNull public String email() { return email; } public NewUser setEmail(@Nullable String email) { this.email = email; return this; } public List<String> scmAccounts() { return scmAccounts; } public NewUser setScmAccounts(List<String> scmAccounts) { this.scmAccounts = scmAccounts; return this; } @Nullable public String password() { return password; } public NewUser setPassword(@Nullable String password) { this.password = password; return this; } @Nullable public ExternalIdentity externalIdentity() { return externalIdentity; } public NewUser setExternalIdentity(@Nullable ExternalIdentity externalIdentity) { this.externalIdentity = externalIdentity; return this; } public static Builder builder() { return new Builder(); } public static class Builder { private String login; private String name; private String email; private List<String> scmAccounts = new ArrayList<>(); private String password; private ExternalIdentity externalIdentity; public Builder setLogin(@Nullable String login) { this.login = login; 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 setPassword(@Nullable String password) { this.password = password; return this; } public Builder setExternalIdentity(@Nullable ExternalIdentity externalIdentity) { this.externalIdentity = externalIdentity; return this; } public NewUser build() { checkState(externalIdentity == null || password == null, "Password should not be set with an external identity"); return new NewUser(this); } } }
3,633
24.412587
119
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/NewUserNotifier.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; import org.slf4j.Logger; import org.sonar.api.server.ServerSide; import org.sonar.api.platform.NewUserHandler; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * @since 3.2 */ @ServerSide public class NewUserNotifier { private static final Logger LOG = LoggerFactory.getLogger(NewUserNotifier.class); private final NewUserHandler[] handlers; @Autowired(required = false) public NewUserNotifier(NewUserHandler[] handlers) { this.handlers = handlers; } @Autowired(required = false) public NewUserNotifier() { this(new NewUserHandler[0]); } public void onNewUser(NewUserHandler.Context context) { LOG.debug("User created: {}. Notifying {} handlers...",context.getLogin(), NewUserHandler.class.getSimpleName() ); for (NewUserHandler handler : handlers) { handler.doOnNewUser(context); } } }
1,765
31.703704
118
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SecurityRealmFactory.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; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.CoreProperties; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.security.LoginPasswordAuthenticator; import org.sonar.api.security.SecurityRealm; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.SonarException; import org.springframework.beans.factory.annotation.Autowired; import static org.sonar.process.ProcessProperties.Property.SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE; import static org.sonar.process.ProcessProperties.Property.SONAR_SECURITY_REALM; /** * @since 2.14 */ @ServerSide public class SecurityRealmFactory implements Startable { private static final Logger LOG = LoggerFactory.getLogger("org.sonar.INFO"); private static final String LDAP_SECURITY_REALM = "LDAP"; private final boolean ignoreStartupFailure; private final SecurityRealm realm; @Autowired(required = false) public SecurityRealmFactory(Configuration config, SecurityRealm[] realms, LoginPasswordAuthenticator[] authenticators) { ignoreStartupFailure = config.getBoolean(SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey()).orElse(false); String realmName = config.get(SONAR_SECURITY_REALM.getKey()).orElse(null); String className = config.get(CoreProperties.CORE_AUTHENTICATOR_CLASS).orElse(null); if (LDAP_SECURITY_REALM.equals(realmName)) { realm = null; return; } SecurityRealm selectedRealm = null; if (!StringUtils.isEmpty(realmName)) { selectedRealm = selectRealm(realms, realmName); if (selectedRealm == null) { throw new SonarException(String.format( "Realm '%s' not found. Please check the property '%s' in conf/sonar.properties", realmName, SONAR_SECURITY_REALM.getKey())); } } if (selectedRealm == null && !StringUtils.isEmpty(className)) { LoginPasswordAuthenticator authenticator = selectAuthenticator(authenticators, className); if (authenticator == null) { throw new SonarException(String.format( "Authenticator '%s' not found. Please check the property '%s' in conf/sonar.properties", className, CoreProperties.CORE_AUTHENTICATOR_CLASS)); } selectedRealm = new CompatibilityRealm(authenticator); } realm = selectedRealm; } @Autowired(required = false) public SecurityRealmFactory(Configuration config, LoginPasswordAuthenticator[] authenticators) { this(config, new SecurityRealm[0], authenticators); } @Autowired(required = false) public SecurityRealmFactory(Configuration config, SecurityRealm[] realms) { this(config, realms, new LoginPasswordAuthenticator[0]); } @Autowired(required = false) public SecurityRealmFactory(Configuration config) { this(config, new SecurityRealm[0], new LoginPasswordAuthenticator[0]); } @Override public void start() { if (realm != null) { try { LOG.info("Security realm: {}", realm.getName()); realm.init(); LOG.info("Security realm started"); } catch (RuntimeException e) { if (ignoreStartupFailure) { LOG.error("IGNORED - Security realm fails to start: {}", e.getMessage()); } else { throw new SonarException("Security realm fails to start: " + e.getMessage(), e); } } } } @Override public void stop() { // nothing } @Nullable public SecurityRealm getRealm() { return realm; } public boolean hasExternalAuthentication() { return getRealm() != null; } private static SecurityRealm selectRealm(SecurityRealm[] realms, String realmName) { for (SecurityRealm realm : realms) { if (StringUtils.equals(realmName, realm.getName())) { return realm; } } return null; } private static LoginPasswordAuthenticator selectAuthenticator(LoginPasswordAuthenticator[] authenticators, String className) { for (LoginPasswordAuthenticator lpa : authenticators) { if (lpa.getClass().getName().equals(className)) { return lpa; } } return null; } }
5,056
33.875862
152
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ServerUserSession.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; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; 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.resources.Qualifiers; import org.sonar.api.resources.Scopes; 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.ComponentTreeQuery; import org.sonar.db.component.ComponentTreeQuery.Strategy; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import static java.util.Collections.singleton; import static java.util.Optional.of; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toSet; import static org.sonar.api.resources.Qualifiers.SUBVIEW; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS; /** * Implementation of {@link UserSession} used in web server */ public class ServerUserSession extends AbstractUserSession { private static final Set<String> QUALIFIERS = Set.of(VIEW, SUBVIEW); @CheckForNull private final UserDto userDto; private final DbClient dbClient; private final Map<String, String> entityUuidByComponentUuid = new HashMap<>(); private final Map<String, Set<String>> permissionsByEntityUuid = new HashMap<>(); private Collection<GroupDto> groups; private Boolean isSystemAdministrator; private Set<GlobalPermission> permissions; public ServerUserSession(DbClient dbClient, @Nullable UserDto userDto) { this.dbClient = dbClient; this.userDto = userDto; } private Collection<GroupDto> loadGroups() { if (this.userDto == null) { return Collections.emptyList(); } try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.groupDao().selectByUserLogin(dbSession, userDto.getLogin()); } } @Override @CheckForNull public Long getLastSonarlintConnectionDate() { return userDto == null ? null : userDto.getLastSonarlintConnectionDate(); } @Override @CheckForNull public String getLogin() { return userDto == null ? null : userDto.getLogin(); } @Override @CheckForNull public String getUuid() { return userDto == null ? null : userDto.getUuid(); } @Override @CheckForNull public String getName() { return userDto == null ? null : userDto.getName(); } @Override public Collection<GroupDto> getGroups() { if (groups == null) { groups = loadGroups(); } return groups; } @Override public boolean shouldResetPassword() { return userDto != null && userDto.isResetPassword(); } @Override public boolean isLoggedIn() { return userDto != null; } @Override public Optional<IdentityProvider> getIdentityProvider() { return ofNullable(userDto).map(d -> computeIdentity(d).getIdentityProvider()); } @Override public Optional<ExternalIdentity> getExternalIdentity() { return ofNullable(userDto).map(d -> computeIdentity(d).getExternalIdentity()); } @Override protected boolean hasPermissionImpl(GlobalPermission permission) { if (permissions == null) { permissions = loadGlobalPermissions(); } return permissions.contains(permission); } @Override protected Optional<String> componentUuidToEntityUuid(String componentUuid) { String entityUuid = entityUuidByComponentUuid.get(componentUuid); if (entityUuid != null) { return of(entityUuid); } try (DbSession dbSession = dbClient.openSession(false)) { Optional<ComponentDto> component = dbClient.componentDao().selectByUuid(dbSession, componentUuid); if (component.isEmpty()) { return Optional.empty(); } // permissions must be checked on the project entityUuid = getEntityUuid(dbSession, component.get()); entityUuidByComponentUuid.put(componentUuid, entityUuid); return of(entityUuid); } } @Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { return hasPermission(permission, entityUuid); } @Override protected boolean hasChildProjectsPermission(String permission, String applicationUuid) { Set<String> childProjectUuids = loadChildProjectUuids(applicationUuid); Set<String> projectsWithPermission = keepEntitiesUuidsByPermission(permission, childProjectUuids); return projectsWithPermission.containsAll(childProjectUuids); } @Override protected boolean hasPortfolioChildProjectsPermission(String permission, String portfolioUuid) { Set<ComponentDto> portfolioHierarchyComponents = resolvePortfolioHierarchyComponents(portfolioUuid); Set<String> branchUuids = findBranchUuids(portfolioHierarchyComponents); Set<String> projectUuids = findProjectUuids(branchUuids); Set<String> projectsWithPermission = keepEntitiesUuidsByPermission(permission, projectUuids); return projectsWithPermission.containsAll(projectUuids); } @Override public <T extends EntityDto> List<T> keepAuthorizedEntities(String permission, Collection<T> entities) { Set<String> projectsUuids = entities.stream().map(EntityDto::getUuid).collect(Collectors.toSet()); // TODO in SONAR-19445 Set<String> authorizedEntitiesUuids = keepEntitiesUuidsByPermission(permission, projectsUuids); return entities.stream() .filter(project -> authorizedEntitiesUuids.contains(project.getUuid())) .toList(); } private Set<String> keepEntitiesUuidsByPermission(String permission, Collection<String> entityUuids) { try (DbSession dbSession = dbClient.openSession(false)) { String userUuid = userDto == null ? null : userDto.getUuid(); return dbClient.authorizationDao().keepAuthorizedEntityUuids(dbSession, entityUuids, userUuid, permission); } } private static Set<String> findBranchUuids(Set<ComponentDto> portfolioHierarchyComponents) { return portfolioHierarchyComponents.stream() .map(ComponentDto::getCopyComponentUuid) .collect(toSet()); } private Set<String> findProjectUuids(Set<String> branchesComponentsUuid) { try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, branchesComponentsUuid); return getProjectUuids(dbSession, componentDtos); } } private String getEntityUuid(DbSession dbSession, ComponentDto componentDto) { // Portfolio & subPortfolio don't have branch, so branchUuid represents the portfolio uuid. // technical project store root portfolio uuid in branchUuid if (isPortfolioOrSubPortfolio(componentDto) || isTechnicalProject(componentDto)) { return componentDto.branchUuid(); } Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, componentDto.branchUuid()); return branchDto.map(BranchDto::getProjectUuid).orElseThrow(() -> new IllegalStateException("No branch found for component : " + componentDto)); } private Set<String> getProjectUuids(DbSession dbSession, Collection<ComponentDto> components) { Set<String> mainProjectUuids = new HashSet<>(); // the result of following stream could be project or application Collection<String> componentsWithBranch = components.stream() .filter(c -> !(isTechnicalProject(c) || isPortfolioOrSubPortfolio(c))) .map(ComponentDto::branchUuid) .toList(); dbClient.branchDao().selectByUuids(dbSession, componentsWithBranch).stream() .map(BranchDto::getProjectUuid).forEach(mainProjectUuids::add); components.stream() .filter(c -> isTechnicalProject(c) || isPortfolioOrSubPortfolio(c)) .map(ComponentDto::branchUuid) .forEach(mainProjectUuids::add); return mainProjectUuids; } private static boolean isTechnicalProject(ComponentDto componentDto) { return Qualifiers.PROJECT.equals(componentDto.qualifier()) && Scopes.FILE.equals(componentDto.scope()); } private static boolean isPortfolioOrSubPortfolio(ComponentDto componentDto) { return !Objects.isNull(componentDto.qualifier()) && QUALIFIERS.contains(componentDto.qualifier()); } private boolean hasPermission(String permission, String entityUuid) { Set<String> entityPermissions = permissionsByEntityUuid.computeIfAbsent(entityUuid, this::loadEntityPermissions); return entityPermissions.contains(permission); } private Set<String> loadEntityPermissions(String entityUuid) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<EntityDto> entity = dbClient.entityDao().selectByUuid(dbSession, entityUuid); if (entity.isEmpty()) { return Collections.emptySet(); } if (entity.get().isPrivate()) { return loadDbPermissions(dbSession, entityUuid); } Set<String> projectPermissions = new HashSet<>(); projectPermissions.addAll(PUBLIC_PERMISSIONS); projectPermissions.addAll(loadDbPermissions(dbSession, entityUuid)); return Collections.unmodifiableSet(projectPermissions); } } private Set<String> loadChildProjectUuids(String applicationUuid) { try (DbSession dbSession = dbClient.openSession(false)) { BranchDto branchDto = dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, applicationUuid) .orElseThrow(); Set<String> projectBranchesUuid = dbClient.componentDao() .selectDescendants(dbSession, ComponentTreeQuery.builder() .setBaseUuid(branchDto.getUuid()) .setQualifiers(singleton(Qualifiers.PROJECT)) .setScopes(singleton(Scopes.FILE)) .setStrategy(Strategy.CHILDREN).build()) .stream() .map(ComponentDto::getCopyComponentUuid) .collect(toSet()); return dbClient.branchDao().selectByUuids(dbSession, projectBranchesUuid).stream() .map(BranchDto::getProjectUuid) .collect(toSet()); } } private List<ComponentDto> getDirectChildComponents(String portfolioUuid) { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.componentDao().selectDescendants(dbSession, ComponentTreeQuery.builder() .setBaseUuid(portfolioUuid) .setQualifiers(Arrays.asList(Qualifiers.PROJECT, Qualifiers.SUBVIEW)) .setStrategy(Strategy.CHILDREN).build()); } } private Set<ComponentDto> resolvePortfolioHierarchyComponents(String parentComponentUuid) { Set<ComponentDto> portfolioHierarchyProjects = new HashSet<>(); resolvePortfolioHierarchyComponents(parentComponentUuid, portfolioHierarchyProjects); return portfolioHierarchyProjects; } private void resolvePortfolioHierarchyComponents(String parentComponentUuid, Set<ComponentDto> hierarchyChildComponents) { List<ComponentDto> childComponents = getDirectChildComponents(parentComponentUuid); if (childComponents.isEmpty()) { return; } childComponents.forEach(c -> { if (c.getCopyComponentUuid() != null) { hierarchyChildComponents.add(c); } if (Qualifiers.SUBVIEW.equals(c.qualifier())) { resolvePortfolioHierarchyComponents(c.uuid(), hierarchyChildComponents); } }); } private Set<GlobalPermission> loadGlobalPermissions() { Set<String> permissionKeys; try (DbSession dbSession = dbClient.openSession(false)) { if (userDto != null && userDto.getUuid() != null) { permissionKeys = dbClient.authorizationDao().selectGlobalPermissions(dbSession, userDto.getUuid()); } else { permissionKeys = dbClient.authorizationDao().selectGlobalPermissionsOfAnonymous(dbSession); } } return permissionKeys.stream() .map(GlobalPermission::fromKey) .collect(toSet()); } private Set<String> loadDbPermissions(DbSession dbSession, String entityUuid) { if (userDto != null && userDto.getUuid() != null) { return dbClient.authorizationDao().selectEntityPermissions(dbSession, entityUuid, userDto.getUuid()); } return dbClient.authorizationDao().selectEntityPermissionsOfAnonymous(dbSession, entityUuid); } @Override protected List<ComponentDto> doKeepAuthorizedComponents(String permission, Collection<ComponentDto> components) { try (DbSession dbSession = dbClient.openSession(false)) { Set<String> projectUuids = getProjectUuids(dbSession, components); Map<String, ComponentDto> originalComponents = findComponentsByCopyComponentUuid(components, dbSession); Set<String> originalComponentsProjectUuids = getProjectUuids(dbSession, originalComponents.values()); Set<String> allProjectUuids = new HashSet<>(projectUuids); allProjectUuids.addAll(originalComponentsProjectUuids); Set<String> authorizedProjectUuids = dbClient.authorizationDao().keepAuthorizedEntityUuids(dbSession, allProjectUuids, getUuid(), permission); return components.stream() .filter(c -> { if (c.getCopyComponentUuid() != null) { var componentDto = originalComponents.get(c.getCopyComponentUuid()); return componentDto != null && authorizedProjectUuids.contains(getEntityUuid(dbSession, componentDto)); } return authorizedProjectUuids.contains(c.branchUuid()) || authorizedProjectUuids.contains( getEntityUuid(dbSession, c)); }) .toList(); } } private Map<String, ComponentDto> findComponentsByCopyComponentUuid(Collection<ComponentDto> components, DbSession dbSession) { Set<String> copyComponentsUuid = components.stream() .map(ComponentDto::getCopyComponentUuid) .filter(Objects::nonNull) .collect(toSet()); return dbClient.componentDao().selectByUuids(dbSession, copyComponentsUuid).stream() .collect(Collectors.toMap(ComponentDto::uuid, componentDto -> componentDto)); } @Override public boolean isSystemAdministrator() { if (isSystemAdministrator == null) { isSystemAdministrator = loadIsSystemAdministrator(); } return isSystemAdministrator; } @Override public boolean isActive() { return userDto.isActive(); } private boolean loadIsSystemAdministrator() { return hasPermission(GlobalPermission.ADMINISTER); } }
15,392
36.820639
148
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SystemPasscode.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; import javax.annotation.Nullable; import org.sonar.api.server.ws.Request; /** * Passcode for accessing some web services, usually for connecting * monitoring tools without using the credentials * of a system administrator. * * Important - the web services accepting passcode must be listed in * {@link org.sonar.server.authentication.UserSessionInitializer#URL_USING_PASSCODE}. */ public interface SystemPasscode { /** * Whether the system passcode is provided by the HTTP request or not. * Returns {@code false} if passcode is not configured or not valid. */ boolean isValid(Request request); /** * Check if the passcode passed as argument is valid. * Returns {@code false} if passcode is not configured or not valid. */ boolean isValidPasscode(@Nullable String passcode); }
1,688
34.1875
85
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SystemPasscodeImpl.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; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.api.server.ws.Request; import org.slf4j.LoggerFactory; import static org.sonar.process.ProcessProperties.Property.WEB_SYSTEM_PASS_CODE; @ServerSide public class SystemPasscodeImpl implements SystemPasscode, Startable { public static final String PASSCODE_HTTP_HEADER = "X-Sonar-Passcode"; private final Configuration configuration; private String configuredPasscode; public SystemPasscodeImpl(Configuration configuration) { this.configuration = configuration; } @Override public boolean isValid(Request request) { if (configuredPasscode == null) { return false; } return isValidPasscode(request.header(PASSCODE_HTTP_HEADER).orElse(null)); } @Override public boolean isValidPasscode(@Nullable String passcode) { return Optional.ofNullable(passcode) .map(s -> Objects.equals(configuredPasscode, s)) .orElse(false); } @Override public void start() { Optional<String> passcodeOpt = configuration.get(WEB_SYSTEM_PASS_CODE.getKey()) // if present, result is never empty string .map(StringUtils::trimToNull); if (passcodeOpt.isPresent()) { logState("enabled"); configuredPasscode = passcodeOpt.get(); } else { logState("disabled"); configuredPasscode = null; } } private void logState(String state) { LoggerFactory.getLogger(getClass()).info("System authentication by passcode is {}", state); } @Override public void stop() { // nothing to do } }
2,625
29.894118
95
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ThreadLocalUserSession.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; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.UnauthorizedException; /** * Part of the current HTTP session */ public class ThreadLocalUserSession implements UserSession { private static final ThreadLocal<UserSession> DELEGATE = new ThreadLocal<>(); public UserSession get() { UserSession session = DELEGATE.get(); if (session != null) { return session; } throw new UnauthorizedException("User is not authenticated"); } public void set(UserSession session) { DELEGATE.set(session); } public void unload() { DELEGATE.remove(); } public boolean hasSession() { return DELEGATE.get() != null; } @Override @CheckForNull public Long getLastSonarlintConnectionDate() { return get().getLastSonarlintConnectionDate(); } @Override @CheckForNull public String getLogin() { return get().getLogin(); } @Override @CheckForNull public String getUuid() { return get().getUuid(); } @Override @CheckForNull public String getName() { return get().getName(); } @Override public Collection<GroupDto> getGroups() { return get().getGroups(); } @Override public Optional<IdentityProvider> getIdentityProvider() { return get().getIdentityProvider(); } @Override public Optional<ExternalIdentity> getExternalIdentity() { return get().getExternalIdentity(); } @Override public boolean isLoggedIn() { return get().isLoggedIn(); } @Override public UserSession checkLoggedIn() { get().checkLoggedIn(); return this; } @Override public boolean shouldResetPassword() { return get().shouldResetPassword(); } @Override public boolean hasPermission(GlobalPermission permission) { return get().hasPermission(permission); } @Override public UserSession checkPermission(GlobalPermission permission) { get().checkPermission(permission); return this; } @Override public UserSession checkComponentPermission(String projectPermission, ComponentDto component) { get().checkComponentPermission(projectPermission, component); return this; } @Override public UserSession checkEntityPermission(String projectPermission, EntityDto entity) { get().checkEntityPermission(projectPermission, entity); return this; } @Override public UserSession checkChildProjectsPermission(String projectPermission, ComponentDto component) { get().checkChildProjectsPermission(projectPermission, component); return this; } @Override public UserSession checkChildProjectsPermission(String projectPermission, EntityDto application) { get().checkChildProjectsPermission(projectPermission, application); return this; } @Override public UserSession checkComponentUuidPermission(String permission, String componentUuid) { get().checkComponentUuidPermission(permission, componentUuid); return this; } @Override public boolean isSystemAdministrator() { return get().isSystemAdministrator(); } @Override public UserSession checkIsSystemAdministrator() { get().checkIsSystemAdministrator(); return this; } @Override public boolean isActive() { return get().isActive(); } @Override public boolean hasComponentPermission(String permission, ComponentDto component) { return get().hasComponentPermission(permission, component); } @Override public boolean hasEntityPermission(String permission, EntityDto entity) { return get().hasEntityPermission(permission, entity); } @Override public boolean hasEntityPermission(String permission, String entityUuid) { return get().hasEntityPermission(permission, entityUuid); } @Override public boolean hasChildProjectsPermission(String permission, ComponentDto component) { return get().hasChildProjectsPermission(permission, component); } @Override public boolean hasChildProjectsPermission(String permission, EntityDto application) { return get().hasChildProjectsPermission(permission, application); } @Override public boolean hasPortfolioChildProjectsPermission(String permission, ComponentDto portfolio) { return get().hasPortfolioChildProjectsPermission(permission, portfolio); } @Override public boolean hasComponentUuidPermission(String permission, String componentUuid) { return get().hasComponentUuidPermission(permission, componentUuid); } @Override public List<ComponentDto> keepAuthorizedComponents(String permission, Collection<ComponentDto> components) { return get().keepAuthorizedComponents(permission, components); } @Override public <T extends EntityDto> List<T> keepAuthorizedEntities(String permission, Collection<T> entities) { return get().keepAuthorizedEntities(permission, entities); } }
5,933
26.472222
110
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/TokenUserSession.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; import java.util.EnumSet; import java.util.Set; import org.sonar.db.DbClient; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.TokenType; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; public class TokenUserSession extends ServerUserSession { private static final String SCAN = "scan"; private static final Set<GlobalPermission> GLOBAL_ANALYSIS_TOKEN_SUPPORTED_PERMISSIONS = EnumSet.of(GlobalPermission.SCAN, GlobalPermission.PROVISION_PROJECTS); private final UserTokenDto userToken; public TokenUserSession(DbClient dbClient, UserDto user, UserTokenDto userToken) { super(dbClient, user); this.userToken = userToken; } @Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { TokenType tokenType = TokenType.valueOf(userToken.getType()); switch (tokenType) { case USER_TOKEN: return super.hasEntityUuidPermission(permission, entityUuid); case PROJECT_ANALYSIS_TOKEN: return SCAN.equals(permission) && entityUuid.equals(userToken.getProjectUuid()) && (super.hasEntityUuidPermission(SCAN, entityUuid) || super.hasPermissionImpl(GlobalPermission.SCAN)); case GLOBAL_ANALYSIS_TOKEN: //The case with a global analysis token has to return false always, since it is based on the assumption that the user // has global analysis privileges return false; default: throw new IllegalArgumentException("Unsupported token type " + tokenType.name()); } } @Override protected boolean hasPermissionImpl(GlobalPermission permission) { TokenType tokenType = TokenType.valueOf(userToken.getType()); switch (tokenType) { case USER_TOKEN: return super.hasPermissionImpl(permission); case PROJECT_ANALYSIS_TOKEN: //The case with a project analysis token has to return false always, delegating the result to the super class would allow //the project analysis token to work for multiple projects in case the user has Global Permissions. return false; case GLOBAL_ANALYSIS_TOKEN: return GLOBAL_ANALYSIS_TOKEN_SUPPORTED_PERMISSIONS.contains(permission) && super.hasPermissionImpl(permission); default: throw new IllegalArgumentException("Unsupported token type " + tokenType.name()); } } public UserTokenDto getUserToken() { return userToken; } }
3,326
39.573171
162
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/UpdateUser.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; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class UpdateUser { private String login; private String name; private String email; private List<String> scmAccounts; private String password; private ExternalIdentity externalIdentity; private boolean loginChanged; private boolean nameChanged; private boolean emailChanged; private boolean scmAccountsChanged; private boolean passwordChanged; private boolean externalIdentityChanged; @CheckForNull public String login() { return login; } public UpdateUser setLogin(@Nullable String login) { this.login = login; loginChanged = true; return this; } @CheckForNull public String name() { return name; } public UpdateUser setName(@Nullable String name) { this.name = name; nameChanged = true; return this; } @CheckForNull public String email() { return email; } public UpdateUser setEmail(@Nullable String email) { this.email = email; emailChanged = true; return this; } @CheckForNull public List<String> scmAccounts() { return scmAccounts; } public UpdateUser setScmAccounts(@Nullable List<String> scmAccounts) { this.scmAccounts = scmAccounts; scmAccountsChanged = true; return this; } @CheckForNull public String password() { return password; } public UpdateUser setPassword(@Nullable String password) { this.password = password; passwordChanged = true; return this; } @CheckForNull public ExternalIdentity externalIdentity() { return externalIdentity; } /** * This method should only be used when updating a none local user */ public UpdateUser setExternalIdentity(@Nullable ExternalIdentity externalIdentity) { this.externalIdentity = externalIdentity; externalIdentityChanged = true; return this; } public boolean isLoginChanged() { return loginChanged; } public boolean isNameChanged() { return nameChanged; } public boolean isEmailChanged() { return emailChanged; } public boolean isScmAccountsChanged() { return scmAccountsChanged; } public boolean isPasswordChanged() { return passwordChanged; } public boolean isExternalIdentityChanged() { return externalIdentityChanged; } }
3,218
22.669118
86
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/UserSession.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; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import static java.util.Objects.requireNonNull; public interface UserSession { /** * Login of the authenticated user. Returns {@code null} * if {@link #isLoggedIn()} is {@code false}. */ @CheckForNull String getLogin(); /** * Uuid of the authenticated user. Returns {@code null} * if {@link #isLoggedIn()} is {@code false}. */ @CheckForNull String getUuid(); /** * Name of the authenticated user. Returns {@code null} * if {@link #isLoggedIn()} is {@code false}. */ @CheckForNull String getName(); @CheckForNull Long getLastSonarlintConnectionDate(); /** * The groups that the logged-in user is member of. An empty * collection is returned if {@link #isLoggedIn()} is {@code false}. */ Collection<GroupDto> getGroups(); boolean shouldResetPassword(); /** * This enum supports by name only the few providers for which specific code exists. */ enum IdentityProvider { SONARQUBE("sonarqube"), GITHUB("github"), BITBUCKETCLOUD("bitbucket"), OTHER("other"); String key; IdentityProvider(String key) { this.key = key; } public String getKey() { return key; } public static IdentityProvider getFromKey(String key) { return Arrays.stream(IdentityProvider.values()) .filter(i -> i.getKey().equals(key)) .findAny() .orElse(OTHER); } } /** * @return empty if user is anonymous */ Optional<IdentityProvider> getIdentityProvider(); record ExternalIdentity(String id, String login) { public ExternalIdentity(String id, String login) { this.id = requireNonNull(id, "id can't be null"); this.login = requireNonNull(login, "login can't be null"); } @Override public String toString() { return "ExternalIdentity{" + "id='" + id + '\'' + ", login='" + login + '\'' + '}'; } } /** * @return empty if {@link #getIdentityProvider()} returns empty or {@link IdentityProvider#SONARQUBE} */ Optional<ExternalIdentity> getExternalIdentity(); /** * Whether the user is logged-in or anonymous. */ boolean isLoggedIn(); /** * Ensures that user is logged in otherwise throws {@link org.sonar.server.exceptions.UnauthorizedException}. */ UserSession checkLoggedIn(); /** * Returns {@code true} if the permission is granted, otherwise {@code false}. */ boolean hasPermission(GlobalPermission permission); /** * Ensures that {@link #hasPermission(GlobalPermission)} is {@code true}, * otherwise throws a {@link org.sonar.server.exceptions.ForbiddenException}. */ UserSession checkPermission(GlobalPermission permission); /** * Returns {@code true} if the permission is granted to user on the component, * otherwise {@code false}. * If the component does not exist, then returns {@code false}. * * @param component non-null component. * @param permission project permission as defined by {@link org.sonar.server.permission.PermissionService} */ boolean hasComponentPermission(String permission, ComponentDto component); boolean hasEntityPermission(String permission, EntityDto entity); boolean hasEntityPermission(String permission, String entityUuid); boolean hasChildProjectsPermission(String permission, ComponentDto component); boolean hasChildProjectsPermission(String permission, EntityDto application); boolean hasPortfolioChildProjectsPermission(String permission, ComponentDto component); /** * Using {@link #hasComponentPermission(String, ComponentDto)} is recommended * because it does not have to load project if the referenced component * is not a project. * * @deprecated use {@link #hasComponentPermission(String, ComponentDto)} instead */ @Deprecated boolean hasComponentUuidPermission(String permission, String componentUuid); /** * Return the subset of specified components which the user has granted permission. * An empty list is returned if input is empty or if no components are allowed to be * accessed. * If the input is ordered, then the returned components are in the same order. * The duplicated components are returned duplicated too. */ List<ComponentDto> keepAuthorizedComponents(String permission, Collection<ComponentDto> components); <T extends EntityDto> List<T> keepAuthorizedEntities(String permission, Collection<T> components); /** * Ensures that {@link #hasComponentPermission(String, ComponentDto)} is {@code true}, * otherwise throws a {@link org.sonar.server.exceptions.ForbiddenException}. */ UserSession checkComponentPermission(String projectPermission, ComponentDto component); /** * Ensures that {@link #hasEntityPermission(String, EntityDto)} is {@code true}, * otherwise throws a {@link org.sonar.server.exceptions.ForbiddenException}. */ UserSession checkEntityPermission(String projectPermission, EntityDto entity); /** * Ensures that {@link #hasChildProjectsPermission(String, ComponentDto)} is {@code true} * otherwise throws a {@link org.sonar.server.exceptions.ForbiddenException}. */ UserSession checkChildProjectsPermission(String projectPermission, ComponentDto project); /** * Ensures that {@link #hasChildProjectsPermission(String, EntityDto)} is {@code true} * otherwise throws a {@link org.sonar.server.exceptions.ForbiddenException}. */ UserSession checkChildProjectsPermission(String projectPermission, EntityDto application); /** * Ensures that {@link #hasComponentUuidPermission(String, String)} is {@code true}, * otherwise throws a {@link org.sonar.server.exceptions.ForbiddenException}. * * @deprecated use {@link #checkComponentPermission(String, ComponentDto)} instead */ @Deprecated UserSession checkComponentUuidPermission(String permission, String componentUuid); /** * Whether user can administrate system, for example for using cross-organizations services * like update center, system info or management of users. * Returns {@code true} if: * <ul> * <li>user is administrator</li> * </ul> */ boolean isSystemAdministrator(); /** * Ensures that {@link #isSystemAdministrator()} is {@code true}, * otherwise throws {@link org.sonar.server.exceptions.ForbiddenException}. */ UserSession checkIsSystemAdministrator(); boolean isActive(); }
7,579
31.813853
111
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/UserSessionFactory.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; import org.sonar.api.server.ServerSide; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; @ServerSide public interface UserSessionFactory { UserSession create(UserDto user); UserSession create(UserDto user, UserTokenDto userToken); GithubWebhookUserSession createGithubWebhookUserSession(); UserSession createAnonymous(); }
1,236
31.552632
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/UserSessionFactoryImpl.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; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; import org.sonar.server.authentication.UserLastConnectionDatesUpdater; import static java.util.Objects.requireNonNull; @ServerSide public class UserSessionFactoryImpl implements UserSessionFactory { private final DbClient dbClient; private final UserLastConnectionDatesUpdater userLastConnectionDatesUpdater; public UserSessionFactoryImpl(DbClient dbClient, UserLastConnectionDatesUpdater userLastConnectionDatesUpdater) { this.dbClient = dbClient; this.userLastConnectionDatesUpdater = userLastConnectionDatesUpdater; } @Override public ServerUserSession create(UserDto user) { requireNonNull(user, "UserDto must not be null"); userLastConnectionDatesUpdater.updateLastConnectionDateIfNeeded(user); return new ServerUserSession(dbClient, user); } @Override public TokenUserSession create(UserDto user, UserTokenDto userToken) { requireNonNull(user, "UserDto must not be null"); requireNonNull(userToken, "UserTokenDto must not be null"); userLastConnectionDatesUpdater.updateLastConnectionDateIfNeeded(user); return new TokenUserSession(dbClient, user, userToken); } @Override public GithubWebhookUserSession createGithubWebhookUserSession() { return new GithubWebhookUserSession(); } @Override public ServerUserSession createAnonymous() { return new ServerUserSession(dbClient, null); } }
2,393
35.272727
115
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/UserUpdater.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; import com.google.common.base.Joiner; import com.google.common.base.Strings; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.regex.Pattern; import javax.annotation.Nullable; import javax.inject.Inject; import org.apache.commons.lang.math.RandomUtils; import org.sonar.api.config.Configuration; import org.sonar.api.platform.NewUserHandler; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.SecretNewValue; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserGroupDto; import org.sonar.server.authentication.CredentialsLocalAuthentication; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.util.Validation; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.Lists.newArrayList; import static java.lang.String.format; import static java.util.Collections.emptyList; import static org.sonar.api.CoreProperties.DEFAULT_ISSUE_ASSIGNEE; import static org.sonar.core.util.Slug.slugify; import static org.sonar.server.exceptions.BadRequestException.checkRequest; @ServerSide public class UserUpdater { private static final String SQ_AUTHORITY = "sonarqube"; private static final String LOGIN_PARAM = "Login"; private static final String PASSWORD_PARAM = "Password"; private static final String NAME_PARAM = "Name"; private static final String EMAIL_PARAM = "Email"; private static final Pattern START_WITH_SPECIFIC_AUTHORIZED_CHARACTERS = Pattern.compile("\\w+"); private static final Pattern CONTAINS_ONLY_AUTHORIZED_CHARACTERS = Pattern.compile("\\A\\w[\\w\\.\\-@]+\\z"); public static final int LOGIN_MIN_LENGTH = 2; public static final int LOGIN_MAX_LENGTH = 255; public static final int EMAIL_MAX_LENGTH = 100; public static final int NAME_MAX_LENGTH = 200; private final NewUserNotifier newUserNotifier; private final DbClient dbClient; private final DefaultGroupFinder defaultGroupFinder; private final AuditPersister auditPersister; private final CredentialsLocalAuthentication localAuthentication; @Inject public UserUpdater(NewUserNotifier newUserNotifier, DbClient dbClient, DefaultGroupFinder defaultGroupFinder, Configuration config, AuditPersister auditPersister, CredentialsLocalAuthentication localAuthentication) { this.newUserNotifier = newUserNotifier; this.dbClient = dbClient; this.defaultGroupFinder = defaultGroupFinder; this.auditPersister = auditPersister; this.localAuthentication = localAuthentication; } public UserDto createAndCommit(DbSession dbSession, NewUser newUser, Consumer<UserDto> beforeCommit, UserDto... otherUsersToIndex) { UserDto userDto = saveUser(dbSession, createDto(dbSession, newUser)); return commitUser(dbSession, userDto, beforeCommit, otherUsersToIndex); } public UserDto reactivateAndCommit(DbSession dbSession, UserDto disabledUser, NewUser newUser, Consumer<UserDto> beforeCommit, UserDto... otherUsersToIndex) { checkArgument(!disabledUser.isActive(), "An active user with login '%s' already exists", disabledUser.getLogin()); reactivateUser(dbSession, disabledUser, newUser); return commitUser(dbSession, disabledUser, beforeCommit, otherUsersToIndex); } private void reactivateUser(DbSession dbSession, UserDto reactivatedUser, NewUser newUser) { UpdateUser updateUser = new UpdateUser() .setName(newUser.name()) .setEmail(newUser.email()) .setScmAccounts(newUser.scmAccounts()) .setExternalIdentity(newUser.externalIdentity()); String login = newUser.login(); if (login != null) { updateUser.setLogin(login); } String password = newUser.password(); if (password != null) { updateUser.setPassword(password); } updateDto(dbSession, updateUser, reactivatedUser); updateUser(dbSession, reactivatedUser); addUserToDefaultGroup(dbSession, reactivatedUser); } public void updateAndCommit(DbSession dbSession, UserDto dto, UpdateUser updateUser, Consumer<UserDto> beforeCommit, UserDto... otherUsersToIndex) { boolean isUserUpdated = updateDto(dbSession, updateUser, dto); if (isUserUpdated) { // at least one change. Database must be updated and Elasticsearch re-indexed updateUser(dbSession, dto); commitUser(dbSession, dto, beforeCommit, otherUsersToIndex); } else { // no changes but still execute the consumer beforeCommit.accept(dto); dbSession.commit(); } } private UserDto commitUser(DbSession dbSession, UserDto userDto, Consumer<UserDto> beforeCommit, UserDto... otherUsersToIndex) { beforeCommit.accept(userDto); dbSession.commit(); notifyNewUser(userDto.getLogin(), userDto.getName(), userDto.getEmail()); return userDto; } private UserDto createDto(DbSession dbSession, NewUser newUser) { UserDto userDto = new UserDto(); List<String> messages = new ArrayList<>(); String login = newUser.login(); if (isNullOrEmpty(login)) { userDto.setLogin(generateUniqueLogin(dbSession, newUser.name())); } else if (validateLoginFormat(login, messages)) { checkLoginUniqueness(dbSession, login); userDto.setLogin(login); } String name = newUser.name(); if (validateNameFormat(name, messages)) { userDto.setName(name); } String email = newUser.email(); if (email != null && validateEmailFormat(email, messages)) { userDto.setEmail(email); } String password = newUser.password(); if (password != null && validatePasswords(password, messages)) { localAuthentication.storeHashPassword(userDto, password); } List<String> scmAccounts = sanitizeScmAccounts(newUser.scmAccounts()); if (scmAccounts != null && !scmAccounts.isEmpty() && validateScmAccounts(dbSession, scmAccounts, login, email, null, messages)) { userDto.setScmAccounts(scmAccounts); } setExternalIdentity(dbSession, userDto, newUser.externalIdentity()); checkRequest(messages.isEmpty(), messages); return userDto; } private String generateUniqueLogin(DbSession dbSession, String userName) { String slugName = slugify(userName); for (int i = 0; i < 10; i++) { String login = slugName + RandomUtils.nextInt(100_000); UserDto existingUser = dbClient.userDao().selectByLogin(dbSession, login); if (existingUser == null) { return login; } } throw new IllegalStateException("Cannot create unique login for user name " + userName); } private boolean updateDto(DbSession dbSession, UpdateUser update, UserDto dto) { List<String> messages = newArrayList(); boolean changed = updateLogin(dbSession, update, dto, messages); changed |= updateName(update, dto, messages); changed |= updateEmail(update, dto, messages); changed |= updateExternalIdentity(dbSession, update, dto); changed |= updatePassword(dbSession, update, dto, messages); changed |= updateScmAccounts(dbSession, update, dto, messages); checkRequest(messages.isEmpty(), messages); return changed; } private boolean updateLogin(DbSession dbSession, UpdateUser updateUser, UserDto userDto, List<String> messages) { String newLogin = updateUser.login(); if (!updateUser.isLoginChanged() || !validateLoginFormat(newLogin, messages) || Objects.equals(userDto.getLogin(), newLogin)) { return false; } checkLoginUniqueness(dbSession, newLogin); dbClient.propertiesDao().selectByKeyAndMatchingValue(dbSession, DEFAULT_ISSUE_ASSIGNEE, userDto.getLogin()) .forEach(p -> dbClient.propertiesDao().saveProperty(p.setValue(newLogin))); userDto.setLogin(newLogin); if (userDto.isLocal() || SQ_AUTHORITY.equals(userDto.getExternalIdentityProvider())) { userDto.setExternalLogin(newLogin); userDto.setExternalId(newLogin); } return true; } private static boolean updateName(UpdateUser updateUser, UserDto userDto, List<String> messages) { String name = updateUser.name(); if (updateUser.isNameChanged() && validateNameFormat(name, messages) && !Objects.equals(userDto.getName(), name)) { userDto.setName(name); return true; } return false; } private static boolean updateEmail(UpdateUser updateUser, UserDto userDto, List<String> messages) { String email = updateUser.email(); if (updateUser.isEmailChanged() && validateEmailFormat(email, messages) && !Objects.equals(userDto.getEmail(), email)) { userDto.setEmail(email); return true; } return false; } private boolean updateExternalIdentity(DbSession dbSession, UpdateUser updateUser, UserDto userDto) { ExternalIdentity externalIdentity = updateUser.externalIdentity(); if (updateUser.isExternalIdentityChanged() && !isSameExternalIdentity(userDto, externalIdentity)) { setExternalIdentity(dbSession, userDto, externalIdentity); return true; } return false; } private boolean updatePassword(DbSession dbSession, UpdateUser updateUser, UserDto userDto, List<String> messages) { String password = updateUser.password(); if (updateUser.isPasswordChanged() && validatePasswords(password, messages) && checkPasswordChangeAllowed(userDto, messages)) { localAuthentication.storeHashPassword(userDto, password); userDto.setResetPassword(false); auditPersister.updateUserPassword(dbSession, new SecretNewValue("userLogin", userDto.getLogin())); return true; } return false; } private boolean updateScmAccounts(DbSession dbSession, UpdateUser updateUser, UserDto userDto, List<String> messages) { String email = updateUser.email(); List<String> scmAccounts = sanitizeScmAccounts(updateUser.scmAccounts()); List<String> existingScmAccounts = userDto.getSortedScmAccounts(); if (updateUser.isScmAccountsChanged() && !(existingScmAccounts.containsAll(scmAccounts) && scmAccounts.containsAll(existingScmAccounts))) { if (!scmAccounts.isEmpty()) { String newOrOldEmail = email != null ? email : userDto.getEmail(); if (validateScmAccounts(dbSession, scmAccounts, userDto.getLogin(), newOrOldEmail, userDto, messages)) { userDto.setScmAccounts(scmAccounts); } } else { userDto.setScmAccounts(emptyList()); } return true; } return false; } private static boolean isSameExternalIdentity(UserDto dto, @Nullable ExternalIdentity externalIdentity) { return externalIdentity != null && !dto.isLocal() && Objects.equals(dto.getExternalId(), externalIdentity.getId()) && Objects.equals(dto.getExternalLogin(), externalIdentity.getLogin()) && Objects.equals(dto.getExternalIdentityProvider(), externalIdentity.getProvider()); } private void setExternalIdentity(DbSession dbSession, UserDto dto, @Nullable ExternalIdentity externalIdentity) { if (externalIdentity == null) { dto.setExternalLogin(dto.getLogin()); dto.setExternalIdentityProvider(SQ_AUTHORITY); dto.setExternalId(dto.getLogin()); dto.setLocal(true); } else { dto.setExternalLogin(externalIdentity.getLogin()); dto.setExternalIdentityProvider(externalIdentity.getProvider()); dto.setExternalId(externalIdentity.getId()); dto.setLocal(false); dto.setSalt(null); dto.setCryptedPassword(null); } UserDto existingUser = dbClient.userDao().selectByExternalIdAndIdentityProvider(dbSession, dto.getExternalId(), dto.getExternalIdentityProvider()); checkArgument(existingUser == null || Objects.equals(dto.getUuid(), existingUser.getUuid()), "A user with provider id '%s' and identity provider '%s' already exists", dto.getExternalId(), dto.getExternalIdentityProvider()); } private static boolean checkNotEmptyParam(@Nullable String value, String param, List<String> messages) { if (isNullOrEmpty(value)) { messages.add(format(Validation.CANT_BE_EMPTY_MESSAGE, param)); return false; } return true; } private static boolean validateLoginFormat(@Nullable String login, List<String> messages) { boolean isValid = checkNotEmptyParam(login, LOGIN_PARAM, messages); if (isValid) { if (login.length() < LOGIN_MIN_LENGTH) { messages.add(format(Validation.IS_TOO_SHORT_MESSAGE, LOGIN_PARAM, LOGIN_MIN_LENGTH)); return false; } else if (login.length() > LOGIN_MAX_LENGTH) { messages.add(format(Validation.IS_TOO_LONG_MESSAGE, LOGIN_PARAM, LOGIN_MAX_LENGTH)); return false; } else if (!startWithUnderscoreOrAlphanumeric(login)) { messages.add("Login should start with _ or alphanumeric."); return false; } else if (!CONTAINS_ONLY_AUTHORIZED_CHARACTERS.matcher(login).matches()) { messages.add("Login should contain only letters, numbers, and .-_@"); return false; } } return isValid; } private static boolean startWithUnderscoreOrAlphanumeric(String login) { String firstCharacter = login.substring(0, 1); if ("_".equals(firstCharacter)) { return true; } return START_WITH_SPECIFIC_AUTHORIZED_CHARACTERS.matcher(firstCharacter).matches(); } private static boolean validateNameFormat(@Nullable String name, List<String> messages) { boolean isValid = checkNotEmptyParam(name, NAME_PARAM, messages); if (name != null && name.length() > NAME_MAX_LENGTH) { messages.add(format(Validation.IS_TOO_LONG_MESSAGE, NAME_PARAM, 200)); return false; } return isValid; } private static boolean validateEmailFormat(@Nullable String email, List<String> messages) { if (email != null && email.length() > EMAIL_MAX_LENGTH) { messages.add(format(Validation.IS_TOO_LONG_MESSAGE, EMAIL_PARAM, 100)); return false; } return true; } private static boolean checkPasswordChangeAllowed(UserDto userDto, List<String> messages) { if (!userDto.isLocal()) { messages.add("Password cannot be changed when external authentication is used"); return false; } return true; } private static boolean validatePasswords(@Nullable String password, List<String> messages) { if (password == null || password.length() == 0) { messages.add(format(Validation.CANT_BE_EMPTY_MESSAGE, PASSWORD_PARAM)); return false; } return true; } private boolean validateScmAccounts(DbSession dbSession, List<String> scmAccounts, @Nullable String login, @Nullable String email, @Nullable UserDto existingUser, List<String> messages) { boolean isValid = true; for (String scmAccount : scmAccounts) { if (scmAccount.equals(login) || scmAccount.equals(email)) { messages.add("Login and email are automatically considered as SCM accounts"); isValid = false; } else { List<UserDto> matchingUsers = dbClient.userDao().selectByScmAccountOrLoginOrEmail(dbSession, scmAccount); List<String> matchingUsersWithoutExistingUser = newArrayList(); for (UserDto matchingUser : matchingUsers) { if (existingUser != null && matchingUser.getUuid().equals(existingUser.getUuid())) { continue; } matchingUsersWithoutExistingUser.add(getNameOrLogin(matchingUser) + " (" + matchingUser.getLogin() + ")"); } if (!matchingUsersWithoutExistingUser.isEmpty()) { messages.add(format("The scm account '%s' is already used by user(s) : '%s'", scmAccount, Joiner.on(", ").join(matchingUsersWithoutExistingUser))); isValid = false; } } } return isValid; } private static String getNameOrLogin(UserDto user) { String name = user.getName(); return name != null ? name : user.getLogin(); } private static List<String> sanitizeScmAccounts(@Nullable List<String> scmAccounts) { if (scmAccounts != null) { return new HashSet<>(scmAccounts).stream() .map(Strings::emptyToNull) .filter(Objects::nonNull) .sorted(String::compareToIgnoreCase) .toList(); } return emptyList(); } private void checkLoginUniqueness(DbSession dbSession, String login) { UserDto existingUser = dbClient.userDao().selectByLogin(dbSession, login); checkArgument(existingUser == null, "A user with login '%s' already exists", login); } private UserDto saveUser(DbSession dbSession, UserDto userDto) { userDto.setActive(true); UserDto res = dbClient.userDao().insert(dbSession, userDto); addUserToDefaultGroup(dbSession, userDto); return res; } private void updateUser(DbSession dbSession, UserDto dto) { dto.setActive(true); dbClient.userDao().update(dbSession, dto); } private void notifyNewUser(String login, String name, @Nullable String email) { newUserNotifier.onNewUser(NewUserHandler.Context.builder() .setLogin(login) .setName(name) .setEmail(email) .build()); } private static boolean isUserAlreadyMemberOfDefaultGroup(GroupDto defaultGroup, List<GroupDto> userGroups) { return userGroups.stream().anyMatch(group -> defaultGroup.getUuid().equals(group.getUuid())); } private void addUserToDefaultGroup(DbSession dbSession, UserDto userDto) { addDefaultGroup(dbSession, userDto); } private void addDefaultGroup(DbSession dbSession, UserDto userDto) { List<GroupDto> userGroups = dbClient.groupDao().selectByUserLogin(dbSession, userDto.getLogin()); GroupDto defaultGroup = defaultGroupFinder.findDefaultGroup(dbSession); if (isUserAlreadyMemberOfDefaultGroup(defaultGroup, userGroups)) { return; } dbClient.userGroupDao().insert(dbSession, new UserGroupDto().setUserUuid(userDto.getUuid()).setGroupUuid(defaultGroup.getUuid()), defaultGroup.getName(), userDto.getLogin()); } }
18,945
40.8234
164
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/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; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usergroups/DefaultGroupFinder.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; import org.sonar.api.security.DefaultGroups; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; public class DefaultGroupFinder { private final DbClient dbClient; public DefaultGroupFinder(DbClient dbClient) { this.dbClient = dbClient; } public GroupDto findDefaultGroup(DbSession dbSession) { return dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS) .orElseThrow(() -> new IllegalStateException("Default group cannot be found")); } }
1,405
33.292683
85
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usergroups/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; import javax.annotation.ParametersAreNonnullByDefault;
967
39.333333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/TokenGenerator.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; import org.sonar.db.user.TokenType; public interface TokenGenerator { /** * Generate a token. It must be unique and non deterministic.<br /> * Underlying algorithm, format and max length are * subject to change in subsequent SonarQube versions. * <br/> * Length does not exceed 40 characters (arbitrary value). * Token is composed of hexadecimal characters only (0-9, a-f) * <br/> * The token is sent through the userid field (login) of HTTP Basic authentication, * * Basic authentication is used to authenticate users from tokens, so the * constraints of userid field (login) must be respected. Basically the token * must not contain colon character ":". * */ String generate(TokenType tokenType); /** * Hash a token.<br/> * Underlying algorithm, format and max length are * subject to change in subsequent SonarQube versions. * <br /> * Length must not exceed 255 characters. * Hash is composed of hexadecimal characters only (0-9, a-f) */ String hash(String token); }
1,924
36.019231
85
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/TokenGeneratorImpl.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; import java.security.SecureRandom; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.sonar.db.user.TokenType; public class TokenGeneratorImpl implements TokenGenerator { private static final String SONARQUBE_TOKEN_PREFIX = "sq"; @Override public String generate(TokenType tokenType) { String rawToken = generateRawToken(); return buildIdentifiablePartOfToken(tokenType) + rawToken; } private static String buildIdentifiablePartOfToken(TokenType tokenType) { return SONARQUBE_TOKEN_PREFIX + tokenType.getIdentifier() + "_"; } private static String generateRawToken() { SecureRandom random = new SecureRandom(); byte[] randomBytes = new byte[20]; random.nextBytes(randomBytes); return Hex.encodeHexString(randomBytes); } @Override public String hash(String token) { return DigestUtils.sha384Hex(token); } }
1,802
33.018868
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/UserTokenAuthentication.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; import java.util.Optional; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.http.HttpRequest; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; import org.sonar.server.authentication.Credentials; import org.sonar.server.authentication.UserAuthResult; import org.sonar.server.authentication.UserLastConnectionDatesUpdater; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.exceptions.NotFoundException; import static org.apache.commons.lang.StringUtils.startsWithIgnoreCase; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.server.authentication.BasicAuthentication.extractCredentialsFromHeader; public class UserTokenAuthentication { private static final String ACCESS_LOG_TOKEN_NAME = "TOKEN_NAME"; private static final String BEARER_AUTHORIZATION_SCHEME = "bearer"; private static final String API_MONITORING_METRICS_PATH = "/api/monitoring/metrics"; private static final String AUTHORIZATION_HEADER = "Authorization"; private final TokenGenerator tokenGenerator; private final DbClient dbClient; private final UserLastConnectionDatesUpdater userLastConnectionDatesUpdater; private final AuthenticationEvent authenticationEvent; public UserTokenAuthentication(TokenGenerator tokenGenerator, DbClient dbClient, UserLastConnectionDatesUpdater userLastConnectionDatesUpdater, AuthenticationEvent authenticationEvent) { this.tokenGenerator = tokenGenerator; this.dbClient = dbClient; this.userLastConnectionDatesUpdater = userLastConnectionDatesUpdater; this.authenticationEvent = authenticationEvent; } public Optional<UserAuthResult> authenticate(HttpRequest request) { return findBearerToken(request) .or(() -> findTokenUsedWithBasicAuthentication(request)) .map(userAuthResult -> login(request, userAuthResult)); } private static Optional<String> findBearerToken(HttpRequest request) { // hack necessary as #org.sonar.server.monitoring.MetricsAction and org.sonar.server.platform.ws.SafeModeMonitoringMetricAction // are providing their own bearer token based authentication mechanism that we can't get rid of for backward compatibility reasons if (request.getServletPath().startsWith(API_MONITORING_METRICS_PATH)) { return Optional.empty(); } String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (startsWithIgnoreCase(authorizationHeader, BEARER_AUTHORIZATION_SCHEME)) { String token = StringUtils.removeStartIgnoreCase(authorizationHeader, BEARER_AUTHORIZATION_SCHEME + " "); return Optional.ofNullable(token); } return Optional.empty(); } private static Optional<String> findTokenUsedWithBasicAuthentication(HttpRequest request) { Credentials credentials = extractCredentialsFromHeader(request).orElse(null); if (isTokenWithBasicAuthenticationMethod(credentials)) { return Optional.ofNullable(credentials.getLogin()); } return Optional.empty(); } private static boolean isTokenWithBasicAuthenticationMethod(@Nullable Credentials credentials) { return Optional.ofNullable(credentials).map(c -> c.getPassword().isEmpty()).orElse(false); } private UserAuthResult login(HttpRequest request, String token) { UserAuthResult userAuthResult = authenticateFromUserToken(token, request); authenticationEvent.loginSuccess(request, userAuthResult.getUserDto().getLogin(), AuthenticationEvent.Source.local(AuthenticationEvent.Method.SONARQUBE_TOKEN)); return userAuthResult; } private UserAuthResult authenticateFromUserToken(String token, HttpRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { UserTokenDto userToken = authenticate(token); UserDto userDto = dbClient.userDao().selectByUuid(dbSession, userToken.getUserUuid()); if (userDto == null || !userDto.isActive()) { throw AuthenticationException.newBuilder() .setSource(AuthenticationEvent.Source.local(AuthenticationEvent.Method.SONARQUBE_TOKEN)) .setMessage("User doesn't exist") .build(); } request.setAttribute(ACCESS_LOG_TOKEN_NAME, userToken.getName()); return new UserAuthResult(userDto, userToken, UserAuthResult.AuthType.TOKEN); } catch (NotFoundException | IllegalStateException exception) { throw AuthenticationException.newBuilder() .setSource(AuthenticationEvent.Source.local(AuthenticationEvent.Method.SONARQUBE_TOKEN)) .setMessage(exception.getMessage()) .build(); } } private UserTokenDto authenticate(String token) { UserTokenDto userToken = getUserToken(token); if (userToken == null) { throw new NotFoundException("Token doesn't exist"); } if (userToken.isExpired()) { throw new IllegalStateException("The token expired on " + formatDateTime(userToken.getExpirationDate())); } userLastConnectionDatesUpdater.updateLastConnectionDateIfNeeded(userToken); return userToken; } @Nullable public UserTokenDto getUserToken(String token) { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.userTokenDao().selectByTokenHash(dbSession, tokenGenerator.hash(token)); } } }
6,326
45.182482
164
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/UserTokenModule.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; import org.sonar.core.platform.Module; import org.sonar.server.usertoken.notification.TokenExpirationEmailComposer; import org.sonar.server.usertoken.notification.TokenExpirationNotificationExecutorServiceImpl; import org.sonar.server.usertoken.notification.TokenExpirationNotificationInitializer; import org.sonar.server.usertoken.notification.TokenExpirationNotificationSchedulerImpl; import org.sonar.server.usertoken.notification.TokenExpirationNotificationSender; public class UserTokenModule extends Module { @Override protected void configureModule() { add( TokenExpirationEmailComposer.class, TokenExpirationNotificationSchedulerImpl.class, TokenExpirationNotificationExecutorServiceImpl.class, TokenExpirationNotificationInitializer.class, TokenExpirationNotificationSender.class, UserTokenAuthentication.class, TokenGeneratorImpl.class); } }
1,785
41.52381
94
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/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; import javax.annotation.ParametersAreNonnullByDefault;
967
37.72
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationEmail.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.notification; import java.util.Set; import org.sonar.db.user.UserTokenDto; import org.sonar.server.email.BasicEmail; public class TokenExpirationEmail extends BasicEmail { private final UserTokenDto userToken; public TokenExpirationEmail(String recipient, UserTokenDto userToken) { super(Set.of(recipient)); this.userToken = userToken; } public UserTokenDto getUserToken() { return userToken; } }
1,301
33.263158
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationEmailComposer.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.notification; import java.net.MalformedURLException; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.sonar.api.config.EmailSettings; import org.sonar.db.user.UserTokenDto; import org.sonar.server.email.EmailSender; import static java.lang.String.format; import static org.sonar.db.user.TokenType.PROJECT_ANALYSIS_TOKEN; public class TokenExpirationEmailComposer extends EmailSender<TokenExpirationEmail> { protected TokenExpirationEmailComposer(EmailSettings emailSettings) { super(emailSettings); } @Override protected void addReportContent(HtmlEmail email, TokenExpirationEmail emailData) throws EmailException, MalformedURLException { email.addTo(emailData.getRecipients().toArray(String[]::new)); UserTokenDto token = emailData.getUserToken(); if (token.isExpired()) { email.setSubject(format("Your token \"%s\" has expired.", token.getName())); } else { email.setSubject(format("Your token \"%s\" will expire.", token.getName())); } email.setHtmlMsg(composeEmailBody(token)); } private String composeEmailBody(UserTokenDto token) { StringBuilder builder = new StringBuilder(); if (token.isExpired()) { builder.append(format("Your token \"%s\" has expired.<br/><br/>", token.getName())); } else { builder.append(format("Your token \"%s\" will expire on %s.<br/><br/>", token.getName(), parseDate(token.getExpirationDate()))); } builder .append("Token Summary<br/><br/>") .append(format("Name: %s<br/>", token.getName())) .append(format("Type: %s<br/>", token.getType())); if (PROJECT_ANALYSIS_TOKEN.name().equals(token.getType())) { builder.append(format("Project: %s<br/>", token.getProjectName())); } builder.append(format("Created on: %s<br/>", parseDate(token.getCreatedAt()))); if (token.getLastConnectionDate() != null) { builder.append(format("Last used on: %s<br/>", parseDate(token.getLastConnectionDate()))); } builder.append(format("%s on: %s<br/>", token.isExpired() ? "Expired" : "Expires", parseDate(token.getExpirationDate()))) .append( format("<br/>If this token is still needed, please consider <a href=\"%s/account/security/\">generating</a> an equivalent.<br/><br/>", emailSettings.getServerBaseURL())) .append("Don't forget to update the token in the locations where it is in use. " + "This may include the CI pipeline that analyzes your projects, " + "the IDE settings that connect SonarLint to SonarQube, " + "and any places where you make calls to web services."); return builder.toString(); } private static String parseDate(long timestamp) { return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC).toLocalDate().format(DateTimeFormatter.ofPattern("MMMM dd, yyyy")); } }
3,834
44.654762
177
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationExecutorService.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.notification; import java.util.concurrent.ScheduledExecutorService; import org.sonar.api.server.ServerSide; @ServerSide public interface TokenExpirationNotificationExecutorService extends ScheduledExecutorService { }
1,097
38.214286
94
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationExecutorServiceImpl.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.notification; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl; public class TokenExpirationNotificationExecutorServiceImpl extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService> implements TokenExpirationNotificationExecutorService { public TokenExpirationNotificationExecutorServiceImpl() { super(Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("Token-expiration-notification-%d") .build())); } }
1,584
40.710526
81
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationInitializer.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.notification; import javax.annotation.Nullable; import org.sonar.api.platform.Server; import org.sonar.api.platform.ServerStartHandler; public class TokenExpirationNotificationInitializer implements ServerStartHandler { private final TokenExpirationNotificationScheduler scheduler; public TokenExpirationNotificationInitializer(@Nullable TokenExpirationNotificationScheduler scheduler) { this.scheduler = scheduler; } @Override public void onServerStart(Server server) { if (scheduler != null) { scheduler.startScheduling(); } } }
1,441
35.974359
107
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationScheduler.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.notification; import org.sonar.api.server.ServerSide; @ServerSide public interface TokenExpirationNotificationScheduler { void startScheduling(); }
1,030
35.821429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationSchedulerImpl.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.notification; import com.google.common.annotations.VisibleForTesting; import java.time.Duration; import java.time.LocalDateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.util.GlobalLockManager; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; public class TokenExpirationNotificationSchedulerImpl implements TokenExpirationNotificationScheduler { // Lock 23 hours in case of server restart or multiple nodes in data center edition private static int LOCK_DURATION = 23 * 60 * 60; private static String LOCK_NAME = "token-notif"; private static final Logger LOG = LoggerFactory.getLogger(TokenExpirationNotificationSchedulerImpl.class); private final TokenExpirationNotificationExecutorService executorService; private final GlobalLockManager lockManager; private final TokenExpirationNotificationSender notificationSender; public TokenExpirationNotificationSchedulerImpl(TokenExpirationNotificationExecutorService executorService, GlobalLockManager lockManager, TokenExpirationNotificationSender notificationSender) { this.executorService = executorService; this.lockManager = lockManager; this.notificationSender = notificationSender; } @Override public void startScheduling() { LocalDateTime now = LocalDateTime.now(); // schedule run at midnight everyday LocalDateTime nextRun = now.plusDays(1).withHour(0).withMinute(0).withSecond(0); long initialDelay = Duration.between(now, nextRun).getSeconds(); executorService.scheduleAtFixedRate(this::notifyTokenExpiration, initialDelay, DAYS.toSeconds(1), SECONDS); } @VisibleForTesting void notifyTokenExpiration() { try { // Avoid notification multiple times in case of data center edition if (!lockManager.tryLock(LOCK_NAME, LOCK_DURATION)) { return; } notificationSender.sendNotifications(); } catch (RuntimeException e) { LOG.error("Error in sending token expiration notification", e); } } }
2,938
40.394366
140
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationSender.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.notification; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; public class TokenExpirationNotificationSender { private static final Logger LOG = LoggerFactory.getLogger(TokenExpirationNotificationSender.class); private final DbClient dbClient; private final TokenExpirationEmailComposer emailComposer; public TokenExpirationNotificationSender(DbClient dbClient, TokenExpirationEmailComposer emailComposer) { this.dbClient = dbClient; this.emailComposer = emailComposer; } public void sendNotifications() { if (!emailComposer.areEmailSettingsSet()) { LOG.debug("Emails for token expiration notification have not been sent because email settings are not configured."); return; } try (var dbSession = dbClient.openSession(false)) { var expiringTokens = dbClient.userTokenDao().selectTokensExpiredInDays(dbSession, 7); var expiredTokens = dbClient.userTokenDao().selectTokensExpiredInDays(dbSession, 0); var tokensToNotify = Stream.concat(expiringTokens.stream(), expiredTokens.stream()).toList(); var usersToNotify = tokensToNotify.stream().map(UserTokenDto::getUserUuid).collect(Collectors.toSet()); Map<String, String> userUuidToEmail = dbClient.userDao().selectByUuids(dbSession, usersToNotify).stream() .collect(Collectors.toMap(UserDto::getUuid, UserDto::getEmail)); tokensToNotify.stream().map(token -> new TokenExpirationEmail(userUuidToEmail.get(token.getUserUuid()), token)).forEach(emailComposer::send); } } }
2,595
44.54386
147
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/usertoken/notification/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.notification; import javax.annotation.ParametersAreNonnullByDefault;
980
38.24
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/AuthenticationModuleTest.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; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class AuthenticationModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new AuthenticationModule().configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,281
35.628571
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/BaseContextFactoryTest.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; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.BaseIdentityProvider; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.db.user.UserDto; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.user.TestUserSessionFactory; import org.sonar.server.user.ThreadLocalUserSession; import org.sonar.server.user.UserSession; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class BaseContextFactoryTest { private static final String PUBLIC_ROOT_URL = "https://mydomain.com"; private static final UserIdentity USER_IDENTITY = UserIdentity.builder() .setProviderId("ABCD") .setProviderLogin("johndoo") .setName("John") .setEmail("john@email.com") .build(); private final ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class); private final TestUserRegistrar userIdentityAuthenticator = new TestUserRegistrar(); private final Server server = mock(Server.class); private final HttpServletRequest request = mock(HttpServletRequest.class); private final HttpServletResponse response = mock(HttpServletResponse.class); private final BaseIdentityProvider identityProvider = mock(BaseIdentityProvider.class); private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class); private final TestUserSessionFactory userSessionFactory = TestUserSessionFactory.standalone(); private final BaseContextFactory underTest = new BaseContextFactory(userIdentityAuthenticator, server, jwtHttpHandler, threadLocalUserSession, userSessionFactory); @Before public void setUp() { when(server.getPublicRootUrl()).thenReturn(PUBLIC_ROOT_URL); when(identityProvider.getName()).thenReturn("GitHub"); when(identityProvider.getKey()).thenReturn("github"); } @Test public void create_context() { JavaxHttpRequest httpRequest = new JavaxHttpRequest(request); JavaxHttpResponse httpResponse = new JavaxHttpResponse(response); BaseIdentityProvider.Context context = underTest.newContext(httpRequest, httpResponse, identityProvider); assertThat(context.getHttpRequest()).isEqualTo(httpRequest); assertThat(context.getHttpResponse()).isEqualTo(httpResponse); assertThat(context.getRequest()).isEqualTo(request); assertThat(context.getResponse()).isEqualTo(response); assertThat(context.getServerBaseURL()).isEqualTo(PUBLIC_ROOT_URL); } @Test public void authenticate() { JavaxHttpRequest httpRequest = new JavaxHttpRequest(request); JavaxHttpResponse httpResponse = new JavaxHttpResponse(response); BaseIdentityProvider.Context context = underTest.newContext(httpRequest, httpResponse, identityProvider); ArgumentCaptor<UserDto> userArgumentCaptor = ArgumentCaptor.forClass(UserDto.class); context.authenticate(USER_IDENTITY); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); verify(threadLocalUserSession).set(any(UserSession.class)); verify(jwtHttpHandler).generateToken(userArgumentCaptor.capture(), eq(httpRequest), eq(httpResponse)); assertThat(userArgumentCaptor.getValue().getExternalId()).isEqualTo(USER_IDENTITY.getProviderId()); assertThat(userArgumentCaptor.getValue().getExternalLogin()).isEqualTo(USER_IDENTITY.getProviderLogin()); assertThat(userArgumentCaptor.getValue().getExternalIdentityProvider()).isEqualTo("github"); } }
4,730
42.805556
165
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/BasicAuthenticationTest.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; import java.util.Base64; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.http.HttpRequest; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; import org.sonar.db.user.UserTokenDto; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.usertoken.UserTokenAuthentication; 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.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.SONARQUBE_TOKEN; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; public class BasicAuthenticationTest { private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); private static final String A_LOGIN = "login"; private static final String A_PASSWORD = "password"; private static final String CREDENTIALS_IN_BASE64 = toBase64(A_LOGIN + ":" + A_PASSWORD); private static final UserDto USER = UserTesting.newUserDto().setLogin(A_LOGIN); private static final String EXAMPLE_ENDPOINT = "/api/ce/submit"; private static final String AUTHORIZATION_HEADER = "Authorization"; @Rule public DbTester db = DbTester.create(); private final CredentialsAuthentication credentialsAuthentication = mock(CredentialsAuthentication.class); private final UserTokenAuthentication userTokenAuthentication = mock(UserTokenAuthentication.class); private final HttpRequest request = mock(HttpRequest.class); private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class); private final BasicAuthentication underTest = new BasicAuthentication(credentialsAuthentication, userTokenAuthentication); @Before public void before() { String contextPath = "localhost"; when(request.getRequestURI()).thenReturn(contextPath + EXAMPLE_ENDPOINT); when(request.getContextPath()).thenReturn(contextPath); } @Test public void authenticate_from_basic_http_header() { when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + CREDENTIALS_IN_BASE64); Credentials credentials = new Credentials(A_LOGIN, A_PASSWORD); when(credentialsAuthentication.authenticate(credentials, request, BASIC)).thenReturn(USER); underTest.authenticate(request); verify(credentialsAuthentication).authenticate(credentials, request, BASIC); verifyNoMoreInteractions(authenticationEvent); } @Test public void authenticate_from_basic_http_header_with_password_containing_semi_colon() { String password = "!ascii-only:-)@"; when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(A_LOGIN + ":" + password)); when(credentialsAuthentication.authenticate(new Credentials(A_LOGIN, password), request, BASIC)).thenReturn(USER); underTest.authenticate(request); verify(credentialsAuthentication).authenticate(new Credentials(A_LOGIN, password), request, BASIC); verifyNoMoreInteractions(authenticationEvent); } @Test public void does_not_authenticate_when_no_authorization_header() { underTest.authenticate(request); verifyNoInteractions(credentialsAuthentication, authenticationEvent); } @Test public void does_not_authenticate_when_authorization_header_is_not_BASIC() { when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("OTHER " + CREDENTIALS_IN_BASE64); underTest.authenticate(request); verifyNoInteractions(credentialsAuthentication, authenticationEvent); } @Test public void fail_to_authenticate_when_no_login() { when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(":" + A_PASSWORD)); assertThatThrownBy(() -> underTest.authenticate(request)) .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.local(BASIC)); verifyNoInteractions(authenticationEvent); } @Test public void fail_to_authenticate_when_invalid_header() { when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic Invàlid"); assertThatThrownBy(() -> underTest.authenticate(request)) .hasMessage("Invalid basic header") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.local(BASIC)); } @Test public void authenticate_from_user_token() { UserDto user = db.users().insertUser(); when(userTokenAuthentication.authenticate(request)).thenReturn(Optional.of(new UserAuthResult(user, new UserTokenDto().setName("my-token"), UserAuthResult.AuthType.TOKEN))); when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64("token:")); Optional<UserDto> userAuthenticated = underTest.authenticate(request); assertThat(userAuthenticated).isPresent(); assertThat(userAuthenticated.get().getLogin()).isEqualTo(user.getLogin()); } @Test public void does_not_authenticate_from_user_token_when_token_is_invalid() { when(userTokenAuthentication.authenticate(request)).thenReturn(Optional.empty()); when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64("token:")); assertThatThrownBy(() -> underTest.authenticate(request)) .hasMessage("User doesn't exist") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.local(SONARQUBE_TOKEN)); verifyNoInteractions(authenticationEvent); verify(request, times(0)).setAttribute(anyString(), anyString()); } @Test public void does_not_authenticate_from_user_token_when_token_does_not_match_existing_user() { when(userTokenAuthentication.authenticate(request)).thenThrow(AuthenticationException.newBuilder() .setSource(AuthenticationEvent.Source.local(AuthenticationEvent.Method.SONARQUBE_TOKEN)) .setMessage("User doesn't exist") .build()); when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64("token:")); assertThatThrownBy(() -> underTest.authenticate(request)) .hasMessageContaining("User doesn't exist") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.local(SONARQUBE_TOKEN)); verifyNoInteractions(authenticationEvent); } private static String toBase64(String text) { return new String(BASE64_ENCODER.encode(text.getBytes(UTF_8))); } }
7,858
40.363158
177
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CookiesTest.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; import org.junit.Test; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; 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; import static org.sonar.server.authentication.Cookies.findCookie; import static org.sonar.server.authentication.Cookies.newCookieBuilder; public class CookiesTest { private static final String HTTPS_HEADER = "X-Forwarded-Proto"; private HttpRequest request = mock(HttpRequest.class); @Test public void create_cookie() { Cookie cookie = newCookieBuilder(request).setName("name").setValue("value").setHttpOnly(true).setExpiry(10).build(); assertThat(cookie.getName()).isEqualTo("name"); assertThat(cookie.getValue()).isEqualTo("value"); assertThat(cookie.isHttpOnly()).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(10); assertThat(cookie.isSecure()).isFalse(); assertThat(cookie.getPath()).isEqualTo("/"); } @Test public void create_cookie_without_value() { Cookie cookie = newCookieBuilder(request).setName("name").build(); assertThat(cookie.getName()).isEqualTo("name"); assertThat(cookie.getValue()).isNull(); } @Test public void create_cookie_when_web_context() { when(request.getContextPath()).thenReturn("/sonarqube"); Cookie cookie = newCookieBuilder(request).setName("name").setValue("value").setHttpOnly(true).setExpiry(10).build(); assertThat(cookie.getName()).isEqualTo("name"); assertThat(cookie.getValue()).isEqualTo("value"); assertThat(cookie.isHttpOnly()).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(10); assertThat(cookie.isSecure()).isFalse(); assertThat(cookie.getPath()).isEqualTo("/sonarqube"); } @Test public void create_not_secured_cookie_when_header_is_not_http() { when(request.getHeader(HTTPS_HEADER)).thenReturn("http"); Cookie cookie = newCookieBuilder(request).setName("name").setValue("value").setHttpOnly(true).setExpiry(10).build(); assertThat(cookie.isSecure()).isFalse(); } @Test public void create_secured_cookie_when_X_Forwarded_Proto_header_is_https() { when(request.getHeader(HTTPS_HEADER)).thenReturn("https"); Cookie cookie = newCookieBuilder(request).setName("name").setValue("value").setHttpOnly(true).setExpiry(10).build(); assertThat(cookie.isSecure()).isTrue(); } @Test public void create_secured_cookie_when_X_Forwarded_Proto_header_is_HTTPS() { when(request.getHeader(HTTPS_HEADER)).thenReturn("HTTPS"); Cookie cookie = newCookieBuilder(request).setName("name").setValue("value").setHttpOnly(true).setExpiry(10).build(); assertThat(cookie.isSecure()).isTrue(); } @Test public void find_cookie() { Cookie cookie = newCookieBuilder(request).setName("name").setValue("value").build(); when(request.getCookies()).thenReturn(new Cookie[] {cookie}); assertThat(findCookie("name", request)).isPresent(); assertThat(findCookie("NAME", request)).isEmpty(); assertThat(findCookie("unknown", request)).isEmpty(); } @Test public void does_not_fail_to_find_cookie_when_no_cookie() { assertThat(findCookie("unknown", request)).isEmpty(); } @Test public void fail_with_NPE_when_cookie_name_is_null() { assertThatThrownBy(() -> newCookieBuilder(request).setName(null)) .isInstanceOf(NullPointerException.class); } @Test public void fail_with_NPE_when_cookie_has_no_name() { assertThatThrownBy(() -> newCookieBuilder(request).setName(null)) .isInstanceOf(NullPointerException.class); } }
4,560
37.327731
120
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsExternalAuthenticationTest.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; import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.security.Authenticator; import org.sonar.api.security.ExternalGroupsProvider; import org.sonar.api.security.ExternalUsersProvider; import org.sonar.api.security.SecurityRealm; import org.sonar.api.security.UserDetails; import org.sonar.api.server.http.HttpRequest; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationEvent.Source; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.user.SecurityRealmFactory; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.SONARQUBE_TOKEN; public class CredentialsExternalAuthenticationTest { private static final String LOGIN = "LOGIN"; private static final String PASSWORD = "PASSWORD"; private static final String REALM_NAME = "realm name"; private final MapSettings settings = new MapSettings(); private final SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class); private final SecurityRealm realm = mock(SecurityRealm.class); private final Authenticator authenticator = mock(Authenticator.class); private final ExternalUsersProvider externalUsersProvider = mock(ExternalUsersProvider.class); private final ExternalGroupsProvider externalGroupsProvider = mock(ExternalGroupsProvider.class); private final TestUserRegistrar userIdentityAuthenticator = new TestUserRegistrar(); private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class); private final HttpRequest request = new JavaxHttpRequest(mock(HttpServletRequest.class)); private final CredentialsExternalAuthentication underTest = new CredentialsExternalAuthentication(settings.asConfig(), securityRealmFactory, userIdentityAuthenticator, authenticationEvent); @Before public void setUp() throws Exception { when(realm.getName()).thenReturn(REALM_NAME); } @Test public void authenticate() { executeStartWithoutGroupSync(); when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true); UserDetails userDetails = new UserDetails(); userDetails.setName("name"); userDetails.setEmail("email"); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(userDetails); underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getProviderLogin()).isEqualTo(LOGIN); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getProviderId()).isNull(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getName()).isEqualTo("name"); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getEmail()).isEqualTo("email"); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().shouldSyncGroups()).isFalse(); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, REALM_NAME)); } @Test public void authenticate_with_sonarqube_identity_provider() { executeStartWithoutGroupSync(); when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true); UserDetails userDetails = new UserDetails(); userDetails.setName("name"); userDetails.setEmail("email"); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(userDetails); underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getProvider().getKey()).isEqualTo("sonarqube"); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getProvider().getName()).isEqualTo("sonarqube"); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getProvider().getDisplay()).isNull(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getProvider().isEnabled()).isTrue(); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, REALM_NAME)); } @Test public void login_is_used_when_no_name_provided() { executeStartWithoutGroupSync(); when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true); UserDetails userDetails = new UserDetails(); userDetails.setEmail("email"); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(userDetails); underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getProvider().getName()).isEqualTo("sonarqube"); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, REALM_NAME)); } @Test public void authenticate_with_group_sync() { when(externalGroupsProvider.doGetGroups(any(ExternalGroupsProvider.Context.class))).thenReturn(asList("group1", "group2")); executeStartWithGroupSync(); executeAuthenticate(); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().shouldSyncGroups()).isTrue(); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, REALM_NAME)); } @Test public void use_login_if_user_details_contains_no_name() { executeStartWithoutGroupSync(); when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true); UserDetails userDetails = new UserDetails(); userDetails.setName(null); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(userDetails); underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getName()).isEqualTo(LOGIN); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, REALM_NAME)); } @Test public void use_downcase_login() { settings.setProperty("sonar.authenticator.downcase", true); executeStartWithoutGroupSync(); executeAuthenticate("LOGIN"); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getProviderLogin()).isEqualTo("login"); verify(authenticationEvent).loginSuccess(request, "login", Source.realm(BASIC, REALM_NAME)); } @Test public void does_not_user_downcase_login() { settings.setProperty("sonar.authenticator.downcase", false); executeStartWithoutGroupSync(); executeAuthenticate("LoGiN"); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); assertThat(userIdentityAuthenticator.getAuthenticatorParameters().getUserIdentity().getProviderLogin()).isEqualTo("LoGiN"); verify(authenticationEvent).loginSuccess(request, "LoGiN", Source.realm(BASIC, REALM_NAME)); } @Test public void fail_to_authenticate_when_user_details_are_null() { executeStartWithoutGroupSync(); when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(null); Credentials credentials = new Credentials(LOGIN, PASSWORD); assertThatThrownBy(() -> underTest.authenticate(credentials, request, BASIC)) .hasMessage("No user details") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.realm(BASIC, REALM_NAME)) .hasFieldOrPropertyWithValue("login", LOGIN); verifyNoInteractions(authenticationEvent); } @Test public void fail_to_authenticate_when_external_authentication_fails() { executeStartWithoutGroupSync(); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(new UserDetails()); when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(false); Credentials credentials = new Credentials(LOGIN, PASSWORD); assertThatThrownBy(() -> underTest.authenticate(credentials, request, BASIC)) .hasMessage("Realm returned authenticate=false") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.realm(BASIC, REALM_NAME)) .hasFieldOrPropertyWithValue("login", LOGIN); verifyNoInteractions(authenticationEvent); } @Test public void fail_to_authenticate_when_any_exception_is_thrown() { executeStartWithoutGroupSync(); String expectedMessage = "emulating exception in doAuthenticate"; doThrow(new IllegalArgumentException(expectedMessage)).when(authenticator).doAuthenticate(any(Authenticator.Context.class)); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(new UserDetails()); Credentials credentials = new Credentials(LOGIN, PASSWORD); assertThatThrownBy(() -> underTest.authenticate(credentials, request, SONARQUBE_TOKEN)) .hasMessage(expectedMessage) .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.realm(SONARQUBE_TOKEN, REALM_NAME)) .hasFieldOrPropertyWithValue("login", LOGIN); verifyNoInteractions(authenticationEvent); } @Test public void return_empty_user_when_no_realm() { assertThat(underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)).isEmpty(); verifyNoMoreInteractions(authenticationEvent); } @Test public void fail_to_start_when_no_authenticator() { when(realm.doGetAuthenticator()).thenReturn(null); when(securityRealmFactory.getRealm()).thenReturn(realm); assertThatThrownBy(underTest::start) .isInstanceOf(NullPointerException.class) .hasMessage("No authenticator available"); } @Test public void fail_to_start_when_no_user_provider() { when(realm.doGetAuthenticator()).thenReturn(authenticator); when(realm.getUsersProvider()).thenReturn(null); when(securityRealmFactory.getRealm()).thenReturn(realm); assertThatThrownBy(underTest::start) .isInstanceOf(NullPointerException.class) .hasMessage("No users provider available"); } private void executeStartWithoutGroupSync() { when(realm.doGetAuthenticator()).thenReturn(authenticator); when(realm.getUsersProvider()).thenReturn(externalUsersProvider); when(securityRealmFactory.getRealm()).thenReturn(realm); underTest.start(); } private void executeStartWithGroupSync() { when(realm.doGetAuthenticator()).thenReturn(authenticator); when(realm.getUsersProvider()).thenReturn(externalUsersProvider); when(realm.getGroupsProvider()).thenReturn(externalGroupsProvider); when(securityRealmFactory.getRealm()).thenReturn(realm); underTest.start(); } private void executeAuthenticate() { executeAuthenticate(LOGIN); } private void executeAuthenticate(String login) { when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true); UserDetails userDetails = new UserDetails(); userDetails.setName("name"); when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(userDetails); underTest.authenticate(new Credentials(login, PASSWORD), request, BASIC); } }
13,311
44.745704
169
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsTest.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; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; public class CredentialsTest { @Test public void login_cant_be_empty() { Throwable thrown = catchThrowable(() -> new Credentials("", "bar")); assertThat(thrown) .isInstanceOf(IllegalArgumentException.class) .hasMessage("login must not be null nor empty"); thrown = catchThrowable(() -> new Credentials(null, "bar")); assertThat(thrown) .isInstanceOf(IllegalArgumentException.class) .hasMessage("login must not be null nor empty"); Credentials underTest = new Credentials("foo", "bar"); assertThat(underTest.getLogin()).isEqualTo("foo"); } @Test public void password_cant_be_empty_string() { Credentials underTest = new Credentials("foo", ""); assertThat(underTest.getPassword()).isEmpty(); underTest = new Credentials("foo", null); assertThat(underTest.getPassword()).isEmpty(); underTest = new Credentials("foo", " "); assertThat(underTest.getPassword()).hasValue(" "); underTest = new Credentials("foo", "bar"); assertThat(underTest.getPassword()).hasValue("bar"); } @Test public void test_equality() { assertThat(new Credentials("foo", "bar")) .isEqualTo(new Credentials("foo", "bar")) .isNotEqualTo(new Credentials("foo", "baaaar")) .isNotEqualTo(new Credentials("foooooo", "bar")) .isNotEqualTo(new Credentials("foo", null)) .hasSameHashCodeAs(new Credentials("foo", "bar")); } }
2,459
34.142857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierFilterTest.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; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import org.sonar.server.user.ThreadLocalUserSession; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class DefaultAdminCredentialsVerifierFilterTest { private final HttpRequest request = mock(HttpRequest.class); private final HttpResponse response = mock(HttpResponse.class); private final FilterChain chain = mock(FilterChain.class); private final Configuration config = mock(Configuration.class); private final DefaultAdminCredentialsVerifier defaultAdminCredentialsVerifier = mock(DefaultAdminCredentialsVerifier.class); private final ThreadLocalUserSession session = mock(ThreadLocalUserSession.class); private final DefaultAdminCredentialsVerifierFilter underTest = new DefaultAdminCredentialsVerifierFilter(config, defaultAdminCredentialsVerifier, session); @Before public void before() { when(request.getRequestURI()).thenReturn("/"); when(request.getContextPath()).thenReturn(""); when(config.getBoolean("sonar.forceRedirectOnDefaultAdminCredentials")).thenReturn(Optional.of(true)); when(defaultAdminCredentialsVerifier.hasDefaultCredentialUser()).thenReturn(true); when(session.hasSession()).thenReturn(true); when(session.isLoggedIn()).thenReturn(true); when(session.isSystemAdministrator()).thenReturn(true); } @Test public void verify_other_methods() { underTest.init(); underTest.destroy(); verifyNoInteractions(request, response, chain, session); } @Test public void redirect_if_instance_uses_default_admin_credentials() throws Exception { underTest.doFilter(request, response, chain); verify(response).sendRedirect("/admin/change_admin_password"); } @Test public void redirect_if_instance_uses_default_admin_credentials_and_web_context_configured() throws Exception { when(request.getContextPath()).thenReturn("/sonarqube"); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/admin/change_admin_password"); } @Test public void redirect_if_request_uri_ends_with_slash() throws Exception { when(request.getRequestURI()).thenReturn("/projects/"); when(request.getContextPath()).thenReturn("/sonarqube"); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/admin/change_admin_password"); } @Test public void do_not_redirect_if_not_a_system_administrator() throws Exception { when(session.isSystemAdministrator()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test public void do_not_redirect_if_not_logged_in() throws Exception { when(session.isLoggedIn()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test public void do_not_redirect_if_user_is_admin() throws Exception { when(session.getLogin()).thenReturn("admin"); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test public void do_not_redirect_if_instance_does_not_use_default_admin_credentials() throws Exception { when(defaultAdminCredentialsVerifier.hasDefaultCredentialUser()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test public void do_not_redirect_if_config_says_so() throws Exception { when(config.getBoolean("sonar.forceRedirectOnDefaultAdminCredentials")).thenReturn(Optional.of(false)); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test @UseDataProvider("skipped_urls") public void doGetPattern_verify(String urltoSkip) throws Exception { when(request.getRequestURI()).thenReturn(urltoSkip); when(request.getContextPath()).thenReturn(""); underTest.doGetPattern().matches(urltoSkip); verify(response, never()).sendRedirect(any()); } @DataProvider public static Object[][] skipped_urls() { return new Object[][] { {"/batch/index"}, {"/batch/file"}, {"/api/issues"}, {"/api/issues/"}, {"/api/*"}, {"/admin/change_admin_password"}, {"/account/reset_password"}, }; } }
5,862
33.692308
158
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierNotificationTemplateTest.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; import org.junit.Test; import org.sonar.api.notifications.Notification; import org.sonar.server.issue.notification.EmailMessage; import static org.assertj.core.api.Assertions.assertThat; public class DefaultAdminCredentialsVerifierNotificationTemplateTest { private DefaultAdminCredentialsVerifierNotificationTemplate underTest = new DefaultAdminCredentialsVerifierNotificationTemplate(); @Test public void do_not_format_other_notifications() { assertThat(underTest.format(new Notification("foo"))).isNull(); } @Test public void format_notification() { Notification notification = new Notification(DefaultAdminCredentialsVerifierNotification.TYPE); EmailMessage emailMessage = underTest.format(notification); assertThat(emailMessage.getSubject()).isEqualTo("Default Administrator credentials are still used"); assertThat(emailMessage.getMessage()).isEqualTo(""" Hello, Your SonarQube instance is still using default administrator credentials. Make sure to change the password for the 'admin' account or deactivate this account."""); } }
1,983
37.153846
132
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/FakeBasicIdentityProvider.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; import org.sonar.api.server.authentication.BaseIdentityProvider; class FakeBasicIdentityProvider extends TestIdentityProvider implements BaseIdentityProvider { private boolean initCalled = false; public FakeBasicIdentityProvider(String key, boolean enabled) { setKey(key); setName("name of " + key); setEnabled(enabled); } @Override public void init(Context context) { initCalled = true; } public boolean isInitCalled() { return initCalled; } }
1,372
30.204545
94
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/FakeOAuth2IdentityProvider.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; import org.sonar.api.server.authentication.OAuth2IdentityProvider; class FakeOAuth2IdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider { private boolean initCalled = false; private boolean callbackCalled = false; public FakeOAuth2IdentityProvider(String key, boolean enabled) { setKey(key); setName("name of " + key); setEnabled(enabled); } @Override public void init(InitContext context) { initCalled = true; } @Override public void callback(CallbackContext context) { callbackCalled = true; } public boolean isInitCalled() { return initCalled; } public boolean isCallbackCalled() { return callbackCalled; } }
1,587
28.962264
97
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/IdentityProviderRepositoryTest.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; import java.util.List; import org.junit.Test; import org.sonar.api.server.authentication.IdentityProvider; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class IdentityProviderRepositoryTest { private static IdentityProvider GITHUB = new TestIdentityProvider() .setKey("github") .setName("Github") .setEnabled(true); private static IdentityProvider BITBUCKET = new TestIdentityProvider() .setKey("bitbucket") .setName("Bitbucket") .setEnabled(true); private static IdentityProvider DISABLED = new TestIdentityProvider() .setKey("disabled") .setName("Disabled") .setEnabled(false); @Test public void return_enabled_provider() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET, DISABLED)); assertThat(underTest.getEnabledByKey(GITHUB.getKey())).isEqualTo(GITHUB); assertThat(underTest.getEnabledByKey(BITBUCKET.getKey())).isEqualTo(BITBUCKET); } @Test public void fail_on_disabled_provider() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET, DISABLED)); assertThatThrownBy(() -> underTest.getEnabledByKey(DISABLED.getKey())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Identity provider disabled does not exist or is not enabled"); } @Test public void fail_on_non_exist_provider() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET, DISABLED)); assertThatThrownBy(() -> underTest.getEnabledByKey("NotExist")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Identity provider NotExist does not exist or is not enabled"); } @Test public void return_all_enabled_providers() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET, DISABLED)); List<IdentityProvider> providers = underTest.getAllEnabledAndSorted(); assertThat(providers).containsOnly(GITHUB, BITBUCKET); } @Test public void return_sorted_enabled_providers() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET)); List<IdentityProvider> providers = underTest.getAllEnabledAndSorted(); assertThat(providers).containsExactly(BITBUCKET, GITHUB); } @Test public void return_nothing_when_no_identity_provider() { IdentityProviderRepository underTest = new IdentityProviderRepository(null); assertThat(underTest.getAllEnabledAndSorted()).isEmpty(); } }
3,546
35.947917
111
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/InitFilterTest.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; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.slf4j.event.Level; import org.sonar.api.server.authentication.BaseIdentityProvider; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.authentication.UnauthorizedException; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.web.FilterChain; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class InitFilterTest { private static final String OAUTH2_PROVIDER_KEY = "github"; private static final String BASIC_PROVIDER_KEY = "openid"; @Rule public LogTester logTester = new LogTester(); @Rule public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule(); private BaseContextFactory baseContextFactory = mock(BaseContextFactory.class); private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class); private HttpRequest request = mock(HttpRequest.class); private HttpResponse response = mock(HttpResponse.class); private FilterChain chain = mock(FilterChain.class); private FakeOAuth2IdentityProvider oAuth2IdentityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true); private OAuth2IdentityProvider.InitContext oauth2Context = mock(OAuth2IdentityProvider.InitContext.class); private FakeBasicIdentityProvider baseIdentityProvider = new FakeBasicIdentityProvider(BASIC_PROVIDER_KEY, true); private BaseIdentityProvider.Context baseContext = mock(BaseIdentityProvider.Context.class); private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class); private OAuth2AuthenticationParameters auth2AuthenticationParameters = mock(OAuth2AuthenticationParameters.class); private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class); private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class); private InitFilter underTest = new InitFilter(identityProviderRepository, baseContextFactory, oAuth2ContextFactory, authenticationEvent, auth2AuthenticationParameters); @Before public void setUp() throws Exception { when(oAuth2ContextFactory.newContext(request, response, oAuth2IdentityProvider)).thenReturn(oauth2Context); when(baseContextFactory.newContext(request, response, baseIdentityProvider)).thenReturn(baseContext); when(request.getContextPath()).thenReturn(""); } @Test public void do_get_pattern() { assertThat(underTest.doGetPattern()).isNotNull(); } @Test public void do_filter_with_context() { when(request.getContextPath()).thenReturn("/sonarqube"); when(request.getRequestURI()).thenReturn("/sonarqube/sessions/init/" + OAUTH2_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider); underTest.doFilter(request, response, chain); assertOAuth2InitCalled(); verifyNoInteractions(authenticationEvent); } @Test public void do_filter_on_auth2_identity_provider() { when(request.getRequestURI()).thenReturn("/sessions/init/" + OAUTH2_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider); underTest.doFilter(request, response, chain); assertOAuth2InitCalled(); verifyNoInteractions(authenticationEvent); } @Test public void do_filter_on_basic_identity_provider() { when(request.getRequestURI()).thenReturn("/sessions/init/" + BASIC_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(baseIdentityProvider); underTest.doFilter(request, response, chain); assertBasicInitCalled(); verifyNoInteractions(authenticationEvent); } @Test public void init_authentication_parameter_on_auth2_identity_provider() { when(request.getContextPath()).thenReturn("/sonarqube"); when(request.getRequestURI()).thenReturn("/sonarqube/sessions/init/" + OAUTH2_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider); underTest.doFilter(request, response, chain); verify(auth2AuthenticationParameters).init(request, response); } @Test public void does_not_init_authentication_parameter_on_basic_authentication() { when(request.getRequestURI()).thenReturn("/sessions/init/" + BASIC_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(baseIdentityProvider); underTest.doFilter(request, response, chain); verify(auth2AuthenticationParameters, never()).init(request, response); } @Test public void fail_if_identity_provider_key_is_empty() throws Exception { when(request.getRequestURI()).thenReturn("/sessions/init/"); underTest.doFilter(request, response, chain); assertError("No provider key found in URI"); verifyNoInteractions(authenticationEvent); verifyNoInteractions(auth2AuthenticationParameters); } @Test public void fail_if_uri_does_not_contains_callback() throws Exception { when(request.getRequestURI()).thenReturn("/sessions/init"); underTest.doFilter(request, response, chain); assertError("No provider key found in URI"); verifyNoInteractions(authenticationEvent); verifyNoInteractions(auth2AuthenticationParameters); } @Test public void fail_if_identity_provider_class_is_unsupported() throws Exception { String unsupportedKey = "unsupported"; when(request.getRequestURI()).thenReturn("/sessions/init/" + unsupportedKey); IdentityProvider identityProvider = new UnsupportedIdentityProvider(unsupportedKey); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); assertError("Unsupported IdentityProvider class: class org.sonar.server.authentication.InitFilterTest$UnsupportedIdentityProvider"); verifyNoInteractions(authenticationEvent); verifyNoInteractions(auth2AuthenticationParameters); } @Test public void redirect_contains_cookie_with_error_message_when_failing_because_of_UnauthorizedExceptionException() throws Exception { IdentityProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider("failing"); when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sessions/unauthorized"); verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture()); AuthenticationException authenticationException = authenticationExceptionCaptor.getValue(); assertThat(authenticationException).hasMessage("Email john@email.com is already used"); assertThat(authenticationException.getSource()).isEqualTo(AuthenticationEvent.Source.external(identityProvider)); assertThat(authenticationException.getLogin()).isNull(); assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used"); verifyDeleteAuthCookie(); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie cookie = cookieArgumentCaptor.getValue(); assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR"); assertThat(cookie.getValue()).isEqualTo("Email%20john%40email.com%20is%20already%20used"); assertThat(cookie.getPath()).isEqualTo("/"); assertThat(cookie.isHttpOnly()).isFalse(); assertThat(cookie.getMaxAge()).isEqualTo(300); assertThat(cookie.isSecure()).isFalse(); } @Test public void redirect_with_context_path_when_failing_because_of_UnauthorizedException() throws Exception { when(request.getContextPath()).thenReturn("/sonarqube"); IdentityProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider("failing"); when(request.getRequestURI()).thenReturn("/sonarqube/sessions/init/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/sessions/unauthorized"); } @Test public void redirect_when_failing_because_of_Exception() throws Exception { IdentityProvider identityProvider = new FailWithIllegalStateException("failing"); when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sessions/unauthorized"); assertThat(logTester.logs(Level.WARN)).containsExactlyInAnyOrder("Fail to initialize authentication with provider 'failing'"); verifyDeleteAuthCookie(); } @Test public void redirect_with_context_when_failing_because_of_Exception() throws Exception { when(request.getContextPath()).thenReturn("/sonarqube"); IdentityProvider identityProvider = new FailWithIllegalStateException("failing"); when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/sessions/unauthorized"); } private void assertOAuth2InitCalled() { assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(oAuth2IdentityProvider.isInitCalled()).isTrue(); } private void assertBasicInitCalled() { assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(baseIdentityProvider.isInitCalled()).isTrue(); } private void assertError(String expectedError) throws Exception { assertThat(logTester.logs(Level.WARN)).contains(expectedError); verify(response).sendRedirect("/sessions/unauthorized"); assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse(); } private void verifyDeleteAuthCookie() { verify(auth2AuthenticationParameters).delete(request, response); } private static class FailWithUnauthorizedExceptionIdProvider extends FakeBasicIdentityProvider { public FailWithUnauthorizedExceptionIdProvider(String key) { super(key, true); } @Override public void init(Context context) { throw new UnauthorizedException("Email john@email.com is already used"); } } private static class FailWithIllegalStateException extends FakeBasicIdentityProvider { public FailWithIllegalStateException(String key) { super(key, true); } @Override public void init(Context context) { throw new IllegalStateException("Failure !"); } } private static class UnsupportedIdentityProvider implements IdentityProvider { private final String unsupportedKey; public UnsupportedIdentityProvider(String unsupportedKey) { this.unsupportedKey = unsupportedKey; } @Override public String getKey() { return unsupportedKey; } @Override public String getName() { return null; } @Override public Display getDisplay() { return null; } @Override public boolean isEnabled() { return true; } @Override public boolean allowsUsersToSignUp() { return false; } } }
12,797
38.5
170
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtCsrfVerifierTest.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; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.server.authentication.event.AuthenticationEvent.Source; import org.sonar.server.authentication.event.AuthenticationException; 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.verify; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.Cookies.SET_COOKIE; import static org.sonar.server.authentication.event.AuthenticationEvent.Method; public class JwtCsrfVerifierTest { private static final int TIMEOUT = 30; private static final String CSRF_STATE = "STATE"; private static final String JAVA_WS_URL = "/api/projects/create"; private static final String LOGIN = "foo login"; private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class); private HttpResponse response = mock(HttpResponse.class); private HttpRequest request = mock(HttpRequest.class); private JwtCsrfVerifier underTest = new JwtCsrfVerifier(); @Before public void setUp() { when(request.getContextPath()).thenReturn(""); } @Test public void generate_state() { String state = underTest.generateState(request, response, TIMEOUT); assertThat(state).isNotEmpty(); verify(response).addHeader(SET_COOKIE, String.format("XSRF-TOKEN=%s; Path=/; SameSite=Lax; Max-Age=30", state)); } @Test public void verify_state() { mockRequestCsrf(CSRF_STATE); mockPostJavaWsRequest(); underTest.verifyState(request, CSRF_STATE, LOGIN); } @Test public void fail_with_AuthenticationException_when_state_header_is_not_the_same_as_state_parameter() { mockRequestCsrf("other value"); mockPostJavaWsRequest(); assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) .isInstanceOf(AuthenticationException.class) .hasMessage("Wrong CSFR in request") .hasFieldOrPropertyWithValue("login", LOGIN) .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test public void fail_with_AuthenticationException_when_state_is_null() { mockRequestCsrf(CSRF_STATE); mockPostJavaWsRequest(); assertThatThrownBy(() -> underTest.verifyState(request, null, LOGIN)) .hasMessage("Missing reference CSRF value") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("login", LOGIN) .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test public void fail_with_AuthenticationException_when_state_parameter_is_empty() { mockRequestCsrf(CSRF_STATE); mockPostJavaWsRequest(); assertThatThrownBy(() -> underTest.verifyState(request, "", LOGIN)) .hasMessage("Missing reference CSRF value") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("login", LOGIN) .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test public void verify_POST_request() { mockRequestCsrf("other value"); when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("POST"); assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) .hasMessage("Wrong CSFR in request") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("login", LOGIN) .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test public void verify_PUT_request() { mockRequestCsrf("other value"); when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("PUT"); assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) .hasMessage("Wrong CSFR in request") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("login", LOGIN) .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test public void verify_DELETE_request() { mockRequestCsrf("other value"); when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("DELETE"); assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) .hasMessage("Wrong CSFR in request") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("login", LOGIN) .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test public void ignore_GET_request() { when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("GET"); underTest.verifyState(request, null, LOGIN); } @Test public void ignore_not_api_requests() { executeVerifyStateDoesNotFailOnRequest("/events", "POST"); executeVerifyStateDoesNotFailOnRequest("/favorites", "POST"); } @Test public void refresh_state() { underTest.refreshState(request, response, CSRF_STATE, 30); verify(response).addHeader(SET_COOKIE, String.format("XSRF-TOKEN=%s; Path=/; SameSite=Lax; Max-Age=30", CSRF_STATE)); } @Test public void remove_state() { underTest.removeState(request, response); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie cookie = cookieArgumentCaptor.getValue(); assertThat(cookie.getValue()).isNull(); assertThat(cookie.getMaxAge()).isZero(); } private void verifyCookie(Cookie cookie) { assertThat(cookie.getName()).isEqualTo("XSRF-TOKEN"); assertThat(cookie.getValue()).isNotEmpty(); assertThat(cookie.getPath()).isEqualTo("/"); assertThat(cookie.isHttpOnly()).isFalse(); assertThat(cookie.getMaxAge()).isEqualTo(TIMEOUT); assertThat(cookie.isSecure()).isFalse(); } private void mockPostJavaWsRequest() { when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("POST"); } private void mockRequestCsrf(String csrfState) { when(request.getHeader("X-XSRF-TOKEN")).thenReturn(csrfState); } private void executeVerifyStateDoesNotFailOnRequest(String uri, String method) { when(request.getRequestURI()).thenReturn(uri); when(request.getMethod()).thenReturn(method); underTest.verifyState(request, null, LOGIN); } }
7,342
34.819512
121
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtSerializerTest.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; import com.google.common.collect.ImmutableMap; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.impl.DefaultClaims; import java.util.Base64; import java.util.Date; import java.util.Optional; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.server.authentication.JwtSerializer.JwtSession; import org.sonar.server.authentication.event.AuthenticationException; import static io.jsonwebtoken.SignatureAlgorithm.HS256; import static org.apache.commons.lang.time.DateUtils.addMinutes; import static org.apache.commons.lang.time.DateUtils.addYears; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; public class JwtSerializerTest { private static final String A_SECRET_KEY = "HrPSavOYLNNrwTY+SOqpChr7OwvbR/zbDLdVXRN0+Eg="; private static final String USER_LOGIN = "john"; private static final String SESSION_TOKEN_UUID = "ABCD"; private MapSettings settings = new MapSettings(); private System2 system2 = System2.INSTANCE; private JwtSerializer underTest = new JwtSerializer(settings.asConfig(), system2); @Test public void generate_token() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 20).getTime())); assertThat(token).isNotEmpty(); } @Test public void generate_token_with_expiration_date() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 20).getTime())); assertThat(token).isNotEmpty(); Claims claims = underTest.decode(token).get(); assertThat(claims.getExpiration().getTime()) .isGreaterThanOrEqualTo(addMinutes(new Date(), 19).getTime()); } @Test public void generate_token_with_big_expiration_date() { setSecretKey(A_SECRET_KEY); underTest.start(); long oneYearLater = addYears(new Date(), 1).getTime(); String token = underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, oneYearLater)); assertThat(token).isNotEmpty(); Claims claims = underTest.decode(token).get(); // Check expiration date it set to one year in the future assertThat(claims.getExpiration().getTime()).isGreaterThanOrEqualTo(oneYearLater - 1000L); } @Test public void generate_token_with_property() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 20).getTime(), ImmutableMap.of("custom", "property"))); assertThat(token).isNotEmpty(); Claims claims = underTest.decode(token).get(); assertThat(claims).containsEntry("custom", "property"); } @Test public void decode_token() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 20).getTime())); Claims claims = underTest.decode(token).get(); assertThat(claims.getId()).isEqualTo(SESSION_TOKEN_UUID); assertThat(claims.getSubject()).isEqualTo(USER_LOGIN); assertThat(claims.getExpiration()).isNotNull(); assertThat(claims.getIssuedAt()).isNotNull(); // Check expiration date it set to more than 19 minutes in the future assertThat(claims.getExpiration()).isAfterOrEqualTo(addMinutes(new Date(), 19)); } @Test public void return_no_token_when_expiration_date_is_reached() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setIssuedAt(new Date(system2.now())) .setExpiration(addMinutes(new Date(), -20)) .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); assertThat(underTest.decode(token)).isEmpty(); } @Test public void return_no_token_when_secret_key_has_changed() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setSubject(USER_LOGIN) .setIssuedAt(new Date(system2.now())) .setExpiration(addMinutes(new Date(), 20)) .signWith(decodeSecretKey("LyWgHktP0FuHB2K+kMs3KWMCJyFHVZDdDSqpIxAMVaQ="), HS256) .compact(); assertThat(underTest.decode(token)).isEmpty(); } @Test public void return_no_token_if_none_algorithm() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setSubject(USER_LOGIN) .setIssuedAt(new Date(system2.now())) .setExpiration(addMinutes(new Date(), 20)) .compact(); assertThat(underTest.decode(token)).isEmpty(); } @Test public void fail_to_decode_token_when_no_id() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setSubject(USER_LOGIN) .setIssuer("sonarqube") .setIssuedAt(new Date(system2.now())) .setExpiration(addMinutes(new Date(), 20)) .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); assertThatThrownBy(() -> underTest.decode(token)) .hasMessage("Token id hasn't been found") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.jwt()) .hasFieldOrPropertyWithValue("login", USER_LOGIN); } @Test public void fail_to_decode_token_when_no_subject() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setIssuer("sonarqube") .setIssuedAt(new Date(system2.now())) .setExpiration(addMinutes(new Date(), 20)) .signWith(HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); assertThatThrownBy(() -> underTest.decode(token)) .hasMessage("Token subject hasn't been found") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.jwt()); } @Test public void fail_to_decode_token_when_no_expiration_date() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setIssuer("sonarqube") .setSubject(USER_LOGIN) .setIssuedAt(new Date(system2.now())) .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); assertThatThrownBy(() -> underTest.decode(token)) .hasMessage("Token expiration date hasn't been found") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.jwt()) .hasFieldOrPropertyWithValue("login", USER_LOGIN); } @Test public void fail_to_decode_token_when_no_creation_date() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setSubject(USER_LOGIN) .setExpiration(addMinutes(new Date(), 20)) .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); assertThatThrownBy(() -> underTest.decode(token)) .hasMessage("Token creation date hasn't been found") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.jwt()) .hasFieldOrPropertyWithValue("login", USER_LOGIN); } @Test public void generate_new_secret_key_if_not_set_by_settings() { assertThat(underTest.getSecretKey()).isNull(); underTest.start(); assertThat(underTest.getSecretKey()).isNotNull(); assertThat(underTest.getSecretKey().getAlgorithm()).isEqualTo(HS256.getJcaName()); } @Test public void load_secret_key_from_settings() { setSecretKey(A_SECRET_KEY); underTest.start(); assertThat(settings.getString("sonar.auth.jwtBase64Hs256Secret")).isEqualTo(A_SECRET_KEY); } @Test public void refresh_token() { setSecretKey(A_SECRET_KEY); underTest.start(); Date now = new Date(); Date createdAt = DateUtils.parseDate("2016-01-01"); // Expired in 10 minutes Date expiredAt = addMinutes(new Date(), 10); Date lastRefreshDate = addMinutes(new Date(), -4); Claims token = new DefaultClaims() .setId("id") .setSubject("subject") .setIssuer("sonarqube") .setIssuedAt(createdAt) .setExpiration(expiredAt); token.put("lastRefreshTime", lastRefreshDate.getTime()); token.put("key", "value"); // Refresh the token with a higher expiration time String encodedToken = underTest.refresh(token, addMinutes(new Date(), 20).getTime()); Claims result = underTest.decode(encodedToken).get(); assertThat(result.getId()).isEqualTo("id"); assertThat(result.getSubject()).isEqualTo("subject"); assertThat(result.getIssuer()).isEqualTo("sonarqube"); assertThat(result.getIssuedAt()).isEqualTo(createdAt); assertThat(((long) result.get("lastRefreshTime"))).isGreaterThanOrEqualTo(now.getTime()); assertThat(result).containsEntry("key", "value"); // Expiration date has been changed assertThat(result.getExpiration()).isNotEqualTo(expiredAt) .isAfterOrEqualTo(addMinutes(new Date(), 19)); } @Test public void refresh_token_generate_a_new_hash() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 20).getTime())); Optional<Claims> claims = underTest.decode(token); String newToken = underTest.refresh(claims.get(), addMinutes(new Date(), 45).getTime()); assertThat(newToken).isNotEqualTo(token); } @Test public void encode_fail_when_not_started() { assertThatThrownBy(() -> underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 10).getTime()))) .isInstanceOf(NullPointerException.class) .hasMessage("org.sonar.server.authentication.JwtSerializer not started"); } @Test public void decode_fail_when_not_started() { assertThatThrownBy(() -> underTest.decode("token")) .isInstanceOf(NullPointerException.class) .hasMessage("org.sonar.server.authentication.JwtSerializer not started"); } @Test public void refresh_fail_when_not_started() { assertThatThrownBy(() -> underTest.refresh(new DefaultClaims(), addMinutes(new Date(), 10).getTime())) .isInstanceOf(NullPointerException.class) .hasMessage("org.sonar.server.authentication.JwtSerializer not started"); } private SecretKey decodeSecretKey(String encodedKey) { byte[] decodedKey = Base64.getDecoder().decode(encodedKey); return new SecretKeySpec(decodedKey, 0, decodedKey.length, HS256.getJcaName()); } private void setSecretKey(String s) { settings.setProperty("sonar.auth.jwtBase64Hs256Secret", s); } }
11,796
33.595308
161
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/LdapCredentialsAuthenticationTest.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; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.api.server.http.HttpRequest; import org.sonar.auth.ldap.LdapAuthenticator; import org.sonar.auth.ldap.LdapGroupsProvider; import org.sonar.auth.ldap.LdapRealm; import org.sonar.auth.ldap.LdapUserDetails; import org.sonar.auth.ldap.LdapUsersProvider; import org.sonar.process.ProcessProperties; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationEvent.Source; import org.sonar.server.authentication.event.AuthenticationException; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.refEq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.auth.ldap.LdapAuthenticationResult.failed; import static org.sonar.auth.ldap.LdapAuthenticationResult.success; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.SONARQUBE_TOKEN; @RunWith(MockitoJUnitRunner.Silent.class) public class LdapCredentialsAuthenticationTest { private static final String LOGIN = "LOGIN"; private static final String PASSWORD = "PASSWORD"; private static final String LDAP_SECURITY_REALM_NAME = "ldap"; private static final String SERVER_KEY = "superServerKey"; private static final String EXPECTED_EXTERNAL_PROVIDER_ID = "LDAP_superServerKey"; private static final LdapUserDetails LDAP_USER_DETAILS; static { LDAP_USER_DETAILS = new LdapUserDetails(); LDAP_USER_DETAILS.setName("name"); } private static final LdapUserDetails LDAP_USER_DETAILS_WITH_EMAIL; static { LDAP_USER_DETAILS_WITH_EMAIL = new LdapUserDetails(); LDAP_USER_DETAILS_WITH_EMAIL.setName("name"); LDAP_USER_DETAILS_WITH_EMAIL.setEmail("email"); } private final MapSettings settings = new MapSettings(); private final TestUserRegistrar userRegistrar = new TestUserRegistrar(); @Mock private AuthenticationEvent authenticationEvent; @Mock private HttpRequest request = mock(HttpRequest.class); @Mock private LdapAuthenticator ldapAuthenticator; @Mock private LdapGroupsProvider ldapGroupsProvider; @Mock private LdapUsersProvider ldapUsersProvider; @Mock private LdapRealm ldapRealm; private LdapCredentialsAuthentication underTest; @Before public void setUp() throws Exception { settings.setProperty(ProcessProperties.Property.SONAR_SECURITY_REALM.getKey(), "LDAP"); settings.setProperty(ProcessProperties.Property.SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey(), "true"); when(ldapRealm.getAuthenticator()).thenReturn(ldapAuthenticator); when(ldapRealm.getUsersProvider()).thenReturn(ldapUsersProvider); when(ldapRealm.getGroupsProvider()).thenReturn(ldapGroupsProvider); when(ldapRealm.isLdapAuthActivated()).thenReturn(true); underTest = new LdapCredentialsAuthentication(settings.asConfig(), userRegistrar, authenticationEvent, ldapRealm); } @Test public void authenticate_with_null_group_provider() { reset(ldapRealm); when(ldapRealm.getAuthenticator()).thenReturn(ldapAuthenticator); when(ldapRealm.getUsersProvider()).thenReturn(ldapUsersProvider); when(ldapRealm.getGroupsProvider()).thenReturn(null); when(ldapRealm.isLdapAuthActivated()).thenReturn(true); underTest = new LdapCredentialsAuthentication(settings.asConfig(), userRegistrar, authenticationEvent, ldapRealm); LdapAuthenticator.Context authenticationContext = new LdapAuthenticator.Context(LOGIN, PASSWORD, request); when(ldapAuthenticator.doAuthenticate(refEq(authenticationContext))).thenReturn(success(SERVER_KEY)); LdapUsersProvider.Context expectedUserContext = new LdapUsersProvider.Context(SERVER_KEY, LOGIN, request); when(ldapUsersProvider.doGetUserDetails(refEq(expectedUserContext))).thenReturn(LDAP_USER_DETAILS_WITH_EMAIL); underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); UserIdentity identity = userRegistrar.getAuthenticatorParameters().getUserIdentity(); assertThat(userRegistrar.isAuthenticated()).isTrue(); assertThat(identity.getProviderLogin()).isEqualTo(LOGIN); assertThat(identity.getProviderId()).isNull(); assertThat(identity.getName()).isEqualTo("name"); assertThat(identity.getEmail()).isEqualTo("email"); assertThat(identity.shouldSyncGroups()).isFalse(); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void authenticate_with_ldap() { executeAuthenticate(LDAP_USER_DETAILS_WITH_EMAIL); IdentityProvider provider = userRegistrar.getAuthenticatorParameters().getProvider(); assertThat(userRegistrar.isAuthenticated()).isTrue(); assertThat(provider.getKey()).isEqualTo(EXPECTED_EXTERNAL_PROVIDER_ID); assertThat(provider.getName()).isEqualTo(EXPECTED_EXTERNAL_PROVIDER_ID); assertThat(provider.getDisplay()).isNull(); assertThat(provider.isEnabled()).isTrue(); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void login_is_used_when_no_name_provided() { LdapUserDetails userDetails = new LdapUserDetails(); userDetails.setEmail("email"); executeAuthenticate(userDetails); assertThat(userRegistrar.getAuthenticatorParameters().getProvider().getName()).isEqualTo(EXPECTED_EXTERNAL_PROVIDER_ID); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void authenticate_with_group_sync() { LdapGroupsProvider.Context expectedGroupContext = new LdapGroupsProvider.Context(SERVER_KEY, LOGIN, request); when(ldapGroupsProvider.doGetGroups(refEq(expectedGroupContext))).thenReturn(asList("group1", "group2")); executeAuthenticate(LDAP_USER_DETAILS); assertThat(userRegistrar.isAuthenticated()).isTrue(); assertThat(userRegistrar.getAuthenticatorParameters().getUserIdentity().shouldSyncGroups()).isTrue(); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void use_login_if_user_details_contains_no_name() { LdapUserDetails userDetails = new LdapUserDetails(); userDetails.setName(null); executeAuthenticate(userDetails); assertThat(userRegistrar.isAuthenticated()).isTrue(); assertThat(userRegistrar.getAuthenticatorParameters().getUserIdentity().getName()).isEqualTo(LOGIN); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void use_downcase_login() { settings.setProperty("sonar.authenticator.downcase", true); mockLdapAuthentication(LOGIN.toLowerCase()); mockLdapUserDetailsRetrieval(LOGIN.toLowerCase(), LDAP_USER_DETAILS); underTest.authenticate(new Credentials(LOGIN.toLowerCase(), PASSWORD), request, BASIC); assertThat(userRegistrar.isAuthenticated()).isTrue(); assertThat(userRegistrar.getAuthenticatorParameters().getUserIdentity().getProviderLogin()).isEqualTo("login"); verify(authenticationEvent).loginSuccess(request, "login", Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void does_not_user_downcase_login() { settings.setProperty("sonar.authenticator.downcase", false); mockLdapAuthentication("LoGiN"); mockLdapUserDetailsRetrieval("LoGiN", LDAP_USER_DETAILS); underTest.authenticate(new Credentials("LoGiN", PASSWORD), request, BASIC); assertThat(userRegistrar.isAuthenticated()).isTrue(); assertThat(userRegistrar.getAuthenticatorParameters().getUserIdentity().getProviderLogin()).isEqualTo("LoGiN"); verify(authenticationEvent).loginSuccess(request, "LoGiN", Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)); } @Test public void fail_to_authenticate_when_user_details_are_null() { assertThatThrownBy(() -> executeAuthenticate(null)) .hasMessage("No user details") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)) .hasFieldOrPropertyWithValue("login", LOGIN); verifyNoInteractions(authenticationEvent); } @Test public void fail_to_authenticate_when_external_authentication_fails() { LdapAuthenticator.Context authenticationContext = new LdapAuthenticator.Context(LOGIN, PASSWORD, request); when(ldapAuthenticator.doAuthenticate(refEq(authenticationContext))).thenReturn(failed()); Credentials credentials = new Credentials(LOGIN, PASSWORD); assertThatThrownBy(() -> underTest.authenticate(credentials, request, BASIC)) .hasMessage("Realm returned authenticate=false") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.realm(BASIC, LDAP_SECURITY_REALM_NAME)) .hasFieldOrPropertyWithValue("login", LOGIN); verifyNoInteractions(ldapUsersProvider); verifyNoInteractions(authenticationEvent); } @Test public void fail_to_authenticate_when_any_exception_is_thrown() { String expectedMessage = "emulating exception in doAuthenticate"; doThrow(new IllegalArgumentException(expectedMessage)).when(ldapAuthenticator).doAuthenticate(any(LdapAuthenticator.Context.class)); Credentials credentials = new Credentials(LOGIN, PASSWORD); assertThatThrownBy(() -> underTest.authenticate(credentials, request, SONARQUBE_TOKEN)) .hasMessage(expectedMessage) .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", Source.realm(SONARQUBE_TOKEN, LDAP_SECURITY_REALM_NAME)) .hasFieldOrPropertyWithValue("login", LOGIN); verifyNoInteractions(ldapUsersProvider); verifyNoInteractions(authenticationEvent); } @Test public void return_empty_user_when_ldap_not_activated() { reset(ldapRealm); when(ldapRealm.isLdapAuthActivated()).thenReturn(false); underTest = new LdapCredentialsAuthentication(settings.asConfig(), userRegistrar, authenticationEvent, ldapRealm); assertThat(underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)).isEmpty(); verifyNoInteractions(authenticationEvent); } private void executeAuthenticate(@Nullable LdapUserDetails userDetails) { mockLdapAuthentication(LOGIN); mockLdapUserDetailsRetrieval(LOGIN, userDetails); underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); } private void mockLdapAuthentication(String login) { LdapAuthenticator.Context authenticationContext = new LdapAuthenticator.Context(login, PASSWORD, request); when(ldapAuthenticator.doAuthenticate(refEq(authenticationContext))).thenReturn(success(SERVER_KEY)); } private void mockLdapUserDetailsRetrieval(String login, @Nullable LdapUserDetails userDetails) { LdapUsersProvider.Context expectedUserContext = new LdapUsersProvider.Context(SERVER_KEY, login, request); when(ldapUsersProvider.doGetUserDetails(refEq(expectedUserContext))).thenReturn(userDetails); } }
12,690
42.313993
136
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/LogOAuthWarningTest.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; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.testfixtures.log.LogTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LogOAuthWarningTest { @Rule public LogTester logTester = new LogTester(); private Server server = mock(Server.class); @Test public void log_warning_at_startup_if_non_secured_base_url_and_oauth_is_installed() { when(server.getPublicRootUrl()).thenReturn("http://mydomain.com"); LogOAuthWarning underTest = new LogOAuthWarning(server, new OAuth2IdentityProvider[1]); underTest.start(); assertThat(logTester.logs(Level.WARN)).containsOnly("For security reasons, OAuth authentication should use HTTPS. You should set the property 'Administration > Configuration > Server base URL' to a HTTPS URL."); underTest.stop(); } @Test public void do_not_log_warning_at_startup_if_secured_base_url_and_oauth_is_installed() { when(server.getPublicRootUrl()).thenReturn("https://mydomain.com"); LogOAuthWarning underTest = new LogOAuthWarning(server, new OAuth2IdentityProvider[1]); underTest.start(); assertThat(logTester.logs(Level.WARN)).isEmpty(); underTest.stop(); } @Test public void do_not_log_warning_at_startup_if_non_secured_base_url_but_oauth_is_not_installed() { when(server.getPublicRootUrl()).thenReturn("http://mydomain.com"); LogOAuthWarning underTest = new LogOAuthWarning(server); underTest.start(); assertThat(logTester.logs(Level.WARN)).isEmpty(); underTest.stop(); } }
2,645
31.666667
215
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2AuthenticationParametersImplTest.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; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.server.http.JavaxHttpRequest; 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.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class OAuth2AuthenticationParametersImplTest { private static final String AUTHENTICATION_COOKIE_NAME = "AUTH-PARAMS"; private final ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class); private final HttpResponse response = mock(HttpResponse.class); private final HttpRequest request = mock(HttpRequest.class); private final OAuth2AuthenticationParameters underTest = new OAuth2AuthenticationParametersImpl(); @Before public void setUp() { when(request.getContextPath()).thenReturn(""); } @Test public void init_create_cookie() { when(request.getParameter("return_to")).thenReturn("/admin/settings"); underTest.init(request, response); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie cookie = cookieArgumentCaptor.getValue(); assertThat(cookie.getName()).isEqualTo(AUTHENTICATION_COOKIE_NAME); assertThat(cookie.getValue()).isNotEmpty(); assertThat(cookie.getPath()).isEqualTo("/"); assertThat(cookie.isHttpOnly()).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(300); assertThat(cookie.isSecure()).isFalse(); } @Test public void init_does_not_create_cookie_when_no_parameter() { underTest.init(request, response); verify(response, never()).addCookie(any(Cookie.class)); } @Test public void init_does_not_create_cookie_when_parameters_are_empty() { when(request.getParameter("return_to")).thenReturn(""); when(request.getParameter("allowEmailShift")).thenReturn(""); underTest.init(request, response); verify(response, never()).addCookie(any(Cookie.class)); } @Test public void init_does_not_create_cookie_when_parameters_are_null() { when(request.getParameter("return_to")).thenReturn(null); when(request.getParameter("allowEmailShift")).thenReturn(null); underTest.init(request, response); verify(response, never()).addCookie(any(Cookie.class)); } @Test @DataProvider({"http://example.com", "/\t/example.com", "//local_file", "/\\local_file", "something_else"}) public void get_return_to_is_not_set_when_not_local(String url) { when(request.getParameter("return_to")).thenReturn(url); assertThat(underTest.getReturnTo(request)).isEmpty(); } @Test public void get_return_to_parameter() { when(request.getCookies()).thenReturn(new Cookie[] {wrapCookie(AUTHENTICATION_COOKIE_NAME, "{\"return_to\":\"/admin/settings\"}")}); Optional<String> redirection = underTest.getReturnTo(request); assertThat(redirection).contains("/admin/settings"); } @Test public void get_return_to_is_empty_when_no_cookie() { when(request.getCookies()).thenReturn(new Cookie[] {}); Optional<String> redirection = underTest.getReturnTo(request); assertThat(redirection).isEmpty(); } @Test public void get_return_to_is_empty_when_no_value() { when(request.getCookies()).thenReturn(new Cookie[] {wrapCookie(AUTHENTICATION_COOKIE_NAME, "{}")}); Optional<String> redirection = underTest.getReturnTo(request); assertThat(redirection).isEmpty(); } @Test public void delete() { when(request.getCookies()).thenReturn(new Cookie[] {wrapCookie(AUTHENTICATION_COOKIE_NAME, "{\"return_to\":\"/admin/settings\"}")}); underTest.delete(request, response); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie updatedCookie = cookieArgumentCaptor.getValue(); assertThat(updatedCookie.getName()).isEqualTo(AUTHENTICATION_COOKIE_NAME); assertThat(updatedCookie.getValue()).isNull(); assertThat(updatedCookie.getPath()).isEqualTo("/"); assertThat(updatedCookie.getMaxAge()).isZero(); } private JavaxHttpRequest.JavaxCookie wrapCookie(String name, String value) { return new JavaxHttpRequest.JavaxCookie(new javax.servlet.http.Cookie(name, value)); } }
5,485
35.092105
136
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2CallbackFilterTest.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; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.slf4j.event.Level; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.authentication.UnauthorizedException; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.web.FilterChain; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.user.ThreadLocalUserSession; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; 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.server.authentication.event.AuthenticationEvent.Source; public class OAuth2CallbackFilterTest { private static final String OAUTH2_PROVIDER_KEY = "github"; private static final String LOGIN = "foo"; @Rule public LogTester logTester = new LogTester(); @Rule public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule(); private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class); private HttpRequest request = mock(HttpRequest.class); private HttpResponse response = mock(HttpResponse.class); private FilterChain chain = mock(FilterChain.class); private FakeOAuth2IdentityProvider oAuth2IdentityProvider = new WellbehaveFakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true, LOGIN); private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class); private OAuth2AuthenticationParameters oAuthRedirection = mock(OAuth2AuthenticationParameters.class); private ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class); private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class); private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class); private OAuth2CallbackFilter underTest = new OAuth2CallbackFilter(identityProviderRepository, oAuth2ContextFactory, authenticationEvent, oAuthRedirection, threadLocalUserSession); @Before public void setUp() { when(oAuth2ContextFactory.newCallback(request, response, oAuth2IdentityProvider)).thenReturn(mock(OAuth2IdentityProvider.CallbackContext.class)); when(request.getContextPath()).thenReturn(""); } @Test public void do_get_pattern() { assertThat(underTest.doGetPattern()).isNotNull(); } @Test public void do_filter_with_context() { when(request.getContextPath()).thenReturn("/sonarqube"); when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider); when(threadLocalUserSession.hasSession()).thenReturn(true); when(threadLocalUserSession.getLogin()).thenReturn(LOGIN); underTest.doFilter(request, response, chain); assertCallbackCalled(oAuth2IdentityProvider); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider)); } @Test public void do_filter_with_context_no_log_if_provider_did_not_call_authenticate_on_context() { when(request.getContextPath()).thenReturn("/sonarqube"); when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY); FakeOAuth2IdentityProvider identityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); assertCallbackCalled(identityProvider); verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture()); AuthenticationException authenticationException = authenticationExceptionCaptor.getValue(); assertThat(authenticationException).hasMessage("Plugin did not call authenticate"); assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider)); assertThat(authenticationException.getLogin()).isNull(); assertThat(authenticationException.getPublicMessage()).isNull(); } @Test public void do_filter_on_auth2_identity_provider() { when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider); when(threadLocalUserSession.hasSession()).thenReturn(true); when(threadLocalUserSession.getLogin()).thenReturn(LOGIN); underTest.doFilter(request, response, chain); assertCallbackCalled(oAuth2IdentityProvider); verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider)); } @Test public void fail_on_not_oauth2_provider() throws Exception { String providerKey = "openid"; when(request.getRequestURI()).thenReturn("/oauth2/callback/" + providerKey); identityProviderRepository.addIdentityProvider(new FakeBasicIdentityProvider(providerKey, true)); underTest.doFilter(request, response, chain); assertError("Not an OAuth2IdentityProvider: class org.sonar.server.authentication.FakeBasicIdentityProvider"); verifyNoInteractions(authenticationEvent); } @Test public void fail_on_disabled_provider() throws Exception { when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY); identityProviderRepository.addIdentityProvider(new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, false)); underTest.doFilter(request, response, chain); assertError("Failed to retrieve IdentityProvider for key 'github'"); verifyNoInteractions(authenticationEvent); } @Test public void redirect_when_failing_because_of_UnauthorizedExceptionException() throws Exception { FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider(); when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sessions/unauthorized"); verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture()); AuthenticationException authenticationException = authenticationExceptionCaptor.getValue(); assertThat(authenticationException).hasMessage("Email john@email.com is already used"); assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider)); assertThat(authenticationException.getLogin()).isNull(); assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used"); verify(oAuthRedirection).delete(request, response); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie cookie = cookieArgumentCaptor.getValue(); assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR"); assertThat(cookie.getValue()).isEqualTo("Email%20john%40email.com%20is%20already%20used"); assertThat(cookie.getPath()).isEqualTo("/"); assertThat(cookie.isHttpOnly()).isFalse(); assertThat(cookie.getMaxAge()).isEqualTo(300); assertThat(cookie.isSecure()).isFalse(); } @Test public void redirect_with_context_path_when_failing_because_of_UnauthorizedExceptionException() throws Exception { when(request.getContextPath()).thenReturn("/sonarqube"); FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider(); when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/sessions/unauthorized"); verify(oAuthRedirection).delete(request, response); } @Test public void redirect_when_failing_because_of_Exception() throws Exception { FailWithIllegalStateException identityProvider = new FailWithIllegalStateException(); when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sessions/unauthorized"); assertThat(logTester.logs(Level.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'"); verify(oAuthRedirection).delete(request, response); } @Test public void redirect_with_context_when_failing_because_of_Exception() throws Exception { when(request.getContextPath()).thenReturn("/sonarqube"); FailWithIllegalStateException identityProvider = new FailWithIllegalStateException(); when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey()); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/sessions/unauthorized"); } @Test public void fail_when_no_oauth2_provider_provided() throws Exception { when(request.getRequestURI()).thenReturn("/oauth2/callback"); underTest.doFilter(request, response, chain); assertError("No provider key found in URI"); verifyNoInteractions(authenticationEvent); } private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) { assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue(); } private void assertError(String expectedError) throws Exception { assertThat(logTester.logs(Level.WARN)).contains(expectedError); verify(response).sendRedirect("/sessions/unauthorized"); assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse(); } private static class FailWithUnauthorizedExceptionIdProvider extends FailingIdentityProvider { @Override public void callback(CallbackContext context) { throw new UnauthorizedException("Email john@email.com is already used"); } } private static class FailWithIllegalStateException extends FailingIdentityProvider { @Override public void callback(CallbackContext context) { throw new IllegalStateException("Failure !"); } } private static abstract class FailingIdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider { FailingIdentityProvider() { this.setKey("failing"); this.setName("Failing"); this.setEnabled(true); } @Override public void init(InitContext context) { // Nothing to do } } /** * An extension of {@link FakeOAuth2IdentityProvider} that actually call {@link org.sonar.api.server.authentication.OAuth2IdentityProvider.CallbackContext#authenticate(UserIdentity)}. */ private static class WellbehaveFakeOAuth2IdentityProvider extends FakeOAuth2IdentityProvider { private final String login; public WellbehaveFakeOAuth2IdentityProvider(String key, boolean enabled, String login) { super(key, enabled); this.login = login; } @Override public void callback(CallbackContext context) { super.callback(context); context.authenticate(UserIdentity.builder() .setProviderLogin(login) .setEmail(login + "@toto.com") .setName("name of " + login) .build()); } } }
12,725
43.1875
185
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2ContextFactoryTest.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; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.db.user.UserDto; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.user.TestUserSessionFactory; import org.sonar.server.user.ThreadLocalUserSession; import org.sonar.server.user.UserSession; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class OAuth2ContextFactoryTest { private static final String PROVIDER_KEY = "github"; private static final String SECURED_PUBLIC_ROOT_URL = "https://mydomain.com"; private static final String PROVIDER_NAME = "provider name"; private static final UserIdentity USER_IDENTITY = UserIdentity.builder() .setProviderId("ABCD") .setProviderLogin("johndoo") .setName("John") .setEmail("john@email.com") .build(); private final ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class); private final TestUserRegistrar userIdentityAuthenticator = new TestUserRegistrar(); private final Server server = mock(Server.class); private final OAuthCsrfVerifier csrfVerifier = mock(OAuthCsrfVerifier.class); private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class); private final TestUserSessionFactory userSessionFactory = TestUserSessionFactory.standalone(); private final OAuth2AuthenticationParameters oAuthParameters = mock(OAuth2AuthenticationParameters.class); private final HttpServletRequest request = mock(HttpServletRequest.class); private final HttpServletResponse response = mock(HttpServletResponse.class); private final HttpRequest httpRequest = new JavaxHttpRequest(request); private final HttpResponse httpResponse = new JavaxHttpResponse(response); private final OAuth2IdentityProvider identityProvider = mock(OAuth2IdentityProvider.class); private final OAuth2ContextFactory underTest = new OAuth2ContextFactory(threadLocalUserSession, userIdentityAuthenticator, server, csrfVerifier, jwtHttpHandler, userSessionFactory, oAuthParameters); @Before public void setUp() { when(identityProvider.getKey()).thenReturn(PROVIDER_KEY); when(identityProvider.getName()).thenReturn(PROVIDER_NAME); } @Test public void create_context() { when(server.getPublicRootUrl()).thenReturn(SECURED_PUBLIC_ROOT_URL); OAuth2IdentityProvider.InitContext context = newInitContext(); assertThat(context.getHttpRequest()).isEqualTo(httpRequest); assertThat(context.getHttpResponse()).isEqualTo(httpResponse); assertThat(context.getRequest()).isEqualTo(request); assertThat(context.getResponse()).isEqualTo(response); assertThat(context.getCallbackUrl()).isEqualTo("https://mydomain.com/oauth2/callback/github"); } @Test public void generate_csrf_state() { OAuth2IdentityProvider.InitContext context = newInitContext(); context.generateCsrfState(); verify(csrfVerifier).generateState(httpRequest, httpResponse); } @Test public void redirect_to() throws Exception { OAuth2IdentityProvider.InitContext context = newInitContext(); context.redirectTo("/test"); verify(response).sendRedirect("/test"); } @Test public void create_callback() { when(server.getPublicRootUrl()).thenReturn(SECURED_PUBLIC_ROOT_URL); OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); assertThat(callback.getHttpRequest()).isEqualTo(httpRequest); assertThat(callback.getHttpResponse()).isEqualTo(httpResponse); assertThat(callback.getCallbackUrl()).isEqualTo("https://mydomain.com/oauth2/callback/github"); } @Test public void authenticate() { OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.authenticate(USER_IDENTITY); assertThat(userIdentityAuthenticator.isAuthenticated()).isTrue(); verify(threadLocalUserSession).set(any(UserSession.class)); ArgumentCaptor<UserDto> userArgumentCaptor = ArgumentCaptor.forClass(UserDto.class); verify(jwtHttpHandler).generateToken(userArgumentCaptor.capture(), eq(httpRequest), eq(httpResponse)); assertThat(userArgumentCaptor.getValue().getExternalId()).isEqualTo(USER_IDENTITY.getProviderId()); assertThat(userArgumentCaptor.getValue().getExternalLogin()).isEqualTo(USER_IDENTITY.getProviderLogin()); assertThat(userArgumentCaptor.getValue().getExternalIdentityProvider()).isEqualTo(PROVIDER_KEY); } @Test public void redirect_to_home() throws Exception { when(server.getContextPath()).thenReturn(""); when(oAuthParameters.getReturnTo(httpRequest)).thenReturn(Optional.empty()); OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.redirectToRequestedPage(); verify(response).sendRedirect("/"); } @Test public void redirect_to_home_with_context() throws Exception { when(server.getContextPath()).thenReturn("/sonarqube"); when(oAuthParameters.getReturnTo(httpRequest)).thenReturn(Optional.empty()); OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.redirectToRequestedPage(); verify(response).sendRedirect("/sonarqube/"); } @Test public void redirect_to_requested_page() throws Exception { when(oAuthParameters.getReturnTo(httpRequest)).thenReturn(Optional.of("/admin/settings")); when(server.getContextPath()).thenReturn(""); OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.redirectToRequestedPage(); verify(response).sendRedirect("/admin/settings"); } @Test public void redirect_to_requested_page_does_not_need_context() throws Exception { when(oAuthParameters.getReturnTo(httpRequest)).thenReturn(Optional.of("/admin/settings")); when(server.getContextPath()).thenReturn("/other"); OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.redirectToRequestedPage(); verify(response).sendRedirect("/admin/settings"); } @Test public void verify_csrf_state() { OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.verifyCsrfState(); verify(csrfVerifier).verifyState(httpRequest, httpResponse, identityProvider); } @Test public void delete_oauth2_parameters_during_redirection() { when(oAuthParameters.getReturnTo(httpRequest)).thenReturn(Optional.of("/admin/settings")); when(server.getContextPath()).thenReturn(""); OAuth2IdentityProvider.CallbackContext callback = newCallbackContext(); callback.redirectToRequestedPage(); verify(oAuthParameters).delete(httpRequest, httpResponse); } private OAuth2IdentityProvider.InitContext newInitContext() { return underTest.newContext(httpRequest, httpResponse, identityProvider); } private OAuth2IdentityProvider.CallbackContext newCallbackContext() { return underTest.newCallback(httpRequest, httpResponse, identityProvider); } }
8,424
38.00463
162
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuthCsrfVerifierTest.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; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.http.JavaxHttpRequest; import static org.apache.commons.codec.digest.DigestUtils.sha1Hex; import static org.apache.commons.codec.digest.DigestUtils.sha256Hex; 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.verify; import static org.mockito.Mockito.when; public class OAuthCsrfVerifierTest { private static final String PROVIDER_NAME = "provider name"; private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class); private OAuth2IdentityProvider identityProvider = mock(OAuth2IdentityProvider.class); private Server server = mock(Server.class); private HttpResponse response = mock(HttpResponse.class); private HttpRequest request = mock(HttpRequest.class); private OAuthCsrfVerifier underTest = new OAuthCsrfVerifier(); @Before public void setUp() { when(server.getContextPath()).thenReturn(""); when(identityProvider.getName()).thenReturn(PROVIDER_NAME); } @Test public void generate_state() { String state = underTest.generateState(request, response); assertThat(state).isNotEmpty(); verify(response).addCookie(cookieArgumentCaptor.capture()); verifyCookie(cookieArgumentCaptor.getValue()); } @Test public void verify_state() { String state = "state"; when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie("OAUTHSTATE", sha256Hex(state))}); when(request.getParameter("aStateParameter")).thenReturn(state); underTest.verifyState(request, response, identityProvider, "aStateParameter"); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie updatedCookie = cookieArgumentCaptor.getValue(); assertThat(updatedCookie.getName()).isEqualTo("OAUTHSTATE"); assertThat(updatedCookie.getValue()).isNull(); assertThat(updatedCookie.getPath()).isEqualTo("/"); assertThat(updatedCookie.getMaxAge()).isZero(); } @Test public void verify_state_using_default_state_parameter() { String state = "state"; when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie("OAUTHSTATE", sha256Hex(state))}); when(request.getParameter("state")).thenReturn(state); underTest.verifyState(request, response, identityProvider); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie updatedCookie = cookieArgumentCaptor.getValue(); assertThat(updatedCookie.getName()).isEqualTo("OAUTHSTATE"); assertThat(updatedCookie.getValue()).isNull(); assertThat(updatedCookie.getPath()).isEqualTo("/"); assertThat(updatedCookie.getMaxAge()).isZero(); } @Test public void fail_with_AuthenticationException_when_state_cookie_is_not_the_same_as_state_parameter() { when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie("OAUTHSTATE", sha1Hex("state"))}); when(request.getParameter("state")).thenReturn("other value"); assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) .hasMessage("CSRF state value is invalid") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } @Test public void fail_with_AuthenticationException_when_state_cookie_is_null() { when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie("OAUTHSTATE", null)}); when(request.getParameter("state")).thenReturn("state"); assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) .hasMessage("CSRF state value is invalid") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } @Test public void fail_with_AuthenticationException_when_state_parameter_is_empty() { when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie("OAUTHSTATE", sha1Hex("state"))}); when(request.getParameter("state")).thenReturn(""); assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) .hasMessage("CSRF state value is invalid") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } @Test public void fail_with_AuthenticationException_when_cookie_is_missing() { when(request.getCookies()).thenReturn(new Cookie[]{}); assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) .hasMessage("Cookie 'OAUTHSTATE' is missing") .isInstanceOf(AuthenticationException.class) .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } private void verifyCookie(Cookie cookie) { assertThat(cookie.getName()).isEqualTo("OAUTHSTATE"); assertThat(cookie.getValue()).isNotEmpty(); assertThat(cookie.getPath()).isEqualTo("/"); assertThat(cookie.isHttpOnly()).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(-1); assertThat(cookie.isSecure()).isFalse(); } private JavaxHttpRequest.JavaxCookie wrapCookie(String name, String value) { return new JavaxHttpRequest.JavaxCookie(new javax.servlet.http.Cookie(name, value)); } }
6,660
41.158228
104
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/PBKDF2FunctionTest.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; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PBKDF2FunctionTest { private static final int GENERATION_ITERATIONS = 1000; private final CredentialsLocalAuthentication.PBKDF2Function pbkdf2Function = new CredentialsLocalAuthentication.PBKDF2Function(GENERATION_ITERATIONS); @Test public void encryptPassword_returnsCorrectEncryptedPassword() { String encryptedPassword = pbkdf2Function.encryptPassword("salt", "test_password"); assertThat(encryptedPassword) .isEqualTo("%d$%s", GENERATION_ITERATIONS, "Yz4QzaROW6N9dqr47NtsDgVJERKC3gTec4rMHonb885IVvTb6OYelaAvMXxoc5QT+4SAjiEmDKaUa2cAC9Ne8Q=="); } }
1,560
38.025
152
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/RequestAuthenticatorImplTest.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; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; import org.sonar.server.tester.AnonymousMockUserSession; import org.sonar.server.tester.MockUserSession; import org.sonar.server.user.GithubWebhookUserSession; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserSessionFactory; import org.sonar.server.usertoken.UserTokenAuthentication; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.user.TokenType.USER_TOKEN; import static org.sonar.db.user.UserTesting.newUserDto; public class RequestAuthenticatorImplTest { private static final UserDto A_USER = newUserDto(); private static final UserTokenDto A_USER_TOKEN = mockUserTokenDto(A_USER); private final HttpRequest request = mock(HttpRequest.class); private final HttpResponse response = mock(HttpResponse.class); private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class); private final BasicAuthentication basicAuthentication = mock(BasicAuthentication.class); private final UserTokenAuthentication userTokenAuthentication = mock(UserTokenAuthentication.class); private final GithubWebhookAuthentication githubWebhookAuthentication = mock(GithubWebhookAuthentication.class); private final HttpHeadersAuthentication httpHeadersAuthentication = mock(HttpHeadersAuthentication.class); private final UserSessionFactory sessionFactory = mock(UserSessionFactory.class); private final RequestAuthenticator underTest = new RequestAuthenticatorImpl(jwtHttpHandler, basicAuthentication, userTokenAuthentication, httpHeadersAuthentication, githubWebhookAuthentication, sessionFactory); private final GithubWebhookUserSession githubWebhookMockUserSession = mock(GithubWebhookUserSession.class); @Before public void setUp() { when(sessionFactory.create(A_USER)).thenReturn(new MockUserSession(A_USER)); when(sessionFactory.create(A_USER, A_USER_TOKEN)).thenReturn(new MockUserSession(A_USER)); when(sessionFactory.createAnonymous()).thenReturn(new AnonymousMockUserSession()); when(sessionFactory.createGithubWebhookUserSession()).thenReturn(githubWebhookMockUserSession); } @Test public void authenticate_from_jwt_token() { when(httpHeadersAuthentication.authenticate(request, response)).thenReturn(Optional.empty()); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.of(A_USER)); assertThat(underTest.authenticate(request, response).getUuid()).isEqualTo(A_USER.getUuid()); verify(response, never()).setStatus(anyInt()); } @Test public void authenticate_from_githubWebhook() { when(httpHeadersAuthentication.authenticate(request, response)).thenReturn(Optional.empty()); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); when(githubWebhookAuthentication.authenticate(request)).thenReturn(Optional.of(UserAuthResult.withGithubWebhook())); assertThat(underTest.authenticate(request, response)).isInstanceOf(GithubWebhookUserSession.class); verify(response, never()).setStatus(anyInt()); } @Test public void authenticate_from_basic_header() { when(basicAuthentication.authenticate(request)).thenReturn(Optional.of(A_USER)); when(httpHeadersAuthentication.authenticate(request, response)).thenReturn(Optional.empty()); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); assertThat(underTest.authenticate(request, response).getUuid()).isEqualTo(A_USER.getUuid()); verify(jwtHttpHandler).validateToken(request, response); verify(basicAuthentication).authenticate(request); verify(response, never()).setStatus(anyInt()); } @Test public void authenticate_from_basic_token() { when(request.getHeader("Authorization")).thenReturn("Basic dGVzdDo="); when(userTokenAuthentication.getUserToken("test")).thenReturn(A_USER_TOKEN); when(userTokenAuthentication.authenticate(request)).thenReturn(Optional.of(new UserAuthResult(A_USER, A_USER_TOKEN, UserAuthResult.AuthType.TOKEN))); when(httpHeadersAuthentication.authenticate(request, response)).thenReturn(Optional.empty()); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); assertThat(underTest.authenticate(request, response).getUuid()).isEqualTo(A_USER.getUuid()); verify(jwtHttpHandler).validateToken(request, response); verify(userTokenAuthentication).authenticate(request); verify(response, never()).setStatus(anyInt()); } @Test public void authenticate_from_sso() { when(httpHeadersAuthentication.authenticate(request, response)).thenReturn(Optional.of(A_USER)); when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); assertThat(underTest.authenticate(request, response).getUuid()).isEqualTo(A_USER.getUuid()); verify(httpHeadersAuthentication).authenticate(request, response); verify(jwtHttpHandler, never()).validateToken(request, response); verify(response, never()).setStatus(anyInt()); } @Test public void return_empty_if_not_authenticated() { when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.empty()); when(httpHeadersAuthentication.authenticate(request, response)).thenReturn(Optional.empty()); when(basicAuthentication.authenticate(request)).thenReturn(Optional.empty()); UserSession session = underTest.authenticate(request, response); assertThat(session.isLoggedIn()).isFalse(); assertThat(session.getUuid()).isNull(); verify(response, never()).setStatus(anyInt()); } private static UserTokenDto mockUserTokenDto(UserDto userDto) { UserTokenDto userTokenDto = new UserTokenDto(); userTokenDto.setType(USER_TOKEN.name()); userTokenDto.setName("User Token"); userTokenDto.setUserUuid(userDto.getUuid()); return userTokenDto; } }
7,147
46.337748
166
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/ResetPasswordFilterTest.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; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import org.sonar.server.user.ThreadLocalUserSession; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class ResetPasswordFilterTest { private final HttpRequest request = mock(HttpRequest.class); private final HttpResponse response = mock(HttpResponse.class); private final FilterChain chain = mock(FilterChain.class); private final ThreadLocalUserSession session = mock(ThreadLocalUserSession.class); private final ResetPasswordFilter underTest = new ResetPasswordFilter(session); @Before public void before() { // set URI to valid for redirect when(request.getRequestURI()).thenReturn("/"); when(request.getContextPath()).thenReturn(""); // set reset password conditions when(session.hasSession()).thenReturn(true); when(session.isLoggedIn()).thenReturn(true); when(session.shouldResetPassword()).thenReturn(true); } @Test public void verify_other_methods() { underTest.init(); underTest.destroy(); verifyNoInteractions(request, response, chain, session); } @Test public void redirect_if_reset_password_set() throws Exception { underTest.doFilter(request, response, chain); verify(response).sendRedirect("/account/reset_password"); } @Test public void redirect_if_reset_password_set_and_web_context_configured() throws Exception { when(request.getContextPath()).thenReturn("/sonarqube"); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/account/reset_password"); } @Test public void redirect_if_request_uri_ends_with_slash() throws Exception { when(request.getRequestURI()).thenReturn("/projects/"); when(request.getContextPath()).thenReturn("/sonarqube"); underTest.doFilter(request, response, chain); verify(response).sendRedirect("/sonarqube/account/reset_password"); } @Test public void do_not_redirect_if_no_session() throws Exception { when(session.hasSession()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test public void do_not_redirect_if_not_logged_in() throws Exception { when(session.isLoggedIn()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test public void do_not_redirect_if_reset_password_not_set() throws Exception { when(session.shouldResetPassword()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); } @Test @UseDataProvider("skipped_urls") public void doGetPattern_verify(String urltoSkip) throws Exception { when(request.getRequestURI()).thenReturn(urltoSkip); when(request.getContextPath()).thenReturn(""); underTest.doGetPattern().matches(urltoSkip); verify(response, never()).sendRedirect(any()); } @DataProvider public static Object[][] skipped_urls() { return new Object[][] { {"/batch/index"}, {"/batch/file"}, {"/api/issues"}, {"/api/issues/"}, {"/api/*"}, {"/account/reset_password"}, }; } }
4,677
31.041096
92
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/SafeModeUserSessionTest.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; import org.junit.Test; import org.sonar.api.web.UserRole; import org.sonar.db.permission.GlobalPermission; import static org.assertj.core.api.Assertions.assertThat; public class SafeModeUserSessionTest { private SafeModeUserSession underTest = new SafeModeUserSession(); @Test public void session_is_anonymous() { assertThat(underTest.getLogin()).isNull(); assertThat(underTest.getUuid()).isNull(); assertThat(underTest.isLoggedIn()).isFalse(); assertThat(underTest.shouldResetPassword()).isFalse(); assertThat(underTest.getName()).isNull(); assertThat(underTest.getGroups()).isEmpty(); assertThat(underTest.isActive()).isFalse(); } @Test public void session_has_no_permissions() { assertThat(underTest.shouldResetPassword()).isFalse(); assertThat(underTest.isSystemAdministrator()).isFalse(); assertThat(underTest.hasPermissionImpl(GlobalPermission.ADMINISTER)).isFalse(); assertThat(underTest.hasEntityUuidPermission(UserRole.USER, "foo")).isFalse(); assertThat(underTest.hasChildProjectsPermission(UserRole.USER, "foo")).isFalse(); assertThat(underTest.hasPortfolioChildProjectsPermission(UserRole.USER, "foo")).isFalse(); } }
2,086
38.377358
94
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/SamlValidationCspHeadersTest.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; import org.junit.Test; import org.sonar.api.server.http.HttpResponse; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.server.authentication.SamlValidationCspHeaders.addCspHeadersWithNonceToResponse; public class SamlValidationCspHeadersTest { @Test public void addCspHeadersWithNonceToResponse_whenCalled_shouldAddNonceToCspHeaders() { HttpResponse httpServletResponse = mock(HttpResponse.class); String nonce = addCspHeadersWithNonceToResponse(httpServletResponse); verify(httpServletResponse).setHeader(eq("Content-Security-Policy"), contains("script-src 'nonce-" + nonce + "'")); verify(httpServletResponse).setHeader(eq("X-Content-Security-Policy"), contains("script-src 'nonce-" + nonce + "'")); verify(httpServletResponse).setHeader(eq("X-WebKit-CSP"), contains("script-src 'nonce-" + nonce + "'")); } }
1,884
41.840909
121
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/SamlValidationRedirectionFilterTest.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; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.sonar.api.platform.Server; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.matches; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class SamlValidationRedirectionFilterTest { public static final List<String> CSP_HEADERS = List.of("Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP"); SamlValidationRedirectionFilter underTest; @Before public void setup() throws ServletException { Server server = mock(Server.class); doReturn("contextPath").when(server).getContextPath(); underTest = new SamlValidationRedirectionFilter(server); underTest.init(); } @Test public void do_get_pattern() { assertThat(underTest.doGetPattern().matches("/oauth2/callback/saml")).isTrue(); assertThat(underTest.doGetPattern().matches("/oauth2/callback/")).isFalse(); assertThat(underTest.doGetPattern().matches("/oauth2/callback/test")).isFalse(); assertThat(underTest.doGetPattern().matches("/oauth2/")).isFalse(); } @Test public void do_filter_validation_relay_state_with_csrfToken() throws IOException { HttpRequest servletRequest = mock(HttpRequest.class); HttpResponse servletResponse = mock(HttpResponse.class); FilterChain filterChain = mock(FilterChain.class); String validSample = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; when(servletRequest.getParameter(matches("SAMLResponse"))).thenReturn(validSample); when(servletRequest.getParameter(matches("RelayState"))).thenReturn("validation-query/CSRF_TOKEN"); when(servletRequest.getContextPath()).thenReturn("contextPath"); PrintWriter pw = mock(PrintWriter.class); when(servletResponse.getWriter()).thenReturn(pw); underTest.doFilter(servletRequest, servletResponse, filterChain); ArgumentCaptor<String> htmlProduced = ArgumentCaptor.forClass(String.class); verify(pw).print(htmlProduced.capture()); CSP_HEADERS.forEach(h -> verify(servletResponse).setHeader(eq(h), anyString())); assertThat(htmlProduced.getValue()).contains(validSample); assertThat(htmlProduced.getValue()).contains("action=\"contextPath/saml/validation\""); assertThat(htmlProduced.getValue()).contains("value=\"CSRF_TOKEN\""); } @Test public void do_filter_validation_relay_state_with_malicious_csrfToken() throws IOException { HttpRequest servletRequest = mock(HttpRequest.class); HttpResponse servletResponse = mock(HttpResponse.class); FilterChain filterChain = mock(FilterChain.class); String validSample = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; when(servletRequest.getParameter(matches("SAMLResponse"))).thenReturn(validSample); String maliciousToken = "test\"</input><script>*Malicious Token*</script><input value=\""; when(servletRequest.getParameter(matches("RelayState"))).thenReturn("validation-query/" + maliciousToken); PrintWriter pw = mock(PrintWriter.class); when(servletResponse.getWriter()).thenReturn(pw); underTest.doFilter(servletRequest, servletResponse, filterChain); ArgumentCaptor<String> htmlProduced = ArgumentCaptor.forClass(String.class); verify(pw).print(htmlProduced.capture()); CSP_HEADERS.forEach(h -> verify(servletResponse).setHeader(eq(h), anyString())); assertThat(htmlProduced.getValue()).contains(validSample); assertThat(htmlProduced.getValue()).doesNotContain("<script>/*Malicious Token*/</script>"); } @Test public void do_filter_validation_wrong_SAML_response() throws IOException { HttpRequest servletRequest = mock(HttpRequest.class); HttpResponse servletResponse = mock(HttpResponse.class); FilterChain filterChain = mock(FilterChain.class); String maliciousSaml = "test\"</input><script>/*hack website*/</script><input value=\""; when(servletRequest.getParameter(matches("SAMLResponse"))).thenReturn(maliciousSaml); when(servletRequest.getParameter(matches("RelayState"))).thenReturn("validation-query/CSRF_TOKEN"); PrintWriter pw = mock(PrintWriter.class); when(servletResponse.getWriter()).thenReturn(pw); underTest.doFilter(servletRequest, servletResponse, filterChain); ArgumentCaptor<String> htmlProduced = ArgumentCaptor.forClass(String.class); verify(pw).print(htmlProduced.capture()); CSP_HEADERS.forEach(h -> verify(servletResponse).setHeader(eq(h), anyString())); assertThat(htmlProduced.getValue()).doesNotContain("<script>/*hack website*/</script>"); assertThat(htmlProduced.getValue()).contains("action=\"contextPath/saml/validation\""); } @Test @UseDataProvider("invalidRelayStateValues") public void do_filter_invalid_relayState_values(String relayStateValue) throws IOException { HttpRequest servletRequest = mock(HttpRequest.class); HttpResponse servletResponse = mock(HttpResponse.class); FilterChain filterChain = mock(FilterChain.class); doReturn(relayStateValue).when(servletRequest).getParameter("RelayState"); underTest.doFilter(servletRequest, servletResponse, filterChain); verifyNoInteractions(servletResponse); } @Test public void extract_nonexistant_template() { assertThrows(IllegalStateException.class, () -> underTest.extractTemplate("not-there")); } @DataProvider public static Object[] invalidRelayStateValues() { return new Object[]{"random_query", "validation-query", null}; } }
7,218
42.487952
129
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/TestUserRegistrar.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; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; public class TestUserRegistrar implements UserRegistrar { private UserRegistration authenticatorParameters; @Override public UserDto register(UserRegistration registration) { this.authenticatorParameters = registration; String providerId = registration.getUserIdentity().getProviderId(); return UserTesting.newUserDto() .setLocal(false) .setExternalLogin(registration.getUserIdentity().getProviderLogin()) .setExternalId(providerId == null ? registration.getUserIdentity().getProviderLogin() : providerId) .setExternalIdentityProvider(registration.getProvider().getKey()); } boolean isAuthenticated() { return authenticatorParameters != null; } UserRegistration getAuthenticatorParameters() { return authenticatorParameters; } }
1,751
35.5
105
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/UserAuthResultTest.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; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class UserAuthResultTest { @Test public void withGithubWebhook_returnsCorrectUserAuthResult() { UserAuthResult userAuthResult = UserAuthResult.withGithubWebhook(); assertThat(userAuthResult.getAuthType()).isEqualTo(UserAuthResult.AuthType.GITHUB_WEBHOOK); assertThat(userAuthResult.getUserDto()).isNull(); assertThat(userAuthResult.getTokenDto()).isNull(); } }
1,349
35.486486
93
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventImplTest.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.event; import com.google.common.base.Joiner; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import static java.util.Arrays.asList; 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.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.event.AuthenticationEvent.Method; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; import static org.sonar.server.authentication.event.AuthenticationException.newBuilder; public class AuthenticationEventImplTest { private static final String LOGIN_129_CHARS = "012345678901234567890123456789012345678901234567890123456789" + "012345678901234567890123456789012345678901234567890123456789012345678"; @Rule public LogTester logTester = new LogTester(); private final AuthenticationEventImpl underTest = new AuthenticationEventImpl(); @Before public void setUp() { logTester.setLevel(LoggerLevel.DEBUG); } @Test public void login_success_fails_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); Source sso = Source.sso(); assertThatThrownBy(() -> underTest.loginSuccess(null, "login", sso)) .isInstanceOf(NullPointerException.class) .hasMessage("request can't be null"); } @Test public void login_success_fails_with_NPE_if_source_is_null() { logTester.setLevel(LoggerLevel.INFO); assertThatThrownBy(() -> underTest.loginSuccess(mock(HttpRequest.class), "login", null)) .isInstanceOf(NullPointerException.class) .hasMessage("source can't be null"); } @Test public void login_success_does_not_interact_with_request_if_log_level_is_above_DEBUG() { HttpRequest request = mock(HttpRequest.class); logTester.setLevel(LoggerLevel.INFO); underTest.loginSuccess(request, "login", Source.sso()); assertThat(logTester.logs()).isEmpty(); } @Test public void login_success_message_is_sanitized() { logTester.setLevel(LoggerLevel.DEBUG); underTest.loginSuccess(mockRequest("1.2.3.4"), "login with \n malicious line \r return", Source.sso()); assertThat(logTester.logs()).isNotEmpty() .contains("login success [method|SSO][provider|SSO|sso][IP|1.2.3.4|][login|login with _ malicious line _ return]"); } @Test public void login_success_creates_DEBUG_log_with_empty_login_if_login_argument_is_null() { underTest.loginSuccess(mockRequest(), null, Source.sso()); verifyLog("login success [method|SSO][provider|SSO|sso][IP||][login|]"); } @Test public void login_success_creates_DEBUG_log_with_method_provider_and_login() { underTest.loginSuccess(mockRequest(), "foo", Source.realm(Method.BASIC, "some provider name")); verifyLog("login success [method|BASIC][provider|REALM|some provider name][IP||][login|foo]"); } @Test public void login_success_prevents_log_flooding_on_login_starting_from_128_chars() { underTest.loginSuccess(mockRequest(), LOGIN_129_CHARS, Source.realm(Method.BASIC, "some provider name")); verifyLog("login success [method|BASIC][provider|REALM|some provider name][IP||][login|012345678901234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345678901234567...(129)]"); } @Test public void login_success_logs_remote_ip_from_request() { underTest.loginSuccess(mockRequest("1.2.3.4"), "foo", Source.realm(Method.EXTERNAL, "bar")); verifyLog("login success [method|EXTERNAL][provider|REALM|bar][IP|1.2.3.4|][login|foo]"); } @Test public void login_success_logs_X_Forwarded_For_header_from_request() { HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5")); underTest.loginSuccess(request, "foo", Source.realm(Method.EXTERNAL, "bar")); verifyLog("login success [method|EXTERNAL][provider|REALM|bar][IP|1.2.3.4|2.3.4.5][login|foo]"); } @Test public void login_success_logs_X_Forwarded_For_header_from_request_and_supports_multiple_headers() { HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5", "6.5.4.3"), asList("9.5.6.7"), asList("6.3.2.4")); underTest.loginSuccess(request, "foo", Source.realm(Method.EXTERNAL, "bar")); verifyLog("login success [method|EXTERNAL][provider|REALM|bar][IP|1.2.3.4|2.3.4.5,6.5.4.3,9.5.6.7,6.3.2.4][login|foo]"); } @Test public void login_failure_fails_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); AuthenticationException exception = newBuilder().setSource(Source.sso()).build(); assertThatThrownBy(() -> underTest.loginFailure(null, exception)) .isInstanceOf(NullPointerException.class) .hasMessage("request can't be null"); } @Test public void login_failure_fails_with_NPE_if_AuthenticationException_is_null() { logTester.setLevel(LoggerLevel.INFO); assertThatThrownBy(() -> underTest.loginFailure(mock(HttpRequest.class), null)) .isInstanceOf(NullPointerException.class) .hasMessage("AuthenticationException can't be null"); } @Test public void login_failure_does_not_interact_with_arguments_if_log_level_is_above_DEBUG() { HttpRequest request = mock(HttpRequest.class); AuthenticationException exception = mock(AuthenticationException.class); logTester.setLevel(LoggerLevel.INFO); underTest.loginFailure(request, exception); verifyNoInteractions(request, exception); } @Test public void login_failure_creates_DEBUG_log_with_empty_login_if_AuthenticationException_has_no_login() { AuthenticationException exception = newBuilder().setSource(Source.sso()).setMessage("message").build(); underTest.loginFailure(mockRequest(), exception); verifyLog("login failure [cause|message][method|SSO][provider|SSO|sso][IP||][login|]"); } @Test public void login_failure_creates_DEBUG_log_with_empty_cause_if_AuthenticationException_has_no_message() { AuthenticationException exception = newBuilder().setSource(Source.sso()).setLogin("FoO").build(); underTest.loginFailure(mockRequest(), exception); verifyLog("login failure [cause|][method|SSO][provider|SSO|sso][IP||][login|FoO]"); } @Test public void login_failure_creates_DEBUG_log_with_method_provider_and_login() { AuthenticationException exception = newBuilder() .setSource(Source.realm(Method.BASIC, "some provider name")) .setMessage("something got terribly wrong") .setLogin("BaR") .build(); underTest.loginFailure(mockRequest(), exception); verifyLog("login failure [cause|something got terribly wrong][method|BASIC][provider|REALM|some provider name][IP||][login|BaR]"); } @Test public void login_failure_prevents_log_flooding_on_login_starting_from_128_chars() { AuthenticationException exception = newBuilder() .setSource(Source.realm(Method.BASIC, "some provider name")) .setMessage("pop") .setLogin(LOGIN_129_CHARS) .build(); underTest.loginFailure(mockRequest(), exception); verifyLog("login failure [cause|pop][method|BASIC][provider|REALM|some provider name][IP||][login|012345678901234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345678901234567...(129)]"); } @Test public void login_failure_logs_remote_ip_from_request() { AuthenticationException exception = newBuilder() .setSource(Source.realm(Method.EXTERNAL, "bar")) .setMessage("Damn it!") .setLogin("Baaad") .build(); underTest.loginFailure(mockRequest("1.2.3.4"), exception); verifyLog("login failure [cause|Damn it!][method|EXTERNAL][provider|REALM|bar][IP|1.2.3.4|][login|Baaad]"); } @Test public void login_failure_logs_X_Forwarded_For_header_from_request() { AuthenticationException exception = newBuilder() .setSource(Source.realm(Method.EXTERNAL, "bar")) .setMessage("Hop la!") .setLogin("foo") .build(); HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5")); underTest.loginFailure(request, exception); verifyLog("login failure [cause|Hop la!][method|EXTERNAL][provider|REALM|bar][IP|1.2.3.4|2.3.4.5][login|foo]"); } @Test public void login_failure_logs_X_Forwarded_For_header_from_request_and_supports_multiple_headers() { AuthenticationException exception = newBuilder() .setSource(Source.realm(Method.EXTERNAL, "bar")) .setMessage("Boom!") .setLogin("foo") .build(); HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5", "6.5.4.3"), asList("9.5.6.7"), asList("6.3.2.4")); underTest.loginFailure(request, exception); verifyLog("login failure [cause|Boom!][method|EXTERNAL][provider|REALM|bar][IP|1.2.3.4|2.3.4.5,6.5.4.3,9.5.6.7,6.3.2.4][login|foo]"); } @Test public void logout_success_fails_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); assertThatThrownBy(() -> underTest.logoutSuccess(null, "foo")) .isInstanceOf(NullPointerException.class) .hasMessage("request can't be null"); } @Test public void logout_success_does_not_interact_with_request_if_log_level_is_above_DEBUG() { HttpRequest request = mock(HttpRequest.class); logTester.setLevel(LoggerLevel.INFO); underTest.logoutSuccess(request, "foo"); verifyNoInteractions(request); } @Test public void logout_success_creates_DEBUG_log_with_empty_login_if_login_argument_is_null() { underTest.logoutSuccess(mockRequest(), null); verifyLog("logout success [IP||][login|]"); } @Test public void logout_success_creates_DEBUG_log_with_login() { underTest.logoutSuccess(mockRequest(), "foo"); verifyLog("logout success [IP||][login|foo]"); } @Test public void logout_success_logs_remote_ip_from_request() { underTest.logoutSuccess(mockRequest("1.2.3.4"), "foo"); verifyLog("logout success [IP|1.2.3.4|][login|foo]"); } @Test public void logout_success_logs_X_Forwarded_For_header_from_request() { HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5")); underTest.logoutSuccess(request, "foo"); verifyLog("logout success [IP|1.2.3.4|2.3.4.5][login|foo]"); } @Test public void logout_success_logs_X_Forwarded_For_header_from_request_and_supports_multiple_headers() { HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5", "6.5.4.3"), asList("9.5.6.7"), asList("6.3.2.4")); underTest.logoutSuccess(request, "foo"); verifyLog("logout success [IP|1.2.3.4|2.3.4.5,6.5.4.3,9.5.6.7,6.3.2.4][login|foo]"); } @Test public void logout_failure_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); assertThatThrownBy(() -> underTest.logoutFailure(null, "bad csrf")) .isInstanceOf(NullPointerException.class) .hasMessage("request can't be null"); } @Test public void login_fails_with_NPE_if_error_message_is_null() { logTester.setLevel(LoggerLevel.INFO); assertThatThrownBy(() -> underTest.logoutFailure(mock(HttpRequest.class), null)) .isInstanceOf(NullPointerException.class) .hasMessage("error message can't be null"); } @Test public void logout_does_not_interact_with_request_if_log_level_is_above_DEBUG() { HttpRequest request = mock(HttpRequest.class); logTester.setLevel(LoggerLevel.INFO); underTest.logoutFailure(request, "bad csrf"); verifyNoInteractions(request); } @Test public void logout_creates_DEBUG_log_with_error() { underTest.logoutFailure(mockRequest(), "bad token"); verifyLog("logout failure [error|bad token][IP||]"); } @Test public void logout_logs_remote_ip_from_request() { underTest.logoutFailure(mockRequest("1.2.3.4"), "bad token"); verifyLog("logout failure [error|bad token][IP|1.2.3.4|]"); } @Test public void logout_logs_X_Forwarded_For_header_from_request() { HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5")); underTest.logoutFailure(request, "bad token"); verifyLog("logout failure [error|bad token][IP|1.2.3.4|2.3.4.5]"); } @Test public void logout_logs_X_Forwarded_For_header_from_request_and_supports_multiple_headers() { HttpRequest request = mockRequest("1.2.3.4", asList("2.3.4.5", "6.5.4.3"), asList("9.5.6.7"), asList("6.3.2.4")); underTest.logoutFailure(request, "bad token"); verifyLog("logout failure [error|bad token][IP|1.2.3.4|2.3.4.5,6.5.4.3,9.5.6.7,6.3.2.4]"); } private void verifyLog(String expected) { assertThat(logTester.logs()).hasSize(1); assertThat(logTester.logs(Level.DEBUG)) .containsOnly(expected); } private static HttpRequest mockRequest() { return mockRequest(""); } private static HttpRequest mockRequest(String remoteAddr, List<String>... remoteIps) { HttpRequest res = mock(HttpRequest.class); when(res.getRemoteAddr()).thenReturn(remoteAddr); when(res.getHeaders("X-Forwarded-For")) .thenReturn(Collections.enumeration( Arrays.stream(remoteIps) .map(Joiner.on(",")::join) .toList())); return res; } }
14,336
36.142487
165
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventSourceTest.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.event; import java.io.Serializable; import org.junit.Test; import org.sonar.api.server.authentication.BaseIdentityProvider; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.event.AuthenticationEvent.Method; import static org.sonar.server.authentication.event.AuthenticationEvent.Provider; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; public class AuthenticationEventSourceTest { @Test public void local_fails_with_NPE_if_method_is_null() { assertThatThrownBy(() -> Source.local(null)) .isInstanceOf(NullPointerException.class) .hasMessage("method can't be null"); } @Test public void local_creates_source_instance_with_specified_method_and_hardcoded_provider_and_provider_name() { Source underTest = Source.local(Method.SONARQUBE_TOKEN); assertThat(underTest.getMethod()).isEqualTo(Method.SONARQUBE_TOKEN); assertThat(underTest.getProvider()).isEqualTo(Provider.LOCAL); assertThat(underTest.getProviderName()).isEqualTo("local"); } @Test public void oauth2_fails_with_NPE_if_provider_is_null() { assertThatThrownBy(() -> Source.oauth2(null)) .isInstanceOf(NullPointerException.class) .hasMessage("identityProvider can't be null"); } @Test public void oauth2_fails_with_NPE_if_providerName_is_null() { assertThatThrownBy(() -> Source.oauth2(newOauth2IdentityProvider(null))) .isInstanceOf(NullPointerException.class) .hasMessage("provider name can't be null"); } @Test public void oauth2_fails_with_IAE_if_providerName_is_empty() { assertThatThrownBy(() -> Source.oauth2(newOauth2IdentityProvider(""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("provider name can't be empty"); } @Test public void oauth2_creates_source_instance_with_specified_provider_name_and_hardcoded_provider_and_method() { Source underTest = Source.oauth2(newOauth2IdentityProvider("some name")); assertThat(underTest.getMethod()).isEqualTo(Method.OAUTH2); assertThat(underTest.getProvider()).isEqualTo(Provider.EXTERNAL); assertThat(underTest.getProviderName()).isEqualTo("some name"); } @Test public void realm_fails_with_NPE_if_method_is_null() { assertThatThrownBy(() -> Source.realm(null, "name")) .isInstanceOf(NullPointerException.class) .hasMessage("method can't be null"); } @Test public void realm_fails_with_NPE_if_providerName_is_null() { assertThatThrownBy(() -> Source.realm(Method.BASIC, null)) .isInstanceOf(NullPointerException.class) .hasMessage("provider name can't be null"); } @Test public void realm_fails_with_IAE_if_providerName_is_empty() { assertThatThrownBy(() -> Source.realm(Method.BASIC, "")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("provider name can't be empty"); } @Test public void realm_creates_source_instance_with_specified_method_and_provider_name_and_hardcoded_provider() { Source underTest = Source.realm(Method.BASIC, "some name"); assertThat(underTest.getMethod()).isEqualTo(Method.BASIC); assertThat(underTest.getProvider()).isEqualTo(Provider.REALM); assertThat(underTest.getProviderName()).isEqualTo("some name"); } @Test public void sso_returns_source_instance_with_hardcoded_method_provider_and_providerName() { Source underTest = Source.sso(); assertThat(underTest.getMethod()).isEqualTo(Method.SSO); assertThat(underTest.getProvider()).isEqualTo(Provider.SSO); assertThat(underTest.getProviderName()).isEqualTo("sso"); assertThat(underTest).isSameAs(Source.sso()); } @Test public void jwt_returns_source_instance_with_hardcoded_method_provider_and_providerName() { Source underTest = Source.jwt(); assertThat(underTest.getMethod()).isEqualTo(Method.JWT); assertThat(underTest.getProvider()).isEqualTo(Provider.JWT); assertThat(underTest.getProviderName()).isEqualTo("jwt"); assertThat(underTest).isSameAs(Source.jwt()); } @Test public void external_fails_with_NPE_if_provider_is_null() { assertThatThrownBy(() -> Source.external(null)) .isInstanceOf(NullPointerException.class) .hasMessage("identityProvider can't be null"); } @Test public void external_fails_with_NPE_if_providerName_is_null() { assertThatThrownBy(() -> Source.external(newBasicIdentityProvider(null))) .isInstanceOf(NullPointerException.class) .hasMessage("provider name can't be null"); } @Test public void external_fails_with_IAE_if_providerName_is_empty() { assertThatThrownBy(() -> Source.external(newBasicIdentityProvider(""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("provider name can't be empty"); } @Test public void external_creates_source_instance_with_specified_provider_name_and_hardcoded_provider_and_method() { Source underTest = Source.external(newBasicIdentityProvider("some name")); assertThat(underTest.getMethod()).isEqualTo(Method.EXTERNAL); assertThat(underTest.getProvider()).isEqualTo(Provider.EXTERNAL); assertThat(underTest.getProviderName()).isEqualTo("some name"); } @Test public void source_is_serializable() { assertThat(Serializable.class.isAssignableFrom(Source.class)).isTrue(); } @Test public void toString_displays_all_fields() { assertThat(Source.sso().toString()) .isEqualTo("Source{method=SSO, provider=SSO, providerName='sso'}"); assertThat(Source.oauth2(newOauth2IdentityProvider("bou")).toString()) .isEqualTo("Source{method=OAUTH2, provider=EXTERNAL, providerName='bou'}"); } @Test public void source_implements_equals_on_all_fields() { assertThat(Source.sso()).isEqualTo(Source.sso()); assertThat(Source.sso()).isNotEqualTo(Source.jwt()); assertThat(Source.jwt()).isEqualTo(Source.jwt()); assertThat(Source.local(Method.BASIC)).isEqualTo(Source.local(Method.BASIC)); assertThat(Source.local(Method.BASIC)).isNotEqualTo(Source.local(Method.SONARQUBE_TOKEN)); assertThat(Source.local(Method.BASIC)).isNotEqualTo(Source.sso()); assertThat(Source.local(Method.BASIC)).isNotEqualTo(Source.jwt()); assertThat(Source.local(Method.BASIC)).isNotEqualTo(Source.oauth2(newOauth2IdentityProvider("voo"))); assertThat(Source.oauth2(newOauth2IdentityProvider("foo"))) .isEqualTo(Source.oauth2(newOauth2IdentityProvider("foo"))); assertThat(Source.oauth2(newOauth2IdentityProvider("foo"))) .isNotEqualTo(Source.oauth2(newOauth2IdentityProvider("bar"))); } private static OAuth2IdentityProvider newOauth2IdentityProvider(String name) { OAuth2IdentityProvider mock = mock(OAuth2IdentityProvider.class); when(mock.getName()).thenReturn(name); return mock; } private static BaseIdentityProvider newBasicIdentityProvider(String name) { BaseIdentityProvider mock = mock(BaseIdentityProvider.class); when(mock.getName()).thenReturn(name); return mock; } }
8,137
38.504854
113
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationExceptionTest.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.event; import org.junit.Test; import org.sonar.server.authentication.event.AuthenticationEvent.Source; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AuthenticationExceptionTest { @Test public void build_fails_with_NPE_if_source_is_null() { AuthenticationException.Builder builder = AuthenticationException.newBuilder() .setLogin("login") .setMessage("message"); assertThatThrownBy(builder::build) .isInstanceOf(NullPointerException.class) .hasMessage("source can't be null"); } @Test public void build_does_not_fail_if_login_is_null() { AuthenticationException exception = AuthenticationException.newBuilder() .setSource(Source.sso()) .setMessage("message") .build(); assertThat(exception.getSource()).isEqualTo(Source.sso()); assertThat(exception.getMessage()).isEqualTo("message"); assertThat(exception.getLogin()).isNull(); } @Test public void build_does_not_fail_if_message_is_null() { AuthenticationException exception = AuthenticationException.newBuilder() .setSource(Source.sso()) .setLogin("login") .build(); assertThat(exception.getSource()).isEqualTo(Source.sso()); assertThat(exception.getMessage()).isNull(); assertThat(exception.getLogin()).isEqualTo("login"); } @Test public void builder_set_methods_do_not_fail_if_login_is_null() { AuthenticationException.newBuilder().setSource(null).setLogin(null).setMessage(null); } }
2,466
33.746479
89
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.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.permission; import org.junit.Test; import org.sonar.db.user.GroupDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; public class GroupUuidOrAnyoneTest { @Test public void for_returns_isAnyone_if_id_is_null() { GroupDto dto = new GroupDto(); GroupUuidOrAnyone underTest = GroupUuidOrAnyone.from(dto); assertThat(underTest.isAnyone()).isTrue(); assertThat(underTest.getUuid()).isNull(); } @Test public void for_returns_isAnyone_false_if_id_is_not_null() { String uuid = randomAlphabetic(10); GroupDto dto = new GroupDto(); dto.setUuid(uuid); GroupUuidOrAnyone underTest = GroupUuidOrAnyone.from(dto); assertThat(underTest.isAnyone()).isFalse(); assertThat(underTest.getUuid()).isEqualTo(uuid); } @Test public void forAnyone_returns_isAnyone_true() { GroupUuidOrAnyone underTest = GroupUuidOrAnyone.forAnyone(); assertThat(underTest.isAnyone()).isTrue(); assertThat(underTest.getUuid()).isNull(); } }
1,934
30.721311
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/PermissionServiceImplTest.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.permission; import org.junit.Test; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import static org.assertj.core.api.Assertions.assertThat; public class PermissionServiceImplTest { private ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers("APP", "VW"); private PermissionServiceImpl underTest = new PermissionServiceImpl(resourceTypesRule); @Test public void globalPermissions_must_be_ordered() { assertThat(underTest.getGlobalPermissions()) .extracting(GlobalPermission::getKey) .containsExactly("admin", "gateadmin", "profileadmin", "provisioning", "scan", "applicationcreator", "portfoliocreator"); } @Test public void projectPermissions_must_be_ordered() { assertThat(underTest.getAllProjectPermissions()) .containsExactly("admin", "codeviewer", "issueadmin", "securityhotspotadmin", "scan", "user"); } }
1,806
38.282609
127
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/tester/AttributeHolderServletContext.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.tester; import java.io.InputStream; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; /** * A dummy implementation of {@link ServletContext} which only implements the attribute related methods. All other * methods thrown a {@link UnsupportedOperationException} when called. */ class AttributeHolderServletContext implements ServletContext { @Override public String getContextPath() { throw new UnsupportedOperationException(); } @Override public ServletContext getContext(String s) { throw new UnsupportedOperationException(); } @Override public int getMajorVersion() { throw new UnsupportedOperationException(); } @Override public int getMinorVersion() { throw new UnsupportedOperationException(); } @Override public int getEffectiveMajorVersion() { throw new UnsupportedOperationException(); } @Override public int getEffectiveMinorVersion() { throw new UnsupportedOperationException(); } @Override public String getMimeType(String s) { throw new UnsupportedOperationException(); } @Override public Set<String> getResourcePaths(String s) { throw new UnsupportedOperationException(); } @Override public URL getResource(String s) { throw new UnsupportedOperationException(); } @Override public InputStream getResourceAsStream(String s) { throw new UnsupportedOperationException(); } @Override public RequestDispatcher getRequestDispatcher(String s) { throw new UnsupportedOperationException(); } @Override public RequestDispatcher getNamedDispatcher(String s) { throw new UnsupportedOperationException(); } @Override public Servlet getServlet(String s) { throw new UnsupportedOperationException(); } @Override public Enumeration<Servlet> getServlets() { throw new UnsupportedOperationException(); } @Override public Enumeration<String> getServletNames() { throw new UnsupportedOperationException(); } @Override public void log(String s) { throw new UnsupportedOperationException(); } @Override public void log(Exception e, String s) { throw new UnsupportedOperationException(); } @Override public void log(String s, Throwable throwable) { throw new UnsupportedOperationException(); } @Override public String getRealPath(String s) { throw new UnsupportedOperationException(); } @Override public String getServerInfo() { throw new UnsupportedOperationException(); } @Override public String getInitParameter(String s) { throw new UnsupportedOperationException(); } @Override public Enumeration<String> getInitParameterNames() { throw new UnsupportedOperationException(); } @Override public boolean setInitParameter(String s, String s1) { throw new UnsupportedOperationException(); } @Override public Object getAttribute(String s) { return this.attributes.get(s); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(this.attributes.keySet()); } private final Map<String, Object> attributes = new HashMap<>(); @Override public void setAttribute(String s, Object o) { attributes.put(s, o); } @Override public void removeAttribute(String s) { attributes.remove(s); } @Override public String getServletContextName() { throw new UnsupportedOperationException(); } @Override public ServletRegistration.Dynamic addServlet(String s, String s1) { throw new UnsupportedOperationException(); } @Override public ServletRegistration.Dynamic addServlet(String s, Servlet servlet) { throw new UnsupportedOperationException(); } @Override public ServletRegistration.Dynamic addServlet(String s, Class<? extends Servlet> aClass) { throw new UnsupportedOperationException(); } @Override public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) { throw new UnsupportedOperationException(); } @Override public <T extends Servlet> T createServlet(Class<T> aClass) { throw new UnsupportedOperationException(); } @Override public ServletRegistration getServletRegistration(String s) { throw new UnsupportedOperationException(); } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { throw new UnsupportedOperationException(); } @Override public FilterRegistration.Dynamic addFilter(String s, String s1) { throw new UnsupportedOperationException(); } @Override public FilterRegistration.Dynamic addFilter(String s, Filter filter) { throw new UnsupportedOperationException(); } @Override public FilterRegistration.Dynamic addFilter(String s, Class<? extends Filter> aClass) { throw new UnsupportedOperationException(); } @Override public <T extends Filter> T createFilter(Class<T> aClass) { throw new UnsupportedOperationException(); } @Override public FilterRegistration getFilterRegistration(String s) { throw new UnsupportedOperationException(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { throw new UnsupportedOperationException(); } @Override public SessionCookieConfig getSessionCookieConfig() { throw new UnsupportedOperationException(); } @Override public void setSessionTrackingModes(Set<SessionTrackingMode> set) { throw new UnsupportedOperationException(); } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { throw new UnsupportedOperationException(); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { throw new UnsupportedOperationException(); } @Override public void addListener(String s) { throw new UnsupportedOperationException(); } @Override public <T extends EventListener> void addListener(T t) { throw new UnsupportedOperationException(); } @Override public void addListener(Class<? extends EventListener> aClass) { throw new UnsupportedOperationException(); } @Override public <T extends EventListener> T createListener(Class<T> aClass) { throw new UnsupportedOperationException(); } @Override public JspConfigDescriptor getJspConfigDescriptor() { throw new UnsupportedOperationException(); } @Override public ClassLoader getClassLoader() { throw new UnsupportedOperationException(); } @Override public void declareRoles(String... strings) { throw new UnsupportedOperationException(); } @Override public String getVirtualServerName() { throw new UnsupportedOperationException(); } @Override public int getSessionTimeout() { return 0; } @Override public void setSessionTimeout(int sessionTimeout) { throw new UnsupportedOperationException(); } @Override public String getRequestCharacterEncoding() { throw new UnsupportedOperationException(); } @Override public void setRequestCharacterEncoding(String encoding) { throw new UnsupportedOperationException(); } @Override public String getResponseCharacterEncoding() { throw new UnsupportedOperationException(); } @Override public void setResponseCharacterEncoding(String encoding) { throw new UnsupportedOperationException(); } }
8,684
24.394737
114
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/tester/AttributeHolderServletContextTest.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.tester; import com.google.common.collect.ImmutableSet; import java.util.Collections; import java.util.Enumeration; import java.util.EventListener; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.SessionTrackingMode; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class AttributeHolderServletContextTest { public static final String SOME_STRING = "SOME_STRING"; public static final Exception SOME_EXCEPTION = new Exception(); public static final String SOME_OTHER_STRING = "SOME OTHER STRING"; AttributeHolderServletContext servletContext = new AttributeHolderServletContext(); public static final ImmutableSet<SessionTrackingMode> SOME_SET_OF_SESSION_TRACKING_MODE = ImmutableSet.of(); @Test(expected = UnsupportedOperationException.class) public void getContextPath_is_not_supported() { servletContext.getContextPath(); } @Test(expected = UnsupportedOperationException.class) public void getContext_is_not_supported() { servletContext.getContext(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getMajorVersion_is_not_supported() { servletContext.getMajorVersion(); } @Test(expected = UnsupportedOperationException.class) public void getMinorVersion_is_not_supported() { servletContext.getMinorVersion(); } @Test(expected = UnsupportedOperationException.class) public void getEffectiveMajorVersion_is_not_supported() { servletContext.getEffectiveMajorVersion(); } @Test(expected = UnsupportedOperationException.class) public void getEffectiveMinorVersion_is_not_supported() { servletContext.getEffectiveMinorVersion(); } @Test(expected = UnsupportedOperationException.class) public void getMimeType_is_not_supported() { servletContext.getMimeType(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getResourcePaths_is_not_supported() { servletContext.getResourcePaths(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getResource_is_not_supported() { servletContext.getResource(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getResourceAsStream_is_not_supported() { servletContext.getResourceAsStream(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getRequestDispatcher_is_not_supported() { servletContext.getRequestDispatcher(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getNamedDispatcher_is_not_supported() { servletContext.getNamedDispatcher(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getServlet_is_not_supported() { servletContext.getServlet(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getServlets_is_not_supported() { servletContext.getServlets(); } @Test(expected = UnsupportedOperationException.class) public void getServletNames_is_not_supported() { servletContext.getServletNames(); } @Test(expected = UnsupportedOperationException.class) public void log_is_not_supported() { servletContext.log(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void log1_is_not_supported() { servletContext.log(SOME_EXCEPTION, SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void log2_is_not_supported() { servletContext.log(SOME_STRING, SOME_EXCEPTION); } @Test(expected = UnsupportedOperationException.class) public void getRealPath_is_not_supported() { servletContext.getRealPath(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getServerInfo_is_not_supported() { servletContext.getServerInfo(); } @Test(expected = UnsupportedOperationException.class) public void getInitParameter_is_not_supported() { servletContext.getInitParameter(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getInitParameterNames_is_not_supported() { servletContext.getInitParameterNames(); } @Test(expected = UnsupportedOperationException.class) public void setInitParameter_is_not_supported() { servletContext.setInitParameter(SOME_STRING, SOME_STRING); } @Test public void getAttribute_returns_null_when_attributes_are_empty() { assertThat(servletContext.getAttribute(SOME_STRING)).isNull(); } @Test public void getAttribute_returns_attribute() { servletContext.setAttribute(SOME_STRING, SOME_OTHER_STRING); assertThat(servletContext.getAttribute(SOME_STRING)).isEqualTo(SOME_OTHER_STRING); } @Test public void getAttributeNames_returns_empty_enumeration_if_attributes_are_empty() { Enumeration<String> attributeNames = servletContext.getAttributeNames(); assertThat(attributeNames.hasMoreElements()).isFalse(); } @Test public void getAttributeNames_returns_names_of_attributes() { servletContext.setAttribute(SOME_STRING, new Object()); servletContext.setAttribute(SOME_OTHER_STRING, new Object()); assertThat(Collections.list(servletContext.getAttributeNames())).containsOnly(SOME_STRING, SOME_OTHER_STRING); } @Test public void removeAttribute_removes_specified_attribute() { servletContext.setAttribute(SOME_STRING, new Object()); servletContext.setAttribute(SOME_OTHER_STRING, new Object()); servletContext.removeAttribute(SOME_OTHER_STRING); assertThat(servletContext.getAttribute(SOME_OTHER_STRING)).isNull(); } @Test(expected = UnsupportedOperationException.class) public void getServletContextName_is_not_supported() { servletContext.getServletContextName(); } @Test(expected = UnsupportedOperationException.class) public void addServlet_by_class_is_not_supported() { servletContext.addServlet(SOME_STRING, Servlet.class); } @Test(expected = UnsupportedOperationException.class) public void addServlet_by_instance_is_not_supported() { servletContext.addServlet(SOME_STRING, new Servlet() { @Override public void init(ServletConfig servletConfig) { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) { } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }); } @Test(expected = UnsupportedOperationException.class) public void addServlet_by_string_is_not_supported() { servletContext.addServlet(SOME_STRING, SOME_OTHER_STRING); } @Test(expected = UnsupportedOperationException.class) public void createServlet_is_not_supported() { servletContext.createServlet(Servlet.class); } @Test(expected = UnsupportedOperationException.class) public void getServletRegistration_is_not_supported() { servletContext.getServletRegistration(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getServletRegistrations_is_not_supported() { servletContext.getServletRegistrations(); } @Test(expected = UnsupportedOperationException.class) public void addFilter_by_class_is_not_supported() { servletContext.addFilter(SOME_STRING, Filter.class); } @Test(expected = UnsupportedOperationException.class) public void addFilter_by_instance_is_not_supported() { servletContext.addFilter(SOME_STRING, new Filter() { @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { } @Override public void destroy() { } }); } @Test(expected = UnsupportedOperationException.class) public void addFilter2_by_string_is_not_supported() { servletContext.addFilter(SOME_STRING, SOME_OTHER_STRING); } @Test(expected = UnsupportedOperationException.class) public void createFilter_is_not_supported() { servletContext.createFilter(Filter.class); } @Test(expected = UnsupportedOperationException.class) public void getFilterRegistration_is_not_supported() { servletContext.getFilterRegistration(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void getFilterRegistrations_is_not_supported() { servletContext.getFilterRegistrations(); } @Test(expected = UnsupportedOperationException.class) public void getSessionCookieConfig_is_not_supported() { servletContext.getSessionCookieConfig(); } @Test(expected = UnsupportedOperationException.class) public void setSessionTrackingModes_is_not_supported() { servletContext.setSessionTrackingModes(SOME_SET_OF_SESSION_TRACKING_MODE); } @Test(expected = UnsupportedOperationException.class) public void getDefaultSessionTrackingModes_is_not_supported() { servletContext.getDefaultSessionTrackingModes(); } @Test(expected = UnsupportedOperationException.class) public void getEffectiveSessionTrackingModes_is_not_supported() { servletContext.getEffectiveSessionTrackingModes(); } @Test(expected = UnsupportedOperationException.class) public void addListener_by_class_is_not_supported() { servletContext.addListener(EventListener.class); } @Test(expected = UnsupportedOperationException.class) public void addListener_by_string_is_not_supported() { servletContext.addListener(SOME_STRING); } @Test(expected = UnsupportedOperationException.class) public void addListener_by_instance_is_not_supported() { servletContext.addListener(new EventListener() { }); } @Test(expected = UnsupportedOperationException.class) public void createListener_is_not_supported() { servletContext.createListener(EventListener.class); } @Test(expected = UnsupportedOperationException.class) public void getJspConfigDescriptor_is_not_supported() { servletContext.getJspConfigDescriptor(); } @Test(expected = UnsupportedOperationException.class) public void getClassLoader_is_not_supported() { servletContext.getClassLoader(); } @Test(expected = UnsupportedOperationException.class) public void declareRoles_is_not_supported() { servletContext.declareRoles(); } @Test(expected = UnsupportedOperationException.class) public void getVirtualServerName_is_not_supported() { servletContext.getVirtualServerName(); } }
11,645
30.306452
117
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/tester/MockUserSessionTest.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.tester; import org.junit.Test; import org.sonar.db.user.GroupDto; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.user.GroupTesting.newGroupDto; public class MockUserSessionTest { @Test public void set_mock_session() { GroupDto group = newGroupDto(); MockUserSession mock = new MockUserSession("foo").setGroups(group); assertThat(mock.getLogin()).isEqualTo("foo"); assertThat(mock.getUuid()).isEqualTo("foouuid"); assertThat(mock.getGroups()).extracting(GroupDto::getUuid).containsOnly(group.getUuid()); assertThat(mock.isLoggedIn()).isTrue(); } }
1,487
36.2
93
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/tester/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.tester; import javax.annotation.ParametersAreNonnullByDefault;
963
39.166667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/BearerPasscodeTest.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; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.ws.SimpleGetRequest; import static org.assertj.core.api.Assertions.assertThat; public class BearerPasscodeTest { private final MapSettings settings = new MapSettings(); private final BearerPasscode underTest = new BearerPasscode(settings.asConfig()); @Test public void isValid_is_true_if_request_header_matches_configured_passcode() { verifyIsValid(true, "foo", "foo"); } @Test public void isValid_is_false_if_request_header_matches_configured_passcode_with_different_case() { verifyIsValid(false, "foo", "FOO"); } @Test public void isValid_is_false_if_request_header_does_not_match_configured_passcode() { verifyIsValid(false, "foo", "bar"); } @Test public void isValid_is_false_if_request_header_is_defined_but_passcode_is_not_configured() { verifyIsValid(false, null, "foo"); } @Test public void isValid_is_false_if_request_header_is_empty() { verifyIsValid(false, "foo", ""); } private void verifyIsValid(boolean expectedResult, String configuredPasscode, String token) { configurePasscode(configuredPasscode); SimpleGetRequest request = new SimpleGetRequest(); request.setHeader("Authorization", "Bearer " + token); assertThat(underTest.isValid(request)).isEqualTo(expectedResult); } private void configurePasscode(String propertyValue) { settings.setProperty("sonar.web.systemPasscode", propertyValue); } }
2,382
32.097222
100
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/CompatibilityRealmTest.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; import org.junit.Test; import org.sonar.api.security.LoginPasswordAuthenticator; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class CompatibilityRealmTest { @Test public void shouldDelegate() { LoginPasswordAuthenticator authenticator = mock(LoginPasswordAuthenticator.class); CompatibilityRealm realm = new CompatibilityRealm(authenticator); realm.init(); verify(authenticator).init(); assertThat(realm.getLoginPasswordAuthenticator()).isSameAs(authenticator); assertThat(realm.getName()).isEqualTo("CompatibilityRealm[" + authenticator.getClass().getName() + "]"); } }
1,582
36.690476
108
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/DefaultUserTest.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; import org.junit.Test; import org.sonar.core.user.DefaultUser; import static org.assertj.core.api.Assertions.assertThat; public class DefaultUserTest { @Test public void test_object_methods() { DefaultUser john = new DefaultUser().setLogin("john").setName("John"); DefaultUser eric = new DefaultUser().setLogin("eric").setName("Eric"); assertThat(john) .isEqualTo(john) .isNotEqualTo(eric) .hasSameHashCodeAs(john); assertThat(john.toString()).contains("login=john").contains("name=John"); } @Test public void test_email() { DefaultUser user = new DefaultUser(); assertThat(user.email()).isNull(); user.setEmail(""); assertThat(user.email()).isNull(); user.setEmail(" "); assertThat(user.email()).isNull(); user.setEmail("s@b.com"); assertThat(user.email()).isEqualTo("s@b.com"); } }
1,745
30.745455
77
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/DoPrivilegedTest.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; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.sonar.db.component.ComponentDto; import org.sonar.server.tester.MockUserSession; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.web.UserRole.USER; public class DoPrivilegedTest { private static final String LOGIN = "dalailaHidou!"; private ThreadLocalUserSession threadLocalUserSession = new ThreadLocalUserSession(); private MockUserSession session = new MockUserSession(LOGIN); @Before public void setUp() { threadLocalUserSession.set(session); } @Test public void allow_everything_in_privileged_block_only() { UserSessionCatcherTask catcher = new UserSessionCatcherTask(); DoPrivileged.execute(catcher); // verify the session used inside Privileged task assertThat(catcher.userSession.isLoggedIn()).isFalse(); assertThat(catcher.userSession.hasComponentPermission("any permission", new ComponentDto())).isTrue(); assertThat(catcher.userSession.isSystemAdministrator()).isTrue(); assertThat(catcher.userSession.shouldResetPassword()).isFalse(); assertThat(catcher.userSession.isActive()).isTrue(); assertThat(catcher.userSession.hasChildProjectsPermission(USER, new ComponentDto().setUuid("uuid"))).isTrue(); assertThat(catcher.userSession.hasPortfolioChildProjectsPermission(USER, new ComponentDto())).isTrue(); // verify session in place after task is done assertThat(threadLocalUserSession.get()).isSameAs(session); } @Test public void loose_privileges_on_exception() { UserSessionCatcherTask catcher = new UserSessionCatcherTask() { @Override protected void doPrivileged() { super.doPrivileged(); throw new RuntimeException("Test to lose privileges"); } }; Assert.assertThrows(Exception.class, () -> DoPrivileged.execute(catcher)); // verify session in place after task is done assertThat(threadLocalUserSession.get()).isSameAs(session); // verify the session used inside Privileged task assertThat(catcher.userSession.isLoggedIn()).isFalse(); assertThat(catcher.userSession.hasComponentPermission("any permission", new ComponentDto())).isTrue(); } private class UserSessionCatcherTask extends DoPrivileged.Task { UserSession userSession; public UserSessionCatcherTask() { super(DoPrivilegedTest.this.threadLocalUserSession); } @Override protected void doPrivileged() { userSession = threadLocalUserSession.get(); } } }
3,422
35.031579
114
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ExternalIdentityTest.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; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExternalIdentityTest { @Test public void create_external_identity() { ExternalIdentity externalIdentity = new ExternalIdentity("github", "login", "ABCD"); assertThat(externalIdentity.getLogin()).isEqualTo("login"); assertThat(externalIdentity.getProvider()).isEqualTo("github"); assertThat(externalIdentity.getId()).isEqualTo("ABCD"); } @Test public void login_is_used_when_id_is_not_provided() { ExternalIdentity externalIdentity = new ExternalIdentity("github", "login", null); assertThat(externalIdentity.getLogin()).isEqualTo("login"); assertThat(externalIdentity.getProvider()).isEqualTo("github"); assertThat(externalIdentity.getId()).isEqualTo("login"); } @Test public void fail_with_NPE_when_identity_provider_is_null() { assertThatThrownBy(() -> new ExternalIdentity(null, "login", "ABCD")) .isInstanceOf(NullPointerException.class) .hasMessage("Identity provider cannot be null"); } @Test public void fail_with_NPE_when_identity_login_is_null() { assertThatThrownBy(() -> new ExternalIdentity("github", null, "ABCD")) .isInstanceOf(NullPointerException.class) .hasMessage("Identity login cannot be null"); } }
2,251
35.918033
88
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/GithubWebhookUserSessionTest.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; import java.util.Arrays; import org.junit.Test; import org.sonar.db.permission.GlobalPermission; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.sonar.server.user.GithubWebhookUserSession.GITHUB_WEBHOOK_USER_NAME; public class GithubWebhookUserSessionTest { GithubWebhookUserSession githubWebhookUserSession = new GithubWebhookUserSession(); @Test public void getLogin() { assertThat(githubWebhookUserSession.getLogin()).isEqualTo(GITHUB_WEBHOOK_USER_NAME); } @Test public void getUuid() { assertThatIllegalStateException().isThrownBy(() -> githubWebhookUserSession.getUuid()); } @Test public void getName() { assertThat(githubWebhookUserSession.getName()).isEqualTo(GITHUB_WEBHOOK_USER_NAME); } @Test public void getGroups() { assertThat(githubWebhookUserSession.getGroups()).isEmpty(); } @Test public void shouldResetPassword() { assertThat(githubWebhookUserSession.shouldResetPassword()).isFalse(); } @Test public void getIdentityProvider() { assertThat(githubWebhookUserSession.getIdentityProvider()).isEmpty(); } @Test public void getExternalIdentity() { assertThat(githubWebhookUserSession.getExternalIdentity()).isEmpty(); } @Test public void isLoggedIn() { assertThat(githubWebhookUserSession.isLoggedIn()).isTrue(); } @Test public void isSystemAdministrator() { assertThat(githubWebhookUserSession.isSystemAdministrator()).isFalse(); } @Test public void isActive() { assertThat(githubWebhookUserSession.isActive()).isTrue(); } @Test public void hasPermissionImpl() { Arrays.stream(GlobalPermission.values()) .forEach(globalPermission -> assertThat(githubWebhookUserSession.hasPermissionImpl(globalPermission)).isFalse() ); } @Test public void componentUuidToProjectUuid() { assertThat(githubWebhookUserSession.componentUuidToEntityUuid("test")).isEmpty(); } @Test public void hasProjectUuidPermission() { assertThat(githubWebhookUserSession.hasEntityUuidPermission("perm", "project")).isFalse(); } @Test public void hasChildProjectsPermission() { assertThat(githubWebhookUserSession.hasChildProjectsPermission("perm", "project")).isFalse(); } @Test public void hasPortfolioChildProjectsPermission() { assertThat(githubWebhookUserSession.hasPortfolioChildProjectsPermission("perm", "project")).isFalse(); } @Test public void hasComponentUuidPermission_returnsAlwaysTrue() { assertThat(githubWebhookUserSession.hasComponentUuidPermission("perm", "project")).isTrue(); } }
3,562
29.452991
106
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/NewUserNotifierTest.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; import org.junit.Test; import org.sonar.api.platform.NewUserHandler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class NewUserNotifierTest { NewUserHandler.Context context = NewUserHandler.Context.builder().setLogin("marius").setName("Marius").build(); @Test public void do_not_fail_if_no_handlers() { NewUserNotifier notifier = new NewUserNotifier(); notifier.onNewUser(context); } @Test public void execute_handlers_on_new_user() { NewUserHandler handler1 = mock(NewUserHandler.class); NewUserHandler handler2 = mock(NewUserHandler.class); NewUserNotifier notifier = new NewUserNotifier(new NewUserHandler[]{handler1, handler2}); notifier.onNewUser(context); verify(handler1).doOnNewUser(context); verify(handler2).doOnNewUser(context); } }
1,718
32.057692
113
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/NewUserTest.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; import org.junit.Test; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NewUserTest { @Test public void create_new_user() { NewUser newUser = NewUser.builder() .setLogin("login") .setName("name") .setEmail("email") .setPassword("password") .setScmAccounts(asList("login1", "login2")) .build(); assertThat(newUser.login()).isEqualTo("login"); assertThat(newUser.name()).isEqualTo("name"); assertThat(newUser.email()).isEqualTo("email"); assertThat(newUser.password()).isEqualTo("password"); assertThat(newUser.scmAccounts()).contains("login1", "login2"); assertThat(newUser.externalIdentity()).isNull(); } @Test public void create_new_user_with_minimal_fields() { NewUser newUser = NewUser.builder().build(); assertThat(newUser.login()).isNull(); assertThat(newUser.name()).isNull(); assertThat(newUser.email()).isNull(); assertThat(newUser.password()).isNull(); assertThat(newUser.scmAccounts()).isEmpty(); } @Test public void create_new_user_with_authority() { NewUser newUser = NewUser.builder() .setLogin("login") .setName("name") .setEmail("email") .setExternalIdentity(new ExternalIdentity("github", "github_login", "ABCD")) .build(); assertThat(newUser.externalIdentity().getProvider()).isEqualTo("github"); assertThat(newUser.externalIdentity().getLogin()).isEqualTo("github_login"); assertThat(newUser.externalIdentity().getId()).isEqualTo("ABCD"); } @Test public void fail_to_set_password_when_external_identity_is_set() { assertThatThrownBy(() -> { NewUser.builder() .setLogin("login") .setName("name") .setEmail("email") .setPassword("password") .setExternalIdentity(new ExternalIdentity("github", "github_login", "ABCD")) .build(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Password should not be set with an external identity"); } }
3,007
32.797753
84
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/SecurityRealmFactoryTest.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; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.security.LoginPasswordAuthenticator; import org.sonar.api.security.SecurityRealm; import org.sonar.api.utils.SonarException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; public class SecurityRealmFactoryTest { private MapSettings settings = new MapSettings(); /** * Typical usage. */ @Test public void should_select_realm_and_start() { SecurityRealm realm = spy(new FakeRealm()); settings.setProperty("sonar.security.realm", realm.getName()); SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}); factory.start(); assertThat(factory.getRealm()).isSameAs(realm); assertThat(factory.hasExternalAuthentication()).isTrue(); verify(realm).init(); factory.stop(); } @Test public void do_not_fail_if_no_realms() { SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig()); factory.start(); assertThat(factory.getRealm()).isNull(); assertThat(factory.hasExternalAuthentication()).isFalse(); } @Test public void return_null_if_realm_is_ldap() { settings.setProperty("sonar.security.realm", "LDAP"); SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig()); factory.start(); assertThat(factory.getRealm()).isNull(); assertThat(factory.hasExternalAuthentication()).isFalse(); } @Test public void realm_not_found() { settings.setProperty("sonar.security.realm", "Fake"); try { new SecurityRealmFactory(settings.asConfig()); fail(); } catch (SonarException e) { assertThat(e.getMessage()).contains("Realm 'Fake' not found."); } } @Test public void should_provide_compatibility_for_authenticator() { settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, FakeAuthenticator.class.getName()); LoginPasswordAuthenticator authenticator = new FakeAuthenticator(); SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new LoginPasswordAuthenticator[] {authenticator}); SecurityRealm realm = factory.getRealm(); assertThat(realm).isInstanceOf(CompatibilityRealm.class); } @Test public void should_take_precedence_over_authenticator() { SecurityRealm realm = new FakeRealm(); settings.setProperty("sonar.security.realm", realm.getName()); LoginPasswordAuthenticator authenticator = new FakeAuthenticator(); settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, FakeAuthenticator.class.getName()); SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}, new LoginPasswordAuthenticator[] {authenticator}); assertThat(factory.getRealm()).isSameAs(realm); } @Test public void authenticator_not_found() { settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, "Fake"); try { new SecurityRealmFactory(settings.asConfig()); fail(); } catch (SonarException e) { assertThat(e.getMessage()).contains("Authenticator 'Fake' not found."); } } @Test public void ignore_startup_failure() { SecurityRealm realm = spy(new AlwaysFailsRealm()); settings.setProperty("sonar.security.realm", realm.getName()); settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_IGNORE_STARTUP_FAILURE, true); new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}).start(); verify(realm).init(); } @Test public void should_fail() { SecurityRealm realm = spy(new AlwaysFailsRealm()); settings.setProperty("sonar.security.realm", realm.getName()); try { new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}).start(); fail(); } catch (SonarException e) { assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); assertThat(e.getMessage()).contains("Security realm fails to start"); } } private static class AlwaysFailsRealm extends FakeRealm { @Override public void init() { throw new IllegalStateException(); } } private static class FakeRealm extends SecurityRealm { @Override public LoginPasswordAuthenticator getLoginPasswordAuthenticator() { return null; } } private static class FakeAuthenticator implements LoginPasswordAuthenticator { public void init() { } public boolean authenticate(String login, String password) { return false; } } }
5,573
32.578313
131
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/SystemPasscodeImplTest.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; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.event.Level; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.ws.SimpleGetRequest; import org.sonar.api.testfixtures.log.LogTester; import static org.assertj.core.api.Assertions.assertThat; @RunWith(DataProviderRunner.class) public class SystemPasscodeImplTest { @Rule public LogTester logTester = new LogTester(); private MapSettings settings = new MapSettings(); private SystemPasscodeImpl underTest = new SystemPasscodeImpl(settings.asConfig()); @After public void tearDown() { underTest.stop(); } @Test public void startup_logs_show_that_feature_is_enabled() { configurePasscode("foo"); underTest.start(); assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is enabled"); } @Test public void startup_logs_show_that_feature_is_disabled() { underTest.start(); assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled"); } @Test public void passcode_is_disabled_if_blank_configuration() { configurePasscode(""); underTest.start(); assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled"); } @DataProvider public static Object[][] passcodeConfigurationAndUserInput() { return new Object[][] { {"toto", "toto", true}, {"toto", "tata", false}, {"toto", "Toto", false}, {"toto", "toTo", false}, {null, null, false}, {null, "toto", false}, {"toto", null, false}, }; } @Test @UseDataProvider("passcodeConfigurationAndUserInput") public void isValidPasscode_worksCorrectly(String configuredPasscode, String userPasscode, boolean expectedResult) { configurePasscode(configuredPasscode); assertThat(underTest.isValidPasscode(userPasscode)).isEqualTo(expectedResult); } @Test @UseDataProvider("passcodeConfigurationAndUserInput") public void isValid_worksCorrectly(String configuredPasscode, String userPasscode, boolean expectedResult) { configurePasscode(configuredPasscode); SimpleGetRequest request = new SimpleGetRequest(); request.setHeader("X-Sonar-Passcode", userPasscode); assertThat(underTest.isValid(request)).isEqualTo(expectedResult); } private void configurePasscode(String propertyValue) { settings.setProperty("sonar.web.systemPasscode", propertyValue); underTest.start(); } }
3,589
31.636364
118
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ThreadLocalUserSessionTest.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; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.GroupTesting; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.AnonymousMockUserSession; import org.sonar.server.tester.MockUserSession; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.USER; public class ThreadLocalUserSessionTest { private final ThreadLocalUserSession threadLocalUserSession = new ThreadLocalUserSession(); @Before public void setUp() { // for test isolation threadLocalUserSession.unload(); } @After public void tearDown() { // clean up for next test threadLocalUserSession.unload(); } @Test public void get_session_for_user() { GroupDto group = GroupTesting.newGroupDto(); MockUserSession expected = new MockUserSession("karadoc") .setUuid("karadoc-uuid") .setResetPassword(true) .setLastSonarlintConnectionDate(1000L) .setGroups(group); threadLocalUserSession.set(expected); UserSession session = threadLocalUserSession.get(); assertThat(session).isSameAs(expected); assertThat(threadLocalUserSession.getLastSonarlintConnectionDate()).isEqualTo(1000L); assertThat(threadLocalUserSession.getLogin()).isEqualTo("karadoc"); assertThat(threadLocalUserSession.getUuid()).isEqualTo("karadoc-uuid"); assertThat(threadLocalUserSession.isLoggedIn()).isTrue(); assertThat(threadLocalUserSession.isActive()).isTrue(); assertThat(threadLocalUserSession.shouldResetPassword()).isTrue(); assertThat(threadLocalUserSession.getGroups()).extracting(GroupDto::getUuid).containsOnly(group.getUuid()); assertThat(threadLocalUserSession.hasChildProjectsPermission(USER, new ComponentDto())).isFalse(); assertThat(threadLocalUserSession.hasChildProjectsPermission(USER, new ProjectDto())).isFalse(); assertThat(threadLocalUserSession.hasPortfolioChildProjectsPermission(USER, new ComponentDto())).isFalse(); assertThat(threadLocalUserSession.hasEntityPermission(USER, new ProjectDto().getUuid())).isFalse(); } @Test public void get_session_for_anonymous() { AnonymousMockUserSession expected = new AnonymousMockUserSession(); threadLocalUserSession.set(expected); UserSession session = threadLocalUserSession.get(); assertThat(session).isSameAs(expected); assertThat(threadLocalUserSession.getLogin()).isNull(); assertThat(threadLocalUserSession.isLoggedIn()).isFalse(); assertThat(threadLocalUserSession.shouldResetPassword()).isFalse(); assertThat(threadLocalUserSession.getGroups()).isEmpty(); } @Test public void throw_UnauthorizedException_when_no_session() { assertThatThrownBy(threadLocalUserSession::get) .isInstanceOf(UnauthorizedException.class); } @Test public void throw_ForbiddenException_when_no_access_to_applications_projects() { GroupDto group = GroupTesting.newGroupDto(); MockUserSession expected = new MockUserSession("karadoc") .setUuid("karadoc-uuid") .setResetPassword(true) .setLastSonarlintConnectionDate(1000L) .setGroups(group); threadLocalUserSession.set(expected); ComponentDto componentDto = new ComponentDto().setQualifier(Qualifiers.APP); ProjectDto projectDto = new ProjectDto().setQualifier(Qualifiers.APP).setUuid("project-uuid"); assertThatThrownBy(() -> threadLocalUserSession.checkChildProjectsPermission(USER, componentDto)) .isInstanceOf(ForbiddenException.class); assertThatThrownBy(() -> threadLocalUserSession.checkChildProjectsPermission(USER, projectDto)) .isInstanceOf(ForbiddenException.class); } @Test public void checkChildProjectsPermission_gets_session_when_user_has_access_to_applications_projects() { GroupDto group = GroupTesting.newGroupDto(); MockUserSession expected = new MockUserSession("karadoc") .setUuid("karadoc-uuid") .setResetPassword(true) .setLastSonarlintConnectionDate(1000L) .setGroups(group); ProjectDto subProjectDto = new ProjectDto().setQualifier(Qualifiers.PROJECT).setUuid("subproject-uuid"); ProjectDto applicationAsProjectDto = new ProjectDto().setQualifier(Qualifiers.APP).setUuid("application-project-uuid"); expected.registerProjects(subProjectDto); expected.registerApplication(applicationAsProjectDto, subProjectDto); threadLocalUserSession.set(expected); assertThat(threadLocalUserSession.checkChildProjectsPermission(USER, applicationAsProjectDto)).isEqualTo(threadLocalUserSession); } }
5,744
41.242647
133
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserSessionFactoryImplTest.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; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class UserSessionFactoryImplTest { @InjectMocks private UserSessionFactoryImpl userSessionFactory; @Test public void createGithubWebhookUserSession_returnsNonNullGithubWebhookUserSession() { GithubWebhookUserSession githubWebhookUserSession = userSessionFactory.createGithubWebhookUserSession(); assertThat(githubWebhookUserSession).isNotNull(); } }
1,481
34.285714
108
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/TokenGeneratorImplTest.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; import org.junit.Test; import org.sonar.db.user.TokenType; import static org.assertj.core.api.Assertions.assertThat; public class TokenGeneratorImplTest { private final TokenGeneratorImpl underTest = new TokenGeneratorImpl(); @Test public void generate_different_tokens() { // this test is not enough to ensure that generated strings are unique, // but it still does a simple and stupid verification String firstToken = underTest.generate(TokenType.USER_TOKEN); String secondToken = underTest.generate(TokenType.USER_TOKEN); assertThat(firstToken) .isNotEqualTo(secondToken) .hasSize(44); } @Test public void generated_userToken_should_have_squ_prefix() { String token = underTest.generate(TokenType.USER_TOKEN); assertThat(token).matches("squ_.{40}"); } @Test public void generated_projectAnalysisToken_should_have_sqp_prefix() { String token = underTest.generate(TokenType.PROJECT_ANALYSIS_TOKEN); assertThat(token).matches("sqp_.{40}"); } @Test public void generated_globalAnalysisToken_should_have_sqa_prefix() { String token = underTest.generate(TokenType.GLOBAL_ANALYSIS_TOKEN); assertThat(token).matches("sqa_.{40}"); } @Test public void generateProjectBadgeToken_nullToken_shouldNotHavePrefix() { String token = underTest.generate(TokenType.PROJECT_BADGE_TOKEN); assertThat(token).matches("sqb_.{40}"); } @Test public void token_does_not_contain_colon() { assertThat(underTest.generate(TokenType.USER_TOKEN)).doesNotContain(":"); } @Test public void hash_token() { String hash = underTest.hash("1234567890123456789012345678901234567890"); assertThat(hash) .hasSize(96) .isEqualTo("b2501fc3833ae6feba7dc8a973a22d709b7c796ee97cbf66db2c22df873a9fa147b1b630878f771457b7769efd9ffa0d") .matches("[0-9a-f]+"); } }
2,748
31.341176
116
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/UserTokenModuleTest.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; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class UserTokenModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new UserTokenModule().configure(container); assertThat(container.getAddedObjects()).hasSize(7); } }
1,264
35.142857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/notification/TokenExpirationEmailComposerTest.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.notification; import java.net.MalformedURLException; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.EmailSettings; import org.sonar.db.user.TokenType; import org.sonar.db.user.UserTokenDto; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TokenExpirationEmailComposerTest { private final EmailSettings emailSettings = mock(EmailSettings.class); private final long createdAt = LocalDate.parse("2022-01-01").atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(); private final TokenExpirationEmailComposer underTest = new TokenExpirationEmailComposer(emailSettings); @Before public void setup() { when(emailSettings.getServerBaseURL()).thenReturn("http://localhost"); } @Test public void composer_email_with_expiring_project_token() throws MalformedURLException, EmailException { long expiredDate = LocalDate.now().atStartOfDay(ZoneOffset.UTC).plusDays(7).toInstant().toEpochMilli(); var token = createToken("projectToken", "projectA", expiredDate); var emailData = new TokenExpirationEmail("admin@sonarsource.com", token); var email = mock(HtmlEmail.class); underTest.addReportContent(email, emailData); verify(email).setSubject(String.format("Your token \"projectToken\" will expire.")); verify(email).setHtmlMsg( String.format("Your token \"projectToken\" will expire on %s.<br/><br/>" + "Token Summary<br/><br/>" + "Name: projectToken<br/>" + "Type: PROJECT_ANALYSIS_TOKEN<br/>" + "Project: projectA<br/>" + "Created on: January 01, 2022<br/>" + "Last used on: January 01, 2022<br/>" + "Expires on: %s<br/><br/>" + "If this token is still needed, please consider <a href=\"http://localhost/account/security/\">generating</a> an equivalent.<br/><br/>" + "Don't forget to update the token in the locations where it is in use. This may include the CI pipeline that analyzes your projects, the IDE settings that connect SonarLint to SonarQube, and any places where you make calls to web services.", parseDate(expiredDate), parseDate(expiredDate))); } @Test public void composer_email_with_expired_global_token() throws MalformedURLException, EmailException { long expiredDate = LocalDate.now().atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(); var token = createToken("globalToken", null, expiredDate); var emailData = new TokenExpirationEmail("admin@sonarsource.com", token); var email = mock(HtmlEmail.class); underTest.addReportContent(email, emailData); verify(email).setSubject("Your token \"globalToken\" has expired."); verify(email).setHtmlMsg( String.format("Your token \"globalToken\" has expired.<br/><br/>" + "Token Summary<br/><br/>" + "Name: globalToken<br/>" + "Type: GLOBAL_ANALYSIS_TOKEN<br/>" + "Created on: January 01, 2022<br/>" + "Last used on: January 01, 2022<br/>" + "Expired on: %s<br/><br/>" + "If this token is still needed, please consider <a href=\"http://localhost/account/security/\">generating</a> an equivalent.<br/><br/>" + "Don't forget to update the token in the locations where it is in use. This may include the CI pipeline that analyzes your projects, the IDE settings that connect SonarLint to SonarQube, and any places where you make calls to web services.", parseDate(expiredDate))); } private UserTokenDto createToken(String name, String project, long expired) { var token = new UserTokenDto(); token.setName(name); if (project != null) { token.setType(TokenType.PROJECT_ANALYSIS_TOKEN.name()); token.setProjectName(project); } else { token.setType(TokenType.GLOBAL_ANALYSIS_TOKEN.name()); } token.setCreatedAt(createdAt); token.setLastConnectionDate(createdAt); token.setExpirationDate(expired); return token; } private String parseDate(long timestamp) { return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC).toLocalDate().format(DateTimeFormatter.ofPattern("MMMM dd, yyyy")); } }
5,304
46.792793
253
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationExecutorServiceImplTest.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.notification; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class TokenExpirationNotificationExecutorServiceImplTest { @Test public void constructor_createsExecutorDelegateThatIsReadyToAct(){ TokenExpirationNotificationExecutorService tokenExpirationNotificationExecutorService = new TokenExpirationNotificationExecutorServiceImpl(); assertThat(tokenExpirationNotificationExecutorService.isShutdown()).isFalse(); assertThat(tokenExpirationNotificationExecutorService.isTerminated()).isFalse(); } }
1,441
39.055556
145
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationInitializerTest.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.notification; import org.junit.Test; import org.sonar.api.platform.Server; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class TokenExpirationNotificationInitializerTest { @Test public void when_scheduler_should_start_on_server_start() { var scheduler = mock(TokenExpirationNotificationScheduler.class); var underTest = new TokenExpirationNotificationInitializer(scheduler); underTest.onServerStart(mock(Server.class)); verify(scheduler, times(1)).startScheduling(); } @Test public void server_start_with_no_scheduler_still_work() { var underTest = new TokenExpirationNotificationInitializer(null); underTest.onServerStart(mock(Server.class)); assertThatNoException(); } }
1,749
36.234043
75
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationSchedulerImplTest.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.notification; import org.junit.Rule; import org.junit.Test; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.util.GlobalLockManager; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class TokenExpirationNotificationSchedulerImplTest { @Rule public LogTester logTester = new LogTester(); private final TokenExpirationNotificationExecutorService executorService = mock(TokenExpirationNotificationExecutorService.class); private final GlobalLockManager lockManager = mock(GlobalLockManager.class); private final TokenExpirationNotificationSender notificationSender = mock(TokenExpirationNotificationSender.class); private final TokenExpirationNotificationSchedulerImpl underTest = new TokenExpirationNotificationSchedulerImpl(executorService, lockManager, notificationSender); @Test public void startScheduling() { underTest.startScheduling(); verify(executorService, times(1)).scheduleAtFixedRate(any(Runnable.class), anyLong(), eq(DAYS.toSeconds(1)), eq(SECONDS)); } @Test public void no_notification_if_it_is_already_sent() { when(lockManager.tryLock(anyString(), anyInt())).thenReturn(false); underTest.notifyTokenExpiration(); verifyNoInteractions(notificationSender); } @Test public void log_error_if_exception_in_sending_notification() { when(lockManager.tryLock(anyString(), anyInt())).thenReturn(true); doThrow(new IllegalStateException()).when(notificationSender).sendNotifications(); underTest.notifyTokenExpiration(); assertThat(logTester.getLogs(LoggerLevel.ERROR)) .extracting(LogAndArguments::getFormattedMsg) .containsExactly("Error in sending token expiration notification"); } }
3,316
42.644737
143
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/notification/TokenExpirationNotificationSenderTest.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.notification; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.db.DbClient; import org.sonar.db.user.UserDao; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDao; import org.sonar.db.user.UserTokenDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TokenExpirationNotificationSenderTest { @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = mock(DbClient.class); private final TokenExpirationEmailComposer emailComposer = mock(TokenExpirationEmailComposer.class); private final TokenExpirationNotificationSender underTest = new TokenExpirationNotificationSender(dbClient, emailComposer); @Test public void no_notification_when_email_setting_is_not_set() { logTester.setLevel(Level.DEBUG); when(emailComposer.areEmailSettingsSet()).thenReturn(false); underTest.sendNotifications(); assertThat(logTester.getLogs(Level.DEBUG)) .extracting(LogAndArguments::getFormattedMsg) .containsExactly("Emails for token expiration notification have not been sent because email settings are not configured."); } @Test public void send_notification() { var expiringToken = new UserTokenDto().setUserUuid("admin"); var expiredToken = new UserTokenDto().setUserUuid("admin"); var user = mock(UserDto.class); when(user.getUuid()).thenReturn("admin"); when(user.getEmail()).thenReturn("admin@admin.com"); var userTokenDao = mock(UserTokenDao.class); var userDao = mock(UserDao.class); when(userDao.selectByUuids(any(), any())).thenReturn(List.of(user)); when(userTokenDao.selectTokensExpiredInDays(any(), eq(7L))).thenReturn(List.of(expiringToken)); when(userTokenDao.selectTokensExpiredInDays(any(), eq(0L))).thenReturn(List.of(expiredToken)); when(dbClient.userTokenDao()).thenReturn(userTokenDao); when(dbClient.userDao()).thenReturn(userDao); when(emailComposer.areEmailSettingsSet()).thenReturn(true); underTest.sendNotifications(); var argumentCaptor = ArgumentCaptor.forClass(TokenExpirationEmail.class); verify(emailComposer, times(2)).send(argumentCaptor.capture()); List<TokenExpirationEmail> emails = argumentCaptor.getAllValues(); assertThat(emails).hasSize(2); assertThat(emails.get(0).getRecipients()).containsOnly("admin@admin.com"); assertThat(emails.get(0).getUserToken()).isEqualTo(expiringToken); assertThat(emails.get(1).getRecipients()).containsOnly("admin@admin.com"); assertThat(emails.get(1).getUserToken()).isEqualTo(expiredToken); } }
3,906
42.898876
129
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/authentication/IdentityProviderRepositoryRule.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; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.sonar.api.server.authentication.IdentityProvider; public class IdentityProviderRepositoryRule extends IdentityProviderRepository implements TestRule { public IdentityProviderRepositoryRule() { super(null); } public IdentityProviderRepositoryRule addIdentityProvider(IdentityProvider identityProvider) { providersByKey.put(identityProvider.getKey(), identityProvider); return this; } @Override public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { providersByKey.clear(); } } }; } }
1,731
31.679245
100
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/authentication/TestIdentityProvider.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; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.IdentityProvider; public class TestIdentityProvider implements IdentityProvider { private String key; private String name; private Display display; private boolean enabled; private boolean allowsUsersToSignUp; @Override public String getKey() { return key; } public TestIdentityProvider setKey(String key) { this.key = key; return this; } @Override public String getName() { return name; } public TestIdentityProvider setName(String name) { this.name = name; return this; } @Override public Display getDisplay() { return display; } public TestIdentityProvider setDisplay(Display display) { this.display = display; return this; } @Override public boolean isEnabled() { return enabled; } public TestIdentityProvider setEnabled(boolean enabled) { this.enabled = enabled; return this; } @Override public boolean allowsUsersToSignUp() { return allowsUsersToSignUp; } public TestIdentityProvider setAllowsUsersToSignUp(boolean allowsUsersToSignUp) { this.allowsUsersToSignUp = allowsUsersToSignUp; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (getClass() != o.getClass()) { return false; } TestIdentityProvider that = (TestIdentityProvider) o; return key.equals(that.key); } @Override public int hashCode() { return key.hashCode(); } }
2,446
23.227723
83
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/language/LanguageTesting.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.language; import com.google.common.collect.Collections2; import org.apache.commons.lang.StringUtils; import org.sonar.api.resources.AbstractLanguage; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.core.util.NonNullInputFunction; import java.util.Arrays; public class LanguageTesting { public static Language newLanguage(String key, String name, final String... prefixes) { return new AbstractLanguage(key, name) { @Override public String[] getFileSuffixes() { return prefixes; } }; } public static Language newLanguage(String key) { return newLanguage(key, StringUtils.capitalize(key)); } public static Languages newLanguages(String... languageKeys) { return new Languages(Collections2.transform(Arrays.asList(languageKeys), new NonNullInputFunction<String, Language>() { @Override protected Language doApply(String languageKey) { return newLanguage(languageKey); } }).toArray(new Language[0])); } }
1,912
33.160714
123
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/tester/AbstractMockUserSession.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.tester; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.web.UserRole; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.user.AbstractUserSession; import static com.google.common.base.Preconditions.checkArgument; public abstract class AbstractMockUserSession<T extends AbstractMockUserSession> extends AbstractUserSession { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMockUserSession.class); private static final Set<String> PUBLIC_PERMISSIONS = ImmutableSet.of(UserRole.USER, UserRole.CODEVIEWER); // FIXME to check with Simon private final Class<T> clazz; private final HashMultimap<String, String> projectUuidByPermission = HashMultimap.create(); private final Set<GlobalPermission> permissions = new HashSet<>(); private final Map<String, String> projectUuidByComponentUuid = new HashMap<>(); private final Map<String, String> projectUuidByBranchUuid = new HashMap<>(); private final Map<String, Set<String>> applicationProjects = new HashMap<>(); private final Map<String, Set<String>> portfolioProjects = new HashMap<>(); private final Set<String> projectPermissions = new HashSet<>(); private boolean systemAdministrator = false; private boolean resetPassword = false; protected AbstractMockUserSession(Class<T> clazz) { this.clazz = clazz; } public T addPermission(GlobalPermission permission) { permissions.add(permission); return clazz.cast(this); } @Override protected boolean hasPermissionImpl(GlobalPermission permission) { return permissions.contains(permission); } /** * Use this method to register public root component and non root components the UserSession must be aware of. * (ie. this method can be used to emulate the content of the DB) */ public T registerComponents(ComponentDto... components) { Arrays.stream(components) .forEach(component -> { if (component.branchUuid().equals(component.uuid()) && !component.isPrivate()) { this.projectUuidByPermission.put(UserRole.USER, component.uuid()); this.projectUuidByPermission.put(UserRole.CODEVIEWER, component.uuid()); this.projectPermissions.add(UserRole.USER); this.projectPermissions.add(UserRole.CODEVIEWER); } this.projectUuidByComponentUuid.put(component.uuid(), component.branchUuid()); }); return clazz.cast(this); } public T registerProjects(ProjectDto... projects) { Arrays.stream(projects) .forEach(project -> { if (!project.isPrivate()) { this.projectUuidByPermission.put(UserRole.USER, project.getUuid()); this.projectUuidByPermission.put(UserRole.CODEVIEWER, project.getUuid()); this.projectPermissions.add(UserRole.USER); this.projectPermissions.add(UserRole.CODEVIEWER); } this.projectUuidByComponentUuid.put(project.getUuid(), project.getUuid()); }); return clazz.cast(this); } public T registerApplication(ProjectDto application, ProjectDto... appProjects) { registerProjects(application); registerProjects(appProjects); var appProjectsUuid = Arrays.stream(appProjects) .map(ProjectDto::getUuid) .collect(Collectors.toSet()); this.applicationProjects.put(application.getUuid(), appProjectsUuid); return clazz.cast(this); } public T registerPortfolios(PortfolioDto... portfolios) { Arrays.stream(portfolios) .forEach(portfolio -> { if (!portfolio.isPrivate()) { this.projectUuidByPermission.put(UserRole.USER, portfolio.getUuid()); this.projectUuidByPermission.put(UserRole.CODEVIEWER, portfolio.getUuid()); this.projectPermissions.add(UserRole.USER); this.projectPermissions.add(UserRole.CODEVIEWER); } this.projectUuidByComponentUuid.put(portfolio.getUuid(), portfolio.getUuid()); }); return clazz.cast(this); } public T registerBranches(BranchDto ...branchDtos){ Arrays.stream(branchDtos) .forEach(branch -> projectUuidByBranchUuid.put(branch.getUuid(), branch.getProjectUuid())); return clazz.cast(this); } /** * Branches need to be registered in order to save the mapping between branch and project. */ public T addProjectBranchMapping(String projectUuid, ComponentDto... componentDtos) { Arrays.stream(componentDtos) .forEach(componentDto -> projectUuidByBranchUuid.put(componentDto.uuid(), projectUuid)); return clazz.cast(this); } public T addProjectPermission(String permission, ComponentDto... components) { Arrays.stream(components).forEach(component -> { checkArgument( component.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), "public component %s can't be granted public permission %s", component.uuid(), permission); }); registerComponents(components); this.projectPermissions.add(permission); Arrays.stream(components) .forEach(component -> this.projectUuidByPermission.put(permission, component.branchUuid())); return clazz.cast(this); } public T addProjectPermission(String permission, ProjectDto... projects) { Arrays.stream(projects).forEach(component -> { checkArgument( component.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), "public component %s can't be granted public permission %s", component.getUuid(), permission); }); registerProjects(projects); this.projectPermissions.add(permission); Arrays.stream(projects) .forEach(project -> this.projectUuidByPermission.put(permission, project.getUuid())); return clazz.cast(this); } public T addPortfolioPermission(String permission, PortfolioDto... portfolios) { Arrays.stream(portfolios).forEach(component -> { checkArgument( component.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), "public component %s can't be granted public permission %s", component.getUuid(), permission); }); registerPortfolios(portfolios); this.projectPermissions.add(permission); Arrays.stream(portfolios) .forEach(portfolio -> this.projectUuidByPermission.put(permission, portfolio.getUuid())); return clazz.cast(this); } @Override protected Optional<String> componentUuidToEntityUuid(String componentUuid) { return Optional.ofNullable(Optional.ofNullable(projectUuidByBranchUuid.get(componentUuid)) .orElse(projectUuidByComponentUuid.get(componentUuid))); } @Override public boolean hasComponentPermission(String permission, ComponentDto component) { return componentUuidToEntityUuid(component.uuid()) .or(() -> componentUuidToEntityUuid(component.branchUuid())) .map(projectUuid -> hasEntityUuidPermission(permission, projectUuid)).orElseGet(() -> { LOGGER.warn("No project uuid for branchUuid : {}", component.branchUuid()); return false; }); } @Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { return projectPermissions.contains(permission) && projectUuidByPermission.get(permission).contains(entityUuid); } @Override protected boolean hasChildProjectsPermission(String permission, String applicationUuid) { return applicationProjects.containsKey(applicationUuid) && applicationProjects.get(applicationUuid) .stream() .allMatch(projectUuid -> projectPermissions.contains(permission) && projectUuidByPermission.get(permission).contains(projectUuid)); } @Override protected boolean hasPortfolioChildProjectsPermission(String permission, String portfolioUuid) { return portfolioProjects.containsKey(portfolioUuid) && portfolioProjects.get(portfolioUuid) .stream() .allMatch(projectUuid -> projectPermissions.contains(permission) && projectUuidByPermission.get(permission).contains(projectUuid)); } public T setSystemAdministrator(boolean b) { this.systemAdministrator = b; return clazz.cast(this); } @Override public boolean isSystemAdministrator() { return systemAdministrator; } public T setResetPassword(boolean b) { this.resetPassword = b; return clazz.cast(this); } @Override public boolean shouldResetPassword() { return resetPassword; } }
9,611
39.05
137
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/tester/AnonymousMockUserSession.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.tester; import java.util.Collection; import java.util.Collections; import java.util.Optional; import org.sonar.db.user.GroupDto; public class AnonymousMockUserSession extends AbstractMockUserSession<AnonymousMockUserSession> { public AnonymousMockUserSession() { super(AnonymousMockUserSession.class); } @Override public boolean isActive() { return false; } @Override public String getLogin() { return null; } @Override public String getUuid() { return null; } @Override public String getName() { return null; } @Override public boolean isLoggedIn() { return false; } @Override public Collection<GroupDto> getGroups() { return Collections.emptyList(); } @Override public Optional<IdentityProvider> getIdentityProvider() { return Optional.empty(); } @Override public Optional<ExternalIdentity> getExternalIdentity() { return Optional.empty(); } }
1,813
23.849315
97
java