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-api/src/test/java/org/sonar/server/rule/WebServerRuleFinderImplTest.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.rule;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.rules.RuleFinder;
import org.sonar.db.DbClient;
import org.sonar.db.rule.RuleDao;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WebServerRuleFinderImplTest {
private DbClient dbClient = mock(DbClient.class);
private WebServerRuleFinderImpl underTest = new WebServerRuleFinderImpl(dbClient, mock(RuleDescriptionFormatter.class));
@Before
public void setUp() {
when(dbClient.ruleDao()).thenReturn(mock(RuleDao.class));
}
@Test
public void constructor_initializes_with_non_caching_delegate() {
assertThat(underTest.delegate).isInstanceOf(DefaultRuleFinder.class);
}
@Test
public void startCaching_sets_caching_delegate() {
underTest.startCaching();
assertThat(underTest.delegate).isInstanceOf(CachingRuleFinder.class);
}
@Test
public void stopCaching_restores_non_caching_delegate() {
RuleFinder nonCachingDelegate = underTest.delegate;
underTest.startCaching();
underTest.stopCaching();
assertThat(underTest.delegate).isSameAs(nonCachingDelegate);
}
}
| 2,069 | 31.34375 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/setting/SettingsChangeNotifierTest.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.setting;
import org.junit.Test;
import org.sonar.api.config.GlobalPropertyChangeHandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class SettingsChangeNotifierTest {
@Test
public void onGlobalPropertyChange() {
GlobalPropertyChangeHandler handler = mock(GlobalPropertyChangeHandler.class);
SettingsChangeNotifier notifier = new SettingsChangeNotifier(new GlobalPropertyChangeHandler[] {handler});
notifier.onGlobalPropertyChange("foo", "bar");
verify(handler).onChange(argThat(change -> change.getKey().equals("foo") && change.getNewValue().equals("bar")));
}
@Test
public void no_handlers() {
SettingsChangeNotifier notifier = new SettingsChangeNotifier();
assertThat(notifier.changeHandlers).isEmpty();
// does not fail
notifier.onGlobalPropertyChange("foo", "bar");
}
}
| 1,850 | 35.294118 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/BooleanTypeValidationTest.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.util;
import org.junit.Test;
import org.sonar.server.exceptions.BadRequestException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BooleanTypeValidationTest {
private BooleanTypeValidation underTest = new BooleanTypeValidation();
@Test
public void key() {
assertThat(underTest.key()).isEqualTo("BOOLEAN");
}
@Test
public void not_fail_on_valid_boolean() {
underTest.validate("true", null);
underTest.validate("True", null);
underTest.validate("false", null);
underTest.validate("FALSE", null);
}
@Test
public void fail_on_invalid_boolean() {
assertThatThrownBy(() -> underTest.validate("abc", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value 'abc' must be one of \"true\" or \"false\".");
}
}
| 1,733 | 32.346154 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/FloatTypeValidationTest.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.util;
import org.junit.Test;
import org.sonar.server.exceptions.BadRequestException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class FloatTypeValidationTest {
private FloatTypeValidation validation = new FloatTypeValidation();
@Test
public void key() {
assertThat(validation.key()).isEqualTo("FLOAT");
}
@Test
public void not_fail_on_valid_float() {
validation.validate("10.2", null);
validation.validate("10", null);
validation.validate("-10.3", null);
}
@Test
public void fail_on_invalid_float() {
assertThatThrownBy(() -> validation.validate("abc", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value 'abc' must be an floating point number.");
}
}
| 1,682 | 32 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.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.util;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.InternalPropertiesDao;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.property.InternalPropertiesDao.LOCK_NAME_MAX_LENGTH;
import static org.sonar.server.util.GlobalLockManager.DEFAULT_LOCK_DURATION_SECONDS;
@RunWith(DataProviderRunner.class)
public class GlobalLockManagerImplTest {
private final DbClient dbClient = mock(DbClient.class);
private final InternalPropertiesDao internalPropertiesDao = mock(InternalPropertiesDao.class);
private final DbSession dbSession = mock(DbSession.class);
private final GlobalLockManager underTest = new GlobalLockManagerImpl(dbClient);
@Before
public void wire_db_mocks() {
when(dbClient.openSession(false)).thenReturn(dbSession);
when(dbClient.internalPropertiesDao()).thenReturn(internalPropertiesDao);
}
@Test
public void tryLock_fails_with_IAE_if_name_is_empty() {
String badLockName = "";
expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName);
}
@Test
public void tryLock_fails_with_IAE_if_name_length_is_more_than_max_or_more() {
String badLockName = RandomStringUtils.random(LOCK_NAME_MAX_LENGTH + 1 + new Random().nextInt(96));
expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName);
}
@Test
public void tryLock_accepts_name_with_allowed_length() {
for (int i = 1; i <= LOCK_NAME_MAX_LENGTH; i++) {
String lockName = RandomStringUtils.random(i);
assertThatNoException().isThrownBy(() -> underTest.tryLock(lockName));
}
}
@Test
@UseDataProvider("randomValidLockName")
public void tryLock_delegates_to_internalPropertiesDao_and_commits(String randomValidLockName) {
boolean expected = new Random().nextBoolean();
when(internalPropertiesDao.tryLock(dbSession, randomValidLockName, DEFAULT_LOCK_DURATION_SECONDS))
.thenReturn(expected);
assertThat(underTest.tryLock(randomValidLockName)).isEqualTo(expected);
verify(dbClient).openSession(false);
verify(internalPropertiesDao).tryLock(dbSession, randomValidLockName, DEFAULT_LOCK_DURATION_SECONDS);
verify(dbSession).commit();
verifyNoMoreInteractions(internalPropertiesDao);
}
@Test
@UseDataProvider("randomValidDuration")
public void tryLock_with_duration_fails_with_IAE_if_name_is_empty(int randomValidDuration) {
String badLockName = "";
expectBadLockNameIAE(() -> underTest.tryLock(badLockName, randomValidDuration), badLockName);
}
@Test
@UseDataProvider("randomValidDuration")
public void tryLock_with_duration_accepts_name_with_length_15_or_less(int randomValidDuration) {
for (int i = 1; i <= 15; i++) {
underTest.tryLock(RandomStringUtils.random(i), randomValidDuration);
}
}
@Test
@UseDataProvider("randomValidDuration")
public void tryLock_with_duration_fails_with_IAE_if_name_length_is_36_or_more(int randomValidDuration) {
String badLockName = RandomStringUtils.random(LOCK_NAME_MAX_LENGTH + 1 + new Random().nextInt(65));
expectBadLockNameIAE(() -> underTest.tryLock(badLockName, randomValidDuration), badLockName);
}
@Test
@UseDataProvider("randomValidLockName")
public void tryLock_with_duration_fails_with_IAE_if_duration_is_0(String randomValidLockName) {
expectBadDuration(() -> underTest.tryLock(randomValidLockName, 0), 0);
}
@Test
@UseDataProvider("randomValidLockName")
public void tryLock_with_duration_fails_with_IAE_if_duration_is_less_than_0(String randomValidLockName) {
int negativeDuration = -1 - new Random().nextInt(100);
expectBadDuration(() -> underTest.tryLock(randomValidLockName, negativeDuration), negativeDuration);
}
@Test
@UseDataProvider("randomValidDuration")
public void tryLock_with_duration_delegates_to_InternalPropertiesDao_and_commits(int randomValidDuration) {
String lockName = "foo";
boolean expected = new Random().nextBoolean();
when(internalPropertiesDao.tryLock(dbSession, lockName, randomValidDuration))
.thenReturn(expected);
assertThat(underTest.tryLock(lockName, randomValidDuration)).isEqualTo(expected);
verify(dbClient).openSession(false);
verify(internalPropertiesDao).tryLock(dbSession, lockName, randomValidDuration);
verify(dbSession).commit();
verifyNoMoreInteractions(internalPropertiesDao);
}
@DataProvider
public static Object[][] randomValidLockName() {
return new Object[][] {
{randomAlphabetic(1 + new Random().nextInt(LOCK_NAME_MAX_LENGTH))}
};
}
@DataProvider
public static Object[][] randomValidDuration() {
return new Object[][] {
{1 + new Random().nextInt(2_00)}
};
}
private void expectBadLockNameIAE(ThrowingCallable callback, String badLockName) {
assertThatThrownBy(callback)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("name's length must be > 0 and <= " + LOCK_NAME_MAX_LENGTH + ": '" + badLockName + "'");
}
private void expectBadDuration(ThrowingCallable callback, int badDuration) {
assertThatThrownBy(callback)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("duration must be > 0: " + badDuration);
}
}
| 6,891 | 37.719101 | 109 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/IntegerTypeValidationTest.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.util;
import org.junit.Test;
import org.sonar.server.exceptions.BadRequestException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class IntegerTypeValidationTest {
private IntegerTypeValidation validation = new IntegerTypeValidation();
@Test
public void key() {
assertThat(validation.key()).isEqualTo("INTEGER");
}
@Test
public void not_fail_on_valid_integer() {
validation.validate("10", null);
validation.validate("-10", null);
}
@Test
public void fail_on_string() {
assertThatThrownBy(() -> validation.validate("abc", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value 'abc' must be an integer.");
}
@Test
public void fail_on_float() {
assertThatThrownBy(() -> validation.validate("10.1", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value '10.1' must be an integer.");
}
}
| 1,842 | 30.775862 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.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.util;
import org.junit.Test;
import org.sonar.api.PropertyType;
import org.sonar.server.exceptions.BadRequestException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class LongTypeValidationTest {
LongTypeValidation underTest = new LongTypeValidation();
@Test
public void key_is_long_type_name() {
assertThat(underTest.key()).isEqualTo(PropertyType.LONG.name());
}
@Test
public void do_not_fail_with_long_values() {
underTest.validate("1984", null);
underTest.validate("-1984", null);
}
@Test
public void fail_when_float() {
assertThatThrownBy(() -> underTest.validate("3.14", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value '3.14' must be a long.");
}
@Test
public void fail_when_string() {
assertThatThrownBy(() -> underTest.validate("original string", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value 'original string' must be a long.");
}
}
| 1,913 | 32 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/StringListTypeValidationTest.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.util;
import org.junit.Test;
import org.sonar.server.exceptions.BadRequestException;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class StringListTypeValidationTest {
private StringListTypeValidation validation = new StringListTypeValidation();
@Test
public void key() {
assertThat(validation.key()).isEqualTo("SINGLE_SELECT_LIST");
}
@Test
public void not_fail_on_valid_option() {
validation.validate("a", newArrayList("a", "b", "c"));
validation.validate("a", null);
}
@Test
public void fail_on_invalid_option() {
assertThatThrownBy(() -> validation.validate("abc", newArrayList("a", "b", "c")))
.isInstanceOf(BadRequestException.class)
.hasMessage("Value 'abc' must be one of : a, b, c.");
}
}
| 1,766 | 33.647059 | 85 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/StringTypeValidationTest.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.util;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringTypeValidationTest {
StringTypeValidation validation;
@Before
public void setUp() {
validation = new StringTypeValidation();
}
@Test
public void key() {
assertThat(validation.key()).isEqualTo("STRING");
}
@Test
public void not_fail_on_valid_string() {
validation.validate("10", null);
validation.validate("abc", null);
}
}
| 1,366 | 27.479167 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TextTypeValidationTest.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.util;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TextTypeValidationTest {
TextTypeValidation validation;
@Before
public void setUp() {
validation = new TextTypeValidation();
}
@Test
public void key() {
assertThat(validation.key()).isEqualTo("TEXT");
}
@Test
public void not_fail_on_valid_text() {
validation.validate("10", null);
validation.validate("abc", null);
}
}
| 1,356 | 27.270833 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TypeValidationModuleTest.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.util;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class TypeValidationModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new TypeValidationModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(9);
}
}
| 1,269 | 35.285714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TypeValidationsTest.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.util;
import org.junit.Test;
import org.sonar.server.exceptions.BadRequestException;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class TypeValidationsTest {
@Test
public void validate() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
TypeValidations typeValidations = new TypeValidations(newArrayList(fakeTypeValidation));
typeValidations.validate("10", "Fake", newArrayList("a"));
verify(fakeTypeValidation).validate("10", newArrayList("a"));
}
@Test
public void validate__multiple_values() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
TypeValidations typeValidations = new TypeValidations(newArrayList(fakeTypeValidation));
typeValidations.validate(newArrayList("10", "11", "12"), "Fake", newArrayList("11"));
verify(fakeTypeValidation).validate("10", newArrayList("11"));
}
@Test
public void fail_on_unknown_type() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
try {
TypeValidations typeValidations = new TypeValidations(newArrayList(fakeTypeValidation));
typeValidations.validate("10", "Unknown", null);
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(BadRequestException.class);
BadRequestException badRequestException = (BadRequestException) e;
assertThat(badRequestException.getMessage()).isEqualTo("Type 'Unknown' is not valid.");
}
}
}
| 2,702 | 36.027397 | 94 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/fake-report-plugin/src/BasePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class BasePlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,023 | 32.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/fake-report-plugin/src/org/sonar/plugins/testbase/api/BaseApi.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.plugins.testbase.api;
public class BaseApi {
public void doNothing() {
}
}
| 941 | 35.230769 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/fake-sqale-plugin/src/BasePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class BasePlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,023 | 32.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/fake-sqale-plugin/src/org/sonar/plugins/testbase/api/BaseApi.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.plugins.testbase.api;
public class BaseApi {
public void doNothing() {
}
}
| 941 | 35.230769 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/fake-views-plugin/src/BasePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class BasePlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,023 | 32.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/fake-views-plugin/src/org/sonar/plugins/testbase/api/BaseApi.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.plugins.testbase.api;
public class BaseApi {
public void doNothing() {
}
}
| 941 | 35.230769 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-base-plugin-v2/src/BasePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class BasePlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,023 | 32.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-base-plugin-v2/src/org/sonar/plugins/testbase/api/BaseApi.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.plugins.testbase.api;
public class BaseApi {
public void doNothing() {
}
}
| 941 | 35.230769 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-base-plugin/src/BasePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class BasePlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,023 | 32.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-base-plugin/src/org/sonar/plugins/testbase/api/BaseApi.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.plugins.testbase.api;
public class BaseApi {
public void doNothing() {
}
}
| 941 | 35.230769 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-extend-plugin/src/ExtendPlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class ExtendPlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,025 | 32.096774 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-libs-plugin/src/LibsPlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class LibsPlugin extends Plugin {
public void define(Plugin.Context context) {
}
}
| 1,023 | 32.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-require-plugin/src/RequirePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class RequirePlugin extends Plugin {
public RequirePlugin() {
// call a class that is in the api published by the base plugin
new org.sonar.plugins.testbase.api.BaseApi().doNothing();
}
public void define(Plugin.Context context) {
}
}
| 1,188 | 32.027778 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/test/projects/test-requirenew-plugin/src/RequirePlugin.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.
*/
import org.sonar.api.Plugin;
import java.util.Collections;
import java.util.List;
public class RequirePlugin extends Plugin {
public RequirePlugin() {
// call a class that is in the api published by the base plugin
new org.sonar.plugins.testbase.api.BaseApi().doNothing();
}
public void define(Plugin.Context context) {
}
}
| 1,189 | 31.162162 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/testFixtures/java/org/sonar/server/util/GlobalLockManagerRule.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.util;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import static org.sonar.api.utils.Preconditions.checkArgument;
/**
* {@link org.junit.Rule} implementing {@link GlobalLockManager} to test against this interface without consideration
* of time, only attempts to acquire a given lock.
*/
public class GlobalLockManagerRule extends ExternalResource implements GlobalLockManager {
private final Map<String, Deque<Boolean>> lockAttemptsByLockName = new HashMap<>();
@Test
public GlobalLockManagerRule addAttempt(String lockName, boolean success) {
lockAttemptsByLockName.compute(lockName, (k, v) -> {
Deque<Boolean> queue = v == null ? new ArrayDeque<>() : v;
queue.push(success);
return queue;
});
return this;
}
@Override
public boolean tryLock(String name) {
checkArgument(!name.isEmpty() && name.length() <= LOCK_NAME_MAX_LENGTH, "invalid lock name");
Deque<Boolean> deque = lockAttemptsByLockName.get(name);
Boolean res = deque == null ? null : deque.pop();
if (res == null) {
throw new IllegalStateException("No more attempt value available");
}
return res;
}
@Override
public boolean tryLock(String name, int durationSecond) {
checkArgument(durationSecond > 0, "negative duration not allowed");
return tryLock(name);
}
}
| 2,312 | 33.522388 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/CredentialsAuthenticationIT.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.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import static java.lang.String.format;
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.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.authentication.CredentialsAuthentication.ERROR_PASSWORD_CANNOT_BE_NULL;
import static org.sonar.server.authentication.CredentialsLocalAuthentication.ERROR_UNKNOWN_HASH_METHOD;
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 CredentialsAuthenticationIT {
private static final String LOGIN = "LOGIN";
private static final String PASSWORD = "PASSWORD";
private static final String SALT = "0242b0b4c0a93ddfe09dd886de50bc25ba000b51";
private static final int NUMBER_OF_PBKDF2_ITERATIONS = 1;
private static final String ENCRYPTED_PASSWORD = format("%d$%s", NUMBER_OF_PBKDF2_ITERATIONS, "FVu1Wtpe0MM/Rs+CcLT7nbzMMQ0emHDXpcfjJoQrDtCe8cQqWP4rpCXZenBw9bC3/UWx5+kA9go9zKkhq2UmAQ==");
private static final String DEPRECATED_HASH_METHOD = "SHA1";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbTester.getSession();
private final HttpRequest request = mock(HttpRequest.class);
private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", NUMBER_OF_PBKDF2_ITERATIONS);
private final CredentialsExternalAuthentication externalAuthentication = mock(CredentialsExternalAuthentication.class);
private final CredentialsLocalAuthentication localAuthentication = spy(new CredentialsLocalAuthentication(dbClient, settings.asConfig()));
private final LdapCredentialsAuthentication ldapCredentialsAuthentication = mock(LdapCredentialsAuthentication.class);
private final CredentialsAuthentication underTest = new CredentialsAuthentication(dbClient, authenticationEvent, externalAuthentication, localAuthentication,
ldapCredentialsAuthentication);
@Test
public void authenticate_local_user() {
insertUser(newUserDto()
.setLogin(LOGIN)
.setCryptedPassword(ENCRYPTED_PASSWORD)
.setHashMethod(CredentialsLocalAuthentication.HashMethod.PBKDF2.name())
.setSalt(SALT)
.setLocal(true));
UserDto userDto = executeAuthenticate(BASIC);
assertThat(userDto.getLogin()).isEqualTo(LOGIN);
verify(authenticationEvent).loginSuccess(request, LOGIN, Source.local(BASIC));
}
@Test
public void fail_to_authenticate_local_user_when_password_is_wrong() {
insertUser(newUserDto()
.setLogin(LOGIN)
.setCryptedPassword(format("%d$%s", NUMBER_OF_PBKDF2_ITERATIONS, "WrongPassword"))
.setSalt("salt")
.setHashMethod(CredentialsLocalAuthentication.HashMethod.PBKDF2.name())
.setLocal(true));
assertThatThrownBy(() -> executeAuthenticate(BASIC))
.hasMessage("wrong password")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.local(BASIC))
.hasFieldOrPropertyWithValue("login", LOGIN);
verifyNoInteractions(authenticationEvent);
}
@Test
public void authenticate_external_user() {
when(externalAuthentication.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)).thenReturn(Optional.of(newUserDto()));
insertUser(newUserDto()
.setLogin(LOGIN)
.setLocal(false));
executeAuthenticate(BASIC);
verify(externalAuthentication).authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC);
verifyNoInteractions(ldapCredentialsAuthentication);
verifyNoInteractions(authenticationEvent);
}
@Test
public void authenticate_ldap_user() {
when(externalAuthentication.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)).thenReturn(Optional.empty());
String externalId = "12345";
when(ldapCredentialsAuthentication.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)).thenReturn(Optional.of(newUserDto().setExternalId(externalId)));
insertUser(newUserDto()
.setLogin(LOGIN)
.setLocal(false));
assertThat(executeAuthenticate(BASIC).getExternalId()).isEqualTo(externalId);
verify(externalAuthentication).authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC);
verify(ldapCredentialsAuthentication).authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC);
verifyNoInteractions(authenticationEvent);
}
@Test
public void fail_to_authenticate_external_user_when_no_external_and_ldap_authentication() {
when(externalAuthentication.authenticate(new Credentials(LOGIN, PASSWORD), request, SONARQUBE_TOKEN)).thenReturn(Optional.empty());
when(ldapCredentialsAuthentication.authenticate(new Credentials(LOGIN, PASSWORD), request, SONARQUBE_TOKEN)).thenReturn(Optional.empty());
insertUser(newUserDto()
.setLogin(LOGIN)
.setLocal(false));
assertThatThrownBy(() -> executeAuthenticate(SONARQUBE_TOKEN))
.hasMessage("User is not local")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.local(SONARQUBE_TOKEN))
.hasFieldOrPropertyWithValue("login", LOGIN);
verify(externalAuthentication).authenticate(new Credentials(LOGIN, PASSWORD), request, SONARQUBE_TOKEN);
verify(ldapCredentialsAuthentication).authenticate(new Credentials(LOGIN, PASSWORD), request, SONARQUBE_TOKEN);
verifyNoInteractions(authenticationEvent);
}
@Test
public void fail_to_authenticate_local_user_that_have_no_password() {
insertUser(newUserDto()
.setLogin(LOGIN)
.setCryptedPassword(null)
.setSalt(SALT)
.setHashMethod(CredentialsLocalAuthentication.HashMethod.PBKDF2.name())
.setLocal(true));
assertThatThrownBy(() -> executeAuthenticate(BASIC))
.hasMessage("null password in DB")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.local(BASIC))
.hasFieldOrPropertyWithValue("login", LOGIN);
verifyNoInteractions(authenticationEvent);
}
@Test
public void fail_to_authenticate_local_user_that_have_no_salt() {
insertUser(newUserDto()
.setLogin(LOGIN)
.setCryptedPassword(ENCRYPTED_PASSWORD)
.setSalt(null)
.setHashMethod(CredentialsLocalAuthentication.HashMethod.PBKDF2.name())
.setLocal(true));
assertThatThrownBy(() -> executeAuthenticate(SONARQUBE_TOKEN))
.hasMessage("null salt")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.local(SONARQUBE_TOKEN))
.hasFieldOrPropertyWithValue("login", LOGIN);
verifyNoInteractions(authenticationEvent);
}
@Test
public void fail_to_authenticate_unknown_hash_method_should_force_hash() {
insertUser(newUserDto()
.setLogin(LOGIN)
.setCryptedPassword(ENCRYPTED_PASSWORD)
.setSalt(SALT)
.setHashMethod(DEPRECATED_HASH_METHOD)
.setLocal(true));
assertThatThrownBy(() -> executeAuthenticate(SONARQUBE_TOKEN))
.hasMessage(format(ERROR_UNKNOWN_HASH_METHOD, DEPRECATED_HASH_METHOD))
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.local(SONARQUBE_TOKEN))
.hasFieldOrPropertyWithValue("login", LOGIN);
verify(localAuthentication).generateHashToAvoidEnumerationAttack();
verifyNoInteractions(authenticationEvent);
}
@Test
public void local_authentication_without_password_should_throw_IAE() {
insertUser(newUserDto()
.setLogin(LOGIN)
.setCryptedPassword(ENCRYPTED_PASSWORD)
.setSalt(SALT)
.setHashMethod(DEPRECATED_HASH_METHOD)
.setLocal(true));
Credentials credentials = new Credentials(LOGIN, null);
assertThatThrownBy(() -> underTest.authenticate(credentials, request, SONARQUBE_TOKEN))
.hasMessage(ERROR_PASSWORD_CANNOT_BE_NULL)
.isInstanceOf(IllegalArgumentException.class);
verifyNoInteractions(authenticationEvent);
}
@Test
public void fail_to_authenticate_unknown_user_after_forcing_hash() {
assertThatThrownBy(() -> executeAuthenticate(BASIC))
.hasMessage("No active user for login")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.local(BASIC))
.hasFieldOrPropertyWithValue("login", LOGIN);
verify(localAuthentication).generateHashToAvoidEnumerationAttack();
verifyNoInteractions(authenticationEvent);
}
private UserDto executeAuthenticate(AuthenticationEvent.Method method) {
return underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, method);
}
private UserDto insertUser(UserDto userDto) {
dbClient.userDao().insert(dbSession, userDto);
dbSession.commit();
return userDto;
}
}
| 10,628 | 41.516 | 188 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/CredentialsLocalAuthenticationIT.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.security.SecureRandom;
import java.util.Base64;
import java.util.Optional;
import java.util.Random;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mindrot.jbcrypt.BCrypt;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import static java.lang.String.format;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.authentication.CredentialsLocalAuthentication.HashMethod.BCRYPT;
import static org.sonar.server.authentication.CredentialsLocalAuthentication.HashMethod.PBKDF2;
public class CredentialsLocalAuthenticationIT {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final String PBKDF2_SALT = generatePBKDF2Salt();
@Rule
public DbTester db = DbTester.create();
private static final Random RANDOM = new Random();
private static final MapSettings settings = new MapSettings();
private CredentialsLocalAuthentication underTest = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
@Before
public void setup() {
settings.setProperty("sonar.internal.pbkdf2.iterations", 1);
}
@Test
public void incorrect_hash_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
UserDto user = newUserDto()
.setHashMethod("ALGON2");
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, "whatever", AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(format(CredentialsLocalAuthentication.ERROR_UNKNOWN_HASH_METHOD, "ALGON2"));
}
@Test
public void null_hash_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
UserDto user = newUserDto();
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, "whatever", AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(CredentialsLocalAuthentication.ERROR_NULL_HASH_METHOD);
}
@Test
public void authentication_with_bcrypt_with_correct_password_should_work() {
String password = randomAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(BCRYPT.name())
.setCryptedPassword(BCrypt.hashpw(password, BCrypt.gensalt(12)));
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
}
@Test
public void authentication_with_sha1_should_throw_AuthenticationException() {
String password = randomAlphanumeric(60);
byte[] saltRandom = new byte[20];
RANDOM.nextBytes(saltRandom);
String salt = DigestUtils.sha1Hex(saltRandom);
UserDto user = newUserDto()
.setHashMethod("SHA1")
.setCryptedPassword(DigestUtils.sha1Hex("--" + salt + "--" + password + "--"))
.setSalt(salt);
DbSession session = db.getSession();
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> underTest.authenticate(session, user, password, AuthenticationEvent.Method.BASIC))
.withMessage("Unknown hash method [SHA1]");
}
@Test
public void authentication_with_bcrypt_with_incorrect_password_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
String password = randomAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(BCRYPT.name())
.setCryptedPassword(BCrypt.hashpw(password, BCrypt.gensalt(12)));
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, "WHATEVER", AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(CredentialsLocalAuthentication.ERROR_WRONG_PASSWORD);
}
@Test
public void authentication_with_bcrypt_with_empty_password_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
UserDto user = newUserDto()
.setCryptedPassword(null)
.setHashMethod(BCRYPT.name());
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, "WHATEVER", AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(CredentialsLocalAuthentication.ERROR_NULL_PASSWORD_IN_DB);
}
@Test
public void authentication_upgrade_hash_function_when_BCRYPT_was_used() {
String password = randomAlphanumeric(60);
UserDto user = newUserDto()
.setLogin("myself")
.setHashMethod(BCRYPT.name())
.setCryptedPassword(BCrypt.hashpw(password, BCrypt.gensalt(12)))
.setSalt(null);
db.users().insertUser(user);
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
Optional<UserDto> myself = db.users().selectUserByLogin("myself");
assertThat(myself).isPresent();
assertThat(myself.get().getHashMethod()).isEqualTo(PBKDF2.name());
assertThat(myself.get().getSalt()).isNotNull();
// authentication must work with upgraded hash method
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
}
@Test
public void authentication_updates_db_if_PBKDF2_iterations_changes() {
String password = randomAlphanumeric(60);
UserDto user = newUserDto().setLogin("myself");
db.users().insertUser(user);
underTest.storeHashPassword(user, password);
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
assertThat(user.getCryptedPassword()).startsWith("1$");
settings.setProperty("sonar.internal.pbkdf2.iterations", 3);
CredentialsLocalAuthentication underTest = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
assertThat(user.getCryptedPassword()).startsWith("3$");
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
}
@Test
public void authentication_with_pbkdf2_with_correct_password_should_work() {
String password = randomAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(PBKDF2.name());
underTest.storeHashPassword(user, password);
assertThat(user.getCryptedPassword()).hasSize(88 + 2);
assertThat(user.getCryptedPassword()).startsWith("1$");
assertThat(user.getSalt()).hasSize(28);
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
}
@Test
public void authentication_with_pbkdf2_with_default_number_of_iterations() {
settings.clear();
CredentialsLocalAuthentication underTest = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
String password = randomAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(PBKDF2.name());
underTest.storeHashPassword(user, password);
assertThat(user.getCryptedPassword()).hasSize(88 + 7);
assertThat(user.getCryptedPassword()).startsWith("100000$");
assertThat(user.getSalt()).hasSize(28);
underTest.authenticate(db.getSession(), user, password, AuthenticationEvent.Method.BASIC);
}
@Test
public void authentication_with_pbkdf2_with_incorrect_password_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
UserDto user = newUserDto()
.setHashMethod(PBKDF2.name())
.setCryptedPassword("1$hash")
.setSalt("salt");
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, "WHATEVER", AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(CredentialsLocalAuthentication.ERROR_WRONG_PASSWORD);
}
@Test
public void authentication_with_pbkdf2_with_invalid_hash_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
String password = randomAlphanumeric(60);
UserDto userInvalidHash = newUserDto()
.setHashMethod(PBKDF2.name())
.setCryptedPassword(password)
.setSalt(PBKDF2_SALT);
assertThatThrownBy(() -> underTest.authenticate(dbSession, userInvalidHash, password, AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage("invalid hash stored");
UserDto userInvalidIterations = newUserDto()
.setHashMethod(PBKDF2.name())
.setCryptedPassword("a$" + password)
.setSalt(PBKDF2_SALT);
assertThatThrownBy(() -> underTest.authenticate(dbSession, userInvalidIterations, password, AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage("invalid hash stored");
}
@Test
public void authentication_with_pbkdf2_with_empty_password_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
UserDto user = newUserDto()
.setCryptedPassword(null)
.setHashMethod(PBKDF2.name())
.setSalt(PBKDF2_SALT);
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, "WHATEVER", AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(CredentialsLocalAuthentication.ERROR_NULL_PASSWORD_IN_DB);
}
@Test
public void authentication_with_pbkdf2_with_empty_salt_should_throw_AuthenticationException() {
String password = randomAlphanumeric(60);
DbSession dbSession = db.getSession();
UserDto user = newUserDto()
.setHashMethod(PBKDF2.name())
.setCryptedPassword("1$" + password)
.setSalt(null);
assertThatThrownBy(() -> underTest.authenticate(dbSession, user, password, AuthenticationEvent.Method.BASIC))
.isInstanceOf(AuthenticationException.class)
.hasMessage(CredentialsLocalAuthentication.ERROR_NULL_SALT);
}
private static String generatePBKDF2Salt() {
byte[] salt = new byte[20];
SECURE_RANDOM.nextBytes(salt);
String saltStr = Base64.getEncoder().encodeToString(salt);
return saltStr;
}
}
| 11,261 | 38.240418 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierImplIT.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.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.notification.NotificationManager;
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.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.sonar.server.property.InternalProperties.DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL;
public class DefaultAdminCredentialsVerifierImplIT {
private static final String ADMIN_LOGIN = "admin";
@Rule
public DbTester db = DbTester.create();
@Rule
public LogTester logTester = new LogTester();
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final NotificationManager notificationManager = mock(NotificationManager.class);
private final DefaultAdminCredentialsVerifierImpl underTest = new DefaultAdminCredentialsVerifierImpl(db.getDbClient(), localAuthentication, notificationManager);
@Test
public void correctly_detect_if_admin_account_is_used_with_default_credential() {
UserDto admin = db.users().insertUser(u -> u.setLogin(ADMIN_LOGIN));
changePassword(admin, "admin");
assertThat(underTest.hasDefaultCredentialUser()).isTrue();
changePassword(admin, "1234");
assertThat(underTest.hasDefaultCredentialUser()).isFalse();
}
@Test
public void does_not_break_if_admin_account_does_not_exist() {
assertThat(underTest.hasDefaultCredentialUser()).isFalse();
}
@Test
public void set_reset_flag_to_true_and_add_log_when_admin_account_with_default_credential_is_detected() {
UserDto admin = db.users().insertUser(u -> u.setLogin(ADMIN_LOGIN));
changePassword(admin, "admin");
underTest.runAtStart();
assertThat(db.users().selectUserByLogin(admin.getLogin()).get().isResetPassword()).isTrue();
assertThat(logTester.logs(Level.WARN)).contains("Default Administrator credentials are still being used. Make sure to change the password or deactivate the account.");
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL)).contains("true");
verify(notificationManager).scheduleForSending(any(Notification.class));
}
@Test
public void do_not_send_email_to_admins_when_already_sent() {
UserDto admin = db.users().insertUser(u -> u.setLogin(ADMIN_LOGIN));
changePassword(admin, "admin");
db.getDbClient().internalPropertiesDao().save(db.getSession(), DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL, "true");
db.commit();
underTest.runAtStart();
verifyNoMoreInteractions(notificationManager);
}
@Test
public void do_nothing_when_admin_is_not_using_default_credential() {
UserDto admin = db.users().insertUser(u -> u.setLogin(ADMIN_LOGIN));
changePassword(admin, "something_else");
underTest.runAtStart();
assertThat(db.users().selectUserByLogin(admin.getLogin()).get().isResetPassword()).isFalse();
assertThat(logTester.logs()).isEmpty();
verifyNoMoreInteractions(notificationManager);
}
@Test
public void do_nothing_when_no_admin_account_with_default_credential_detected() {
UserDto otherUser = db.users().insertUser();
changePassword(otherUser, "admin");
underTest.runAtStart();
assertThat(db.users().selectUserByLogin(otherUser.getLogin()).get().isResetPassword()).isFalse();
assertThat(logTester.logs()).isEmpty();
verifyNoMoreInteractions(notificationManager);
}
@Test
public void do_nothing_when_admin_account_with_default_credential_is_disabled() {
UserDto admin = db.users().insertUser(u -> u.setLogin(ADMIN_LOGIN).setActive(false));
changePassword(admin, "admin");
underTest.runAtStart();
assertThat(db.users().selectUserByLogin(admin.getLogin()).get().isResetPassword()).isFalse();
assertThat(logTester.logs()).isEmpty();
verifyNoMoreInteractions(notificationManager);
}
private void changePassword(UserDto user, String password) {
localAuthentication.storeHashPassword(user, password);
db.getDbClient().userDao().update(db.getSession(), user);
db.commit();
}
}
| 5,455 | 39.117647 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierNotificationHandlerIT.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.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.stubbing.Answer;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.notification.email.EmailNotificationChannel;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
public class DefaultAdminCredentialsVerifierNotificationHandlerIT {
@Rule
public DbTester db = DbTester.create();
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private DefaultAdminCredentialsVerifierNotificationHandler underTest = new DefaultAdminCredentialsVerifierNotificationHandler(db.getDbClient(),
emailNotificationChannel);
@Before
public void setUp() {
when(emailNotificationChannel.deliverAll(anySet()))
.then((Answer<Integer>) invocationOnMock -> ((Set<EmailNotificationChannel.EmailDeliveryRequest>) invocationOnMock.getArguments()[0]).size());
}
@Test
public void deliver_to_all_admins_having_emails() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
DefaultAdminCredentialsVerifierNotification detectActiveAdminAccountWithDefaultCredentialNotification = mock(DefaultAdminCredentialsVerifierNotification.class);
// Users granted admin permission directly
UserDto admin1 = db.users().insertUser(u -> u.setEmail("admin1"));
UserDto adminWithNoEmail = db.users().insertUser(u -> u.setEmail(null));
db.users().insertGlobalPermissionOnUser(admin1, ADMINISTER);
db.users().insertGlobalPermissionOnUser(adminWithNoEmail, ADMINISTER);
// User granted admin permission by group membership
UserDto admin2 = db.users().insertUser(u -> u.setEmail("admin2"));
GroupDto adminGroup = db.users().insertGroup();
db.users().insertPermissionOnGroup(adminGroup, ADMINISTER);
db.users().insertMember(adminGroup, admin2);
db.users().insertUser(u -> u.setEmail("otherUser"));
int deliver = underTest.deliver(singletonList(detectActiveAdminAccountWithDefaultCredentialNotification));
// Only 2 admins have there email defined
assertThat(deliver).isEqualTo(2);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(anySet());
verifyNoMoreInteractions(detectActiveAdminAccountWithDefaultCredentialNotification);
}
@Test
public void deliver_to_no_one_when_no_admins() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
DefaultAdminCredentialsVerifierNotification detectActiveAdminAccountWithDefaultCredentialNotification = mock(DefaultAdminCredentialsVerifierNotification.class);
db.users().insertUser(u -> u.setEmail("otherUser"));
int deliver = underTest.deliver(singletonList(detectActiveAdminAccountWithDefaultCredentialNotification));
assertThat(deliver).isZero();
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
verifyNoMoreInteractions(detectActiveAdminAccountWithDefaultCredentialNotification);
}
@Test
public void do_nothing_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
DefaultAdminCredentialsVerifierNotification detectActiveAdminAccountWithDefaultCredentialNotification = mock(
DefaultAdminCredentialsVerifierNotification.class);
int deliver = underTest.deliver(singletonList(detectActiveAdminAccountWithDefaultCredentialNotification));
assertThat(deliver).isZero();
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
verifyNoMoreInteractions(detectActiveAdminAccountWithDefaultCredentialNotification);
}
@Test
public void getMetadata_returns_empty() {
assertThat(underTest.getMetadata()).isEmpty();
}
@Test
public void getNotificationClass() {
assertThat(underTest.getNotificationClass()).isEqualTo(DefaultAdminCredentialsVerifierNotification.class);
}
}
| 5,253 | 42.421488 | 164 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/GithubWebhookAuthenticationIT.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.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.testfixtures.log.LogAndArguments;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import org.springframework.lang.Nullable;
import static java.lang.String.format;
import static java.util.Objects.requireNonNullElse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.server.authentication.GithubWebhookAuthentication.GITHUB_APP_ID_HEADER;
import static org.sonar.server.authentication.GithubWebhookAuthentication.GITHUB_SIGNATURE_HEADER;
import static org.sonar.server.authentication.GithubWebhookAuthentication.MSG_AUTHENTICATION_FAILED;
import static org.sonar.server.authentication.GithubWebhookAuthentication.MSG_NO_BODY_FOUND;
import static org.sonar.server.authentication.GithubWebhookAuthentication.MSG_NO_WEBHOOK_SECRET_FOUND;
import static org.sonar.server.authentication.GithubWebhookAuthentication.MSG_UNAUTHENTICATED_GITHUB_CALLS_DENIED;
public class GithubWebhookAuthenticationIT {
private static final String GITHUB_SIGNATURE = "sha256=1cd2d35d7bb5fc5738672bcdc959c4bc94ba308eb7008938a2f22b5713571925";
private static final String GITHUB_PAYLOAD = "{\"action\":\"closed_by_user\",\"alert\":{\"number\":2,\"created_at\":\"2022-08-16T13:02:17Z\",\"updated_at\":\"2022-09-05T08:35:05Z\",\"url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/code-scanning/alerts/2\",\"html_url\":\"https://github.com/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/security/code-scanning/2\",\"state\":\"dismissed\",\"fixed_at\":null,\"dismissed_by\":{\"login\":\"aurelien-poscia-sonarsource\",\"id\":100427063,\"node_id\":\"U_kgDOBfxlNw\",\"avatar_url\":\"https://avatars.githubusercontent.com/u/100427063?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/aurelien-poscia-sonarsource\",\"html_url\":\"https://github.com/aurelien-poscia-sonarsource\",\"followers_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/followers\",\"following_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/subscriptions\",\"organizations_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/orgs\",\"repos_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/repos\",\"events_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/received_events\",\"type\":\"User\",\"site_admin\":false},\"dismissed_at\":\"2022-09-05T08:35:05Z\",\"dismissed_reason\":\"false positive\",\"dismissed_comment\":\"c'est pas un buuuuug\",\"rule\":{\"id\":\"js/inconsistent-use-of-new\",\"severity\":\"warning\",\"description\":\"Inconsistent use of 'new'\",\"name\":\"js/inconsistent-use-of-new\",\"tags\":[\"correctness\",\"language-features\",\"reliability\"],\"full_description\":\"If a function is intended to be a constructor, it should always be invoked with 'new'. Otherwise, it should always be invoked as a normal function, that is, without 'new'.\",\"help\":\"\",\"help_uri\":\"\"},\"tool\":{\"name\":\"CodeQL\",\"guid\":null,\"version\":\"2.0.0\"},\"most_recent_instance\":{\"ref\":\"refs/heads/main\",\"analysis_key\":\"(default)\",\"environment\":\"{}\",\"category\":\"\",\"state\":\"dismissed\",\"commit_sha\":\"b4f17b0f7612575b70e9708e0aeda7e8067e8404\",\"message\":{\"text\":\"Function resolvingPromise is sometimes invoked as a constructor (for example here), and sometimes as a normal function (for example here).\"},\"location\":{\"path\":\"src/promiseUtils.js\",\"start_line\":2,\"end_line\":2,\"start_column\":8,\"end_column\":37},\"classifications\":[]},\"instances_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/code-scanning/alerts/2/instances\"},\"ref\":\"\",\"commit_oid\":\"\",\"repository\":{\"id\":525365935,\"node_id\":\"R_kgDOH1Byrw\",\"name\":\"mmf-2821-github-scanning-alerts\",\"full_name\":\"aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts\",\"private\":false,\"owner\":{\"login\":\"aurelien-poscia-sonarsource\",\"id\":100427063,\"node_id\":\"U_kgDOBfxlNw\",\"avatar_url\":\"https://avatars.githubusercontent.com/u/100427063?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/aurelien-poscia-sonarsource\",\"html_url\":\"https://github.com/aurelien-poscia-sonarsource\",\"followers_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/followers\",\"following_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/subscriptions\",\"organizations_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/orgs\",\"repos_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/repos\",\"events_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/received_events\",\"type\":\"User\",\"site_admin\":false},\"html_url\":\"https://github.com/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts\",\"description\":null,\"fork\":false,\"url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts\",\"forks_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/forks\",\"keys_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/keys{/key_id}\",\"collaborators_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/collaborators{/collaborator}\",\"teams_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/teams\",\"hooks_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/hooks\",\"issue_events_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/issues/events{/number}\",\"events_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/events\",\"assignees_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/assignees{/user}\",\"branches_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/branches{/branch}\",\"tags_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/tags\",\"blobs_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/git/blobs{/sha}\",\"git_tags_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/git/tags{/sha}\",\"git_refs_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/git/refs{/sha}\",\"trees_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/git/trees{/sha}\",\"statuses_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/statuses/{sha}\",\"languages_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/languages\",\"stargazers_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/stargazers\",\"contributors_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/contributors\",\"subscribers_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/subscribers\",\"subscription_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/subscription\",\"commits_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/commits{/sha}\",\"git_commits_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/git/commits{/sha}\",\"comments_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/comments{/number}\",\"issue_comment_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/issues/comments{/number}\",\"contents_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/contents/{+path}\",\"compare_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/compare/{base}...{head}\",\"merges_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/merges\",\"archive_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/{archive_format}{/ref}\",\"downloads_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/downloads\",\"issues_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/issues{/number}\",\"pulls_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/pulls{/number}\",\"milestones_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/milestones{/number}\",\"notifications_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/notifications{?since,all,participating}\",\"labels_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/labels{/name}\",\"releases_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/releases{/id}\",\"deployments_url\":\"https://api.github.com/repos/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts/deployments\",\"created_at\":\"2022-08-16T12:16:56Z\",\"updated_at\":\"2022-08-16T12:16:56Z\",\"pushed_at\":\"2022-08-18T10:08:48Z\",\"git_url\":\"git://github.com/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts.git\",\"ssh_url\":\"git@github.com:aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts.git\",\"clone_url\":\"https://github.com/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts.git\",\"svn_url\":\"https://github.com/aurelien-poscia-sonarsource/mmf-2821-github-scanning-alerts\",\"homepage\":null,\"size\":2,\"stargazers_count\":0,\"watchers_count\":0,\"language\":null,\"has_issues\":true,\"has_projects\":true,\"has_downloads\":true,\"has_wiki\":true,\"has_pages\":false,\"forks_count\":0,\"mirror_url\":null,\"archived\":false,\"disabled\":false,\"open_issues_count\":0,\"license\":null,\"allow_forking\":true,\"is_template\":false,\"web_commit_signoff_required\":false,\"topics\":[],\"visibility\":\"public\",\"forks\":0,\"open_issues\":0,\"watchers\":0,\"default_branch\":\"main\"},\"sender\":{\"login\":\"aurelien-poscia-sonarsource\",\"id\":100427063,\"node_id\":\"U_kgDOBfxlNw\",\"avatar_url\":\"https://avatars.githubusercontent.com/u/100427063?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/aurelien-poscia-sonarsource\",\"html_url\":\"https://github.com/aurelien-poscia-sonarsource\",\"followers_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/followers\",\"following_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/subscriptions\",\"organizations_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/orgs\",\"repos_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/repos\",\"events_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/aurelien-poscia-sonarsource/received_events\",\"type\":\"User\",\"site_admin\":false},\"installation\":{\"id\":28299870,\"node_id\":\"MDIzOkludGVncmF0aW9uSW5zdGFsbGF0aW9uMjgyOTk4NzA=\"}}";
private static final String APP_ID = "APP_ID";
private static final String WEBHOOK_SECRET = "toto_secret";
@Rule
public LogTester logTester = new LogTester();
@Rule
public final DbTester db = DbTester.create();
private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private final Settings settings = mock(Settings.class);
private final Encryption encryption = mock(Encryption.class);
private GithubWebhookAuthentication githubWebhookAuthentication;
private AlmSettingDto almSettingDto;
@Before
public void setUp() {
when(settings.getEncryption()).thenReturn(encryption);
githubWebhookAuthentication = new GithubWebhookAuthentication(authenticationEvent, db.getDbClient(), settings);
almSettingDto = db.almSettings().insertGitHubAlmSetting(
setting -> setting.setAppId(APP_ID),
setting -> setting.setWebhookSecret(WEBHOOK_SECRET));
}
@Test
public void authenticate_withComputedSignatureMatchingGithubSignature_returnsAuthentication() {
HttpRequest request = mockRequest(GITHUB_PAYLOAD, GITHUB_SIGNATURE);
Optional<UserAuthResult> authentication = githubWebhookAuthentication.authenticate(request);
assertThat(authentication).isPresent();
UserAuthResult userAuthResult = authentication.get();
assertThat(userAuthResult.getUserDto()).isNull();
assertThat(userAuthResult.getAuthType()).isEqualTo(UserAuthResult.AuthType.GITHUB_WEBHOOK);
assertThat(userAuthResult.getTokenDto()).isNull();
verify(authenticationEvent).loginSuccess(request, "github-webhook", AuthenticationEvent.Source.githubWebhook());
assertThat(logTester.getLogs()).isEmpty();
}
@Test
public void authenticate_withoutGithubSignatureHeader_throws() {
HttpRequest request = mockRequest(GITHUB_PAYLOAD, null);
String expectedMessage = format(MSG_UNAUTHENTICATED_GITHUB_CALLS_DENIED, APP_ID);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> githubWebhookAuthentication.authenticate(request))
.withMessage(expectedMessage);
assertThat(logTester.getLogs(LoggerLevel.WARN)).extracting(LogAndArguments::getFormattedMsg).contains(expectedMessage);
}
@Test
public void authenticate_withoutBody_throws() {
HttpRequest request = mockRequest(null, GITHUB_SIGNATURE);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> githubWebhookAuthentication.authenticate(request))
.withMessage(MSG_AUTHENTICATION_FAILED);
assertThat(logTester.getLogs(LoggerLevel.WARN)).extracting(LogAndArguments::getFormattedMsg).contains(MSG_AUTHENTICATION_FAILED);
}
@Test
public void authenticate_withExceptionWhileReadingBody_throws() throws IOException {
HttpRequest request = mockRequest(GITHUB_PAYLOAD, GITHUB_SIGNATURE);
when(request.getReader()).thenThrow(new IOException());
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> githubWebhookAuthentication.authenticate(request))
.withMessage(MSG_NO_BODY_FOUND);
assertThat(logTester.getLogs(LoggerLevel.WARN)).extracting(LogAndArguments::getFormattedMsg).contains(MSG_NO_BODY_FOUND);
}
@Test
public void authenticate_withoutAppId_returnsEmpty() {
HttpRequest request = mockRequest(null, GITHUB_SIGNATURE);
when(request.getHeader(GITHUB_APP_ID_HEADER)).thenReturn(null);
assertThat(githubWebhookAuthentication.authenticate(request)).isEmpty();
assertThat(logTester.getLogs()).isEmpty();
}
@Test
public void authenticate_withWrongPayload_throws() {
HttpRequest request = mockRequest(GITHUB_PAYLOAD + "_", GITHUB_SIGNATURE);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> githubWebhookAuthentication.authenticate(request))
.withMessage(MSG_AUTHENTICATION_FAILED);
assertThat(logTester.getLogs(LoggerLevel.WARN)).extracting(LogAndArguments::getFormattedMsg).contains(MSG_AUTHENTICATION_FAILED);
}
@Test
public void authenticate_withWrongSignature_throws() {
HttpRequest request = mockRequest(GITHUB_PAYLOAD, GITHUB_SIGNATURE + "_");
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> githubWebhookAuthentication.authenticate(request))
.withMessage(MSG_AUTHENTICATION_FAILED);
assertThat(logTester.getLogs(LoggerLevel.WARN)).extracting(LogAndArguments::getFormattedMsg).contains(MSG_AUTHENTICATION_FAILED);
}
@Test
public void authenticate_whenNoWebhookSecret_throws() {
HttpRequest request = mockRequest(GITHUB_PAYLOAD, GITHUB_SIGNATURE);
db.getDbClient().almSettingDao().update(db.getSession(), almSettingDto.setWebhookSecret(null), true);
db.commit();
String expectedMessage = format(MSG_NO_WEBHOOK_SECRET_FOUND, APP_ID);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> githubWebhookAuthentication.authenticate(request))
.withMessage(expectedMessage);
assertThat(logTester.getLogs(LoggerLevel.WARN)).extracting(LogAndArguments::getFormattedMsg).contains(expectedMessage);
}
private static HttpRequest mockRequest(@Nullable String payload, @Nullable String gitHubSignature) {
HttpRequest request = mock(HttpRequest.class, Mockito.RETURNS_DEEP_STUBS);
try {
StringReader stringReader = new StringReader(requireNonNullElse(payload, ""));
BufferedReader bufferedReader = new BufferedReader(stringReader);
when(request.getReader()).thenReturn(bufferedReader);
when(request.getHeader(GITHUB_SIGNATURE_HEADER)).thenReturn(gitHubSignature);
when(request.getHeader(GITHUB_APP_ID_HEADER)).thenReturn(APP_ID);
} catch (IOException e) {
fail("mockRequest threw an exception: " + e.getMessage());
}
return request;
}
}
| 20,117 | 102.701031 | 11,520 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/HttpHeadersAuthenticationIT.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 java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
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.es.EsTester;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static java.util.Arrays.stream;
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.anyMap;
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;
import static org.sonar.db.user.UserTesting.newUserDto;
public class HttpHeadersAuthenticationIT {
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
@Rule
public DbTester db = DbTester.create(new AlwaysIncreasingSystem2());
@Rule
public EsTester es = EsTester.create();
private static final String DEFAULT_LOGIN = "john";
private static final String DEFAULT_NAME = "John";
private static final String DEFAULT_EMAIL = "john@doo.com";
private static final String GROUP1 = "dev";
private static final String GROUP2 = "admin";
private static final String GROUPS = GROUP1 + "," + GROUP2;
private static final Long NOW = 1_000_000L;
private static final Long CLOSE_REFRESH_TIME = NOW - 1_000L;
private static final UserDto DEFAULT_USER = newUserDto()
.setLogin(DEFAULT_LOGIN)
.setName(DEFAULT_NAME)
.setEmail(DEFAULT_EMAIL)
.setExternalLogin(DEFAULT_LOGIN)
.setExternalIdentityProvider("sonarqube");
private GroupDto group1;
private GroupDto group2;
private GroupDto sonarUsers;
private final System2 system2 = mock(System2.class);
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final DefaultGroupFinder defaultGroupFinder = new DefaultGroupFinder(db.getDbClient());
private final UserRegistrarImpl userIdentityAuthenticator = new UserRegistrarImpl(db.getDbClient(),
new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), defaultGroupFinder, settings.asConfig(), mock(AuditPersister.class), localAuthentication),
defaultGroupFinder, mock(ManagedInstanceService.class));
private final HttpResponse response = mock(HttpResponse.class);
private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class);
private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private final HttpHeadersAuthentication underTest = new HttpHeadersAuthentication(system2, settings.asConfig(), userIdentityAuthenticator, jwtHttpHandler,
authenticationEvent);
@Before
public void setUp() {
when(system2.now()).thenReturn(NOW);
group1 = db.users().insertGroup(GROUP1);
group2 = db.users().insertGroup(GROUP2);
sonarUsers = db.users().insertDefaultGroup();
}
@Test
public void create_user_when_authenticating_new_user() {
startWithSso();
setNotUserInToken();
HttpRequest request = createRequest(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, GROUPS);
underTest.authenticate(request, response);
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, group1, group2, sonarUsers);
verifyTokenIsUpdated(NOW);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void use_login_when_name_is_not_provided() {
startWithSso();
setNotUserInToken();
HttpRequest request = createRequest(DEFAULT_LOGIN, null, null, null);
underTest.authenticate(request, response);
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_LOGIN, null, sonarUsers);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void update_user_when_authenticating_exiting_user() {
startWithSso();
setNotUserInToken();
insertUser(newUserDto().setLogin(DEFAULT_LOGIN).setExternalLogin(DEFAULT_LOGIN).setExternalIdentityProvider("sonarqube").setName("old name").setEmail(DEFAULT_USER.getEmail()), group1);
// Name, email and groups are different
HttpRequest request = createRequest(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, GROUP2);
underTest.authenticate(request, response);
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, group2);
verifyTokenIsUpdated(NOW);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void remove_groups_when_group_headers_is_empty() {
startWithSso();
setNotUserInToken();
insertUser(DEFAULT_USER, group1);
HttpRequest request = createRequest(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, "");
underTest.authenticate(request, response);
verityUserHasNoGroup(DEFAULT_LOGIN);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void remove_groups_when_group_headers_is_null() {
startWithSso();
setNotUserInToken();
insertUser(DEFAULT_USER, group1);
Map<String, String> headerValuesByName = new HashMap<>();
headerValuesByName.put("X-Forwarded-Login", DEFAULT_LOGIN);
headerValuesByName.put("X-Forwarded-Email", DEFAULT_USER.getEmail());
headerValuesByName.put("X-Forwarded-Groups", null);
HttpRequest request = createRequest(headerValuesByName);
underTest.authenticate(request, response);
verityUserHasNoGroup(DEFAULT_LOGIN);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void does_not_update_groups_when_no_group_headers() {
startWithSso();
setNotUserInToken();
insertUser(DEFAULT_USER, group1, sonarUsers);
HttpRequest request = createRequest(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, null);
underTest.authenticate(request, response);
verityUserGroups(DEFAULT_LOGIN, group1, sonarUsers);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void does_not_update_user_when_user_is_in_token_and_refresh_time_is_close() {
startWithSso();
UserDto user = insertUser(DEFAULT_USER, group1);
setUserInToken(user, CLOSE_REFRESH_TIME);
HttpRequest request = createRequest(DEFAULT_LOGIN, "new name", "new email", GROUP2);
underTest.authenticate(request, response);
// User is not updated
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, group1);
verifyTokenIsNotUpdated();
verifyNoInteractions(authenticationEvent);
}
@Test
public void update_user_when_user_in_token_but_refresh_time_is_old() {
startWithSso();
UserDto user = insertUser(DEFAULT_USER, group1);
// Refresh time was updated 6 minutes ago => more than 5 minutes
setUserInToken(user, NOW - 6 * 60 * 1000L);
HttpRequest request = createRequest(DEFAULT_LOGIN, "new name", DEFAULT_USER.getEmail(), GROUP2);
underTest.authenticate(request, response);
// User is updated
verifyUserInDb(DEFAULT_LOGIN, "new name", DEFAULT_USER.getEmail(), group2);
verifyTokenIsUpdated(NOW);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void update_user_when_user_in_token_but_no_refresh_time() {
startWithSso();
UserDto user = insertUser(DEFAULT_USER, group1);
setUserInToken(user, null);
HttpRequest request = createRequest(DEFAULT_LOGIN, "new name", DEFAULT_USER.getEmail(), GROUP2);
underTest.authenticate(request, response);
// User is updated
verifyUserInDb(DEFAULT_LOGIN, "new name", DEFAULT_USER.getEmail(), group2);
verifyTokenIsUpdated(NOW);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void use_refresh_time_from_settings() {
settings.setProperty("sonar.web.sso.refreshIntervalInMinutes", "10");
startWithSso();
UserDto user = insertUser(DEFAULT_USER, group1);
// Refresh time was updated 6 minutes ago => less than 10 minutes ago so not updated
setUserInToken(user, NOW - 6 * 60 * 1000L);
HttpRequest request = createRequest(DEFAULT_LOGIN, "new name", "new email", GROUP2);
underTest.authenticate(request, response);
// User is not updated
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, group1);
verifyTokenIsNotUpdated();
verifyNoInteractions(authenticationEvent);
}
@Test
public void update_user_when_login_from_token_is_different_than_login_from_request() {
startWithSso();
insertUser(DEFAULT_USER, group1);
setUserInToken(DEFAULT_USER, CLOSE_REFRESH_TIME);
HttpRequest request = createRequest("AnotherLogin", "Another name", "Another email", GROUP2);
underTest.authenticate(request, response);
verifyUserInDb("AnotherLogin", "Another name", "Another email", group2, sonarUsers);
verifyTokenIsUpdated(NOW);
verify(authenticationEvent).loginSuccess(request, "AnotherLogin", Source.sso());
}
@Test
public void use_headers_from_settings() {
settings.setProperty("sonar.web.sso.loginHeader", "head-login");
settings.setProperty("sonar.web.sso.nameHeader", "head-name");
settings.setProperty("sonar.web.sso.emailHeader", "head-email");
settings.setProperty("sonar.web.sso.groupsHeader", "head-groups");
startWithSso();
setNotUserInToken();
HttpRequest request = createRequest(ImmutableMap.of("head-login", DEFAULT_LOGIN, "head-name", DEFAULT_NAME, "head-email", DEFAULT_EMAIL, "head-groups", GROUPS));
underTest.authenticate(request, response);
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, group1, group2, sonarUsers);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void detect_group_header_even_with_wrong_case() {
settings.setProperty("sonar.web.sso.loginHeader", "login");
settings.setProperty("sonar.web.sso.nameHeader", "name");
settings.setProperty("sonar.web.sso.emailHeader", "email");
settings.setProperty("sonar.web.sso.groupsHeader", "Groups");
startWithSso();
setNotUserInToken();
HttpRequest request = createRequest(ImmutableMap.of("login", DEFAULT_LOGIN, "name", DEFAULT_NAME, "email", DEFAULT_EMAIL, "groups", GROUPS));
underTest.authenticate(request, response);
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, group1, group2, sonarUsers);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void trim_groups() {
startWithSso();
setNotUserInToken();
HttpRequest request = createRequest(DEFAULT_LOGIN, null, null, " dev , admin ");
underTest.authenticate(request, response);
verifyUserInDb(DEFAULT_LOGIN, DEFAULT_LOGIN, null, group1, group2, sonarUsers);
verify(authenticationEvent).loginSuccess(request, DEFAULT_LOGIN, Source.sso());
}
@Test
public void does_not_authenticate_when_no_header() {
startWithSso();
setNotUserInToken();
underTest.authenticate(createRequest(Collections.emptyMap()), response);
verifyUserNotAuthenticated();
verifyTokenIsNotUpdated();
verifyNoInteractions(authenticationEvent);
}
@Test
public void does_not_authenticate_when_not_enabled() {
startWithoutSso();
underTest.authenticate(createRequest(DEFAULT_LOGIN, DEFAULT_NAME, DEFAULT_EMAIL, GROUPS), response);
verifyUserNotAuthenticated();
verifyNoInteractions(jwtHttpHandler, authenticationEvent);
}
@Test
public void throw_AuthenticationException_when_BadRequestException_is_generated() {
startWithSso();
setNotUserInToken();
assertThatThrownBy(() -> underTest.authenticate(createRequest("invalid login", DEFAULT_NAME, DEFAULT_EMAIL, GROUPS), response))
.hasMessage("Login should contain only letters, numbers, and .-_@")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", Source.sso());
verifyNoInteractions(authenticationEvent);
}
private void startWithSso() {
settings.setProperty("sonar.web.sso.enable", true);
underTest.start();
}
private void startWithoutSso() {
settings.setProperty("sonar.web.sso.enable", false);
underTest.start();
}
private void setUserInToken(UserDto user, @Nullable Long lastRefreshTime) {
when(jwtHttpHandler.getToken(any(HttpRequest.class), any(HttpResponse.class)))
.thenReturn(Optional.of(new JwtHttpHandler.Token(
user,
lastRefreshTime == null ? Collections.emptyMap() : ImmutableMap.of("ssoLastRefreshTime", lastRefreshTime))));
}
private void setNotUserInToken() {
when(jwtHttpHandler.getToken(any(HttpRequest.class), any(HttpResponse.class))).thenReturn(Optional.empty());
}
private UserDto insertUser(UserDto user, GroupDto... groups) {
db.users().insertUser(user);
stream(groups).forEach(group -> db.users().insertMember(group, user));
db.commit();
return user;
}
private static HttpRequest createRequest(Map<String, String> headerValuesByName) {
HttpRequest request = mock(HttpRequest.class);
setHeaders(request, headerValuesByName);
return request;
}
private static HttpRequest createRequest(String login, @Nullable String name, @Nullable String email, @Nullable String groups) {
Map<String, String> headerValuesByName = new HashMap<>();
headerValuesByName.put("X-Forwarded-Login", login);
if (name != null) {
headerValuesByName.put("X-Forwarded-Name", name);
}
if (email != null) {
headerValuesByName.put("X-Forwarded-Email", email);
}
if (groups != null) {
headerValuesByName.put("X-Forwarded-Groups", groups);
}
HttpRequest request = mock(HttpRequest.class);
setHeaders(request, headerValuesByName);
return request;
}
private static void setHeaders(HttpRequest request, Map<String, String> valuesByName) {
valuesByName.forEach((key, value) -> when(request.getHeader(key)).thenReturn(value));
when(request.getHeaderNames()).thenReturn(Collections.enumeration(valuesByName.keySet()));
}
private void verifyUserInDb(String expectedLogin, String expectedName, @Nullable String expectedEmail, GroupDto... expectedGroups) {
UserDto userDto = db.users().selectUserByLogin(expectedLogin).get();
assertThat(userDto.isActive()).isTrue();
assertThat(userDto.getName()).isEqualTo(expectedName);
assertThat(userDto.getEmail()).isEqualTo(expectedEmail);
assertThat(userDto.getExternalLogin()).isEqualTo(expectedLogin);
assertThat(userDto.getExternalIdentityProvider()).isEqualTo("sonarqube");
verityUserGroups(expectedLogin, expectedGroups);
}
private void verityUserGroups(String login, GroupDto... expectedGroups) {
UserDto userDto = db.users().selectUserByLogin(login).get();
if (expectedGroups.length == 0) {
assertThat(db.users().selectGroupUuidsOfUser(userDto)).isEmpty();
} else {
assertThat(db.users().selectGroupUuidsOfUser(userDto)).containsOnly(stream(expectedGroups).map(GroupDto::getUuid).toArray(String[]::new));
}
}
private void verityUserHasNoGroup(String login) {
verityUserGroups(login);
}
private void verifyUserNotAuthenticated() {
assertThat(db.countRowsOfTable(db.getSession(), "users")).isZero();
verifyTokenIsNotUpdated();
}
private void verifyTokenIsUpdated(long refreshTime) {
verify(jwtHttpHandler).generateToken(any(UserDto.class), eq(ImmutableMap.of("ssoLastRefreshTime", refreshTime)), any(HttpRequest.class), any(HttpResponse.class));
}
private void verifyTokenIsNotUpdated() {
verify(jwtHttpHandler, never()).generateToken(any(UserDto.class), anyMap(), any(HttpRequest.class), any(HttpResponse.class));
}
}
| 17,602 | 38.646396 | 188 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/JwtHttpHandlerIT.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 io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpSession;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.internal.MapSettings;
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.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.SessionTokenDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.http.JavaxHttpRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.authentication.Cookies.SET_COOKIE;
public class JwtHttpHandlerIT {
private static final String JWT_TOKEN = "TOKEN";
private static final String CSRF_STATE = "CSRF_STATE";
private static final long NOW = 10_000_000_000L;
private static final long FOUR_MINUTES_AGO = NOW - 4 * 60 * 1000L;
private static final long SIX_MINUTES_AGO = NOW - 6 * 60 * 1000L;
private static final long TEN_DAYS_AGO = NOW - 10 * 24 * 60 * 60 * 1000L;
private static final long IN_FIVE_MINUTES = NOW + 5 * 60 * 1000L;
@Rule
public DbTester db = DbTester.create();
private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
private ArgumentCaptor<JwtSerializer.JwtSession> jwtArgumentCaptor = ArgumentCaptor.forClass(JwtSerializer.JwtSession.class);
private HttpRequest request = mock(HttpRequest.class);
private HttpResponse response = mock(HttpResponse.class);
private HttpSession httpSession = mock(HttpSession.class);
private System2 system2 = spy(System2.INSTANCE);
private MapSettings settings = new MapSettings();
private JwtSerializer jwtSerializer = mock(JwtSerializer.class);
private JwtCsrfVerifier jwtCsrfVerifier = mock(JwtCsrfVerifier.class);
private JwtHttpHandler underTest = new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
@Before
public void setUp() {
when(system2.now()).thenReturn(NOW);
when(jwtSerializer.encode(any(JwtSerializer.JwtSession.class))).thenReturn(JWT_TOKEN);
when(jwtCsrfVerifier.generateState(eq(request), eq(response), anyInt())).thenReturn(CSRF_STATE);
}
@Test
public void create_token() {
UserDto user = db.users().insertUser();
underTest.generateToken(user, request, response);
verify(response).addHeader(SET_COOKIE, "JWT-SESSION=TOKEN; Path=/; SameSite=Lax; Max-Age=259200; HttpOnly");
verify(jwtSerializer).encode(jwtArgumentCaptor.capture());
verifyToken(jwtArgumentCaptor.getValue(), user, 3 * 24 * 60 * 60, NOW);
verifySessionTokenInDb(jwtArgumentCaptor.getValue());
}
@Test
public void generate_csrf_state_when_creating_token() {
UserDto user = db.users().insertUser();
underTest.generateToken(user, request, response);
verify(jwtCsrfVerifier).generateState(request, response, 3 * 24 * 60 * 60);
verify(jwtSerializer).encode(jwtArgumentCaptor.capture());
JwtSerializer.JwtSession token = jwtArgumentCaptor.getValue();
assertThat(token.getProperties()).containsEntry("xsrfToken", CSRF_STATE);
}
@Test
public void generate_token_is_using_session_timeout_from_settings() {
UserDto user = db.users().insertUser();
int sessionTimeoutInMinutes = 10;
settings.setProperty("sonar.web.sessionTimeoutInMinutes", sessionTimeoutInMinutes);
underTest = new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
underTest.generateToken(user, request, response);
verify(jwtSerializer).encode(jwtArgumentCaptor.capture());
verifyToken(jwtArgumentCaptor.getValue(), user, sessionTimeoutInMinutes * 60, NOW);
}
@Test
public void session_timeout_property_cannot_be_updated() {
UserDto user = db.users().insertUser();
int firstSessionTimeoutInMinutes = 10;
settings.setProperty("sonar.web.sessionTimeoutInMinutes", firstSessionTimeoutInMinutes);
underTest = new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
underTest.generateToken(user, request, response);
// The property is updated, but it won't be taking into account
settings.setProperty("sonar.web.sessionTimeoutInMinutes", 15);
underTest.generateToken(user, request, response);
verify(jwtSerializer, times(2)).encode(jwtArgumentCaptor.capture());
verifyToken(jwtArgumentCaptor.getAllValues().get(0), user, firstSessionTimeoutInMinutes * 60, NOW);
verifyToken(jwtArgumentCaptor.getAllValues().get(1), user, firstSessionTimeoutInMinutes * 60, NOW);
}
@Test
public void session_timeout_property_cannot_be_zero() {
settings.setProperty("sonar.web.sessionTimeoutInMinutes", 0);
assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 0 minutes");
}
@Test
public void session_timeout_property_cannot_be_negative() {
settings.setProperty("sonar.web.sessionTimeoutInMinutes", -10);
assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got -10 minutes");
}
@Test
public void session_timeout_property_cannot_be_set_to_five_minutes() {
settings.setProperty("sonar.web.sessionTimeoutInMinutes", 5);
assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 5 minutes");
}
@Test
public void session_timeout_property_cannot_be_greater_than_three_months() {
settings.setProperty("sonar.web.sessionTimeoutInMinutes", 4 * 30 * 24 * 60);
assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 172800 minutes");
}
@Test
public void validate_token() {
UserDto user = db.users().insertUser();
addJwtCookie();
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, NOW);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
assertThat(underTest.validateToken(request, response)).isPresent();
verify(jwtSerializer, never()).encode(any(JwtSerializer.JwtSession.class));
}
@Test
public void validate_token_refresh_session_when_refresh_time_is_reached() {
UserDto user = db.users().insertUser();
addJwtCookie();
// Token was created 10 days ago and refreshed 6 minutes ago
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, TEN_DAYS_AGO);
claims.put("lastRefreshTime", SIX_MINUTES_AGO);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
assertThat(underTest.validateToken(request, response)).isPresent();
verify(jwtSerializer).refresh(any(Claims.class), eq(NOW + 3 * 24 * 60 * 60 * 1000L));
assertThat(dbClient.sessionTokensDao().selectByUuid(dbSession, sessionToken.getUuid()).get().getExpirationDate())
.isNotEqualTo(IN_FIVE_MINUTES)
.isEqualTo(NOW + 3 * 24 * 60 * 60 * 1000L);
}
@Test
public void validate_token_does_not_refresh_session_when_refresh_time_is_not_reached() {
UserDto user = db.users().insertUser();
addJwtCookie();
// Token was created 10 days ago and refreshed 4 minutes ago
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, TEN_DAYS_AGO);
claims.put("lastRefreshTime", FOUR_MINUTES_AGO);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
assertThat(underTest.validateToken(request, response)).isPresent();
verify(jwtSerializer, never()).refresh(any(Claims.class), anyInt());
}
@Test
public void validate_token_does_not_refresh_session_when_disconnected_timeout_is_reached() {
UserDto user = db.users().insertUser();
addJwtCookie();
// Token was created 4 months ago, refreshed 4 minutes ago, and it expired in 5 minutes
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, NOW - (4L * 30 * 24 * 60 * 60 * 1000));
claims.put("lastRefreshTime", FOUR_MINUTES_AGO);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_does_not_refresh_session_when_user_is_disabled() {
addJwtCookie();
UserDto user = addUser(false);
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, NOW);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_does_not_refresh_session_when_token_is_no_more_valid() {
addJwtCookie();
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.empty());
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_does_nothing_when_no_jwt_cookie() {
underTest.validateToken(request, response);
verifyNoInteractions(httpSession, jwtSerializer);
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_does_nothing_when_empty_value_in_jwt_cookie() {
when(request.getCookies()).thenReturn(new Cookie[] {new JavaxHttpRequest.JavaxCookie(new javax.servlet.http.Cookie("JWT-SESSION", ""))});
underTest.validateToken(request, response);
verifyNoInteractions(httpSession, jwtSerializer);
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_verify_csrf_state() {
UserDto user = db.users().insertUser();
addJwtCookie();
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, NOW);
claims.put("xsrfToken", CSRF_STATE);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
underTest.validateToken(request, response);
verify(jwtCsrfVerifier).verifyState(request, CSRF_STATE, user.getUuid());
}
@Test
public void validate_token_does_nothing_when_no_session_token_in_db() {
UserDto user = db.users().insertUser();
addJwtCookie();
// No SessionToken in DB
Claims claims = createToken("ABCD", user.getUuid(), NOW, IN_FIVE_MINUTES);
claims.put("lastRefreshTime", SIX_MINUTES_AGO);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
underTest.validateToken(request, response);
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_does_nothing_when_expiration_date_from_session_token_is_expired() {
UserDto user = db.users().insertUser();
addJwtCookie();
// In SessionToken, the expiration date is expired...
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(FOUR_MINUTES_AGO));
// ...whereas in the cookie, the expiration date is not expired
Claims claims = createToken(sessionToken.getUuid(), user.getUuid(), NOW, IN_FIVE_MINUTES);
claims.put("lastRefreshTime", SIX_MINUTES_AGO);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
underTest.validateToken(request, response);
assertThat(underTest.validateToken(request, response)).isEmpty();
}
@Test
public void validate_token_refresh_state_when_refreshing_token() {
UserDto user = db.users().insertUser();
addJwtCookie();
// Token was created 10 days ago and refreshed 6 minutes ago
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, TEN_DAYS_AGO);
claims.put("xsrfToken", "CSRF_STATE");
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
underTest.validateToken(request, response);
verify(jwtSerializer).refresh(any(Claims.class), anyLong());
verify(jwtCsrfVerifier).refreshState(request, response, "CSRF_STATE", 3 * 24 * 60 * 60);
}
@Test
public void remove_token() {
addJwtCookie();
UserDto user = db.users().insertUser();
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
Claims claims = createToken(sessionToken, TEN_DAYS_AGO);
claims.put("lastRefreshTime", FOUR_MINUTES_AGO);
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
underTest.removeToken(request, response);
verifyCookie(findCookie("JWT-SESSION").get(), null, 0);
verify(jwtCsrfVerifier).removeState(request, response);
assertThat(dbClient.sessionTokensDao().selectByUuid(dbSession, sessionToken.getUuid())).isNotPresent();
}
@Test
public void does_not_remove_token_from_db_when_no_jwt_token_in_cookie() {
addJwtCookie();
UserDto user = db.users().insertUser();
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.empty());
underTest.removeToken(request, response);
verifyCookie(findCookie("JWT-SESSION").get(), null, 0);
verify(jwtCsrfVerifier).removeState(request, response);
assertThat(dbClient.sessionTokensDao().selectByUuid(dbSession, sessionToken.getUuid())).isPresent();
}
@Test
public void does_not_remove_token_from_db_when_no_cookie() {
UserDto user = db.users().insertUser();
SessionTokenDto sessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(IN_FIVE_MINUTES));
underTest.removeToken(request, response);
verifyCookie(findCookie("JWT-SESSION").get(), null, 0);
verify(jwtCsrfVerifier).removeState(request, response);
assertThat(dbClient.sessionTokensDao().selectByUuid(dbSession, sessionToken.getUuid())).isPresent();
}
private void verifyToken(JwtSerializer.JwtSession token, UserDto user, long expectedExpirationDuration, long expectedRefreshTime) {
assertThat(token.getExpirationTime()).isEqualTo(NOW + expectedExpirationDuration * 1000L);
assertThat(token.getUserLogin()).isEqualTo(user.getUuid());
assertThat(token.getProperties()).containsEntry("lastRefreshTime", expectedRefreshTime);
}
private Optional<Cookie> findCookie(String name) {
verify(response).addCookie(cookieArgumentCaptor.capture());
return cookieArgumentCaptor.getAllValues().stream()
.filter(cookie -> name.equals(cookie.getName()))
.findFirst();
}
private void verifyCookie(Cookie cookie, @Nullable String value, int expiry) {
assertThat(cookie.getPath()).isEqualTo("/");
assertThat(cookie.isHttpOnly()).isTrue();
assertThat(cookie.getMaxAge()).isEqualTo(expiry);
assertThat(cookie.isSecure()).isFalse();
assertThat(cookie.getValue()).isEqualTo(value);
}
private void verifySessionTokenInDb(JwtSerializer.JwtSession jwtSession) {
Map<String, Object> map = db.selectFirst(dbSession, "select st.uuid as \"uuid\", " +
"st.user_uuid as \"userUuid\", " +
"st.expiration_date as \"expirationDate\" " +
"from session_tokens st ");
assertThat(map)
.contains(
entry("uuid", jwtSession.getSessionTokenUuid()),
entry("expirationDate", jwtSession.getExpirationTime()));
}
private UserDto addUser(boolean active) {
UserDto user = newUserDto()
.setActive(active);
dbClient.userDao().insert(dbSession, user);
dbSession.commit();
return user;
}
private Cookie addJwtCookie() {
Cookie cookie = new JavaxHttpRequest.JavaxCookie(new javax.servlet.http.Cookie("JWT-SESSION", JWT_TOKEN));
when(request.getCookies()).thenReturn(new Cookie[] {cookie});
return cookie;
}
private Claims createToken(SessionTokenDto sessionToken, long createdAt) {
return createToken(sessionToken.getUuid(), sessionToken.getUserUuid(), createdAt, sessionToken.getExpirationDate());
}
private Claims createToken(String uuid, String userUuid, long createdAt, long expiredAt) {
DefaultClaims claims = new DefaultClaims();
claims.setId(uuid);
claims.setSubject(userUuid);
claims.setIssuedAt(new Date(createdAt));
claims.setExpiration(new Date(expiredAt));
claims.put("lastRefreshTime", createdAt);
return claims;
}
}
| 19,287 | 42.149888 | 152 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/UserLastConnectionDatesUpdaterImplIT.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.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class UserLastConnectionDatesUpdaterImplIT {
private static final long NOW = 10_000_000_000L;
private static final long ONE_MINUTE = 60_000L;
private static final long ONE_HOUR = ONE_MINUTE * 60L;
private static final long TWO_HOUR = ONE_HOUR * 2L;
@Rule
public DbTester db = DbTester.create();
private System2 system2 = new TestSystem2().setNow(NOW);
private UserLastConnectionDatesUpdaterImpl underTest = new UserLastConnectionDatesUpdaterImpl(db.getDbClient(), system2);
@Test
public void update_last_connection_date_from_user_when_last_connection_was_more_than_one_hour() {
UserDto user = db.users().insertUser();
db.users().updateLastConnectionDate(user, NOW - TWO_HOUR);
underTest.updateLastConnectionDateIfNeeded(user);
UserDto userReloaded = db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid());
assertThat(userReloaded.getLastConnectionDate()).isEqualTo(NOW);
}
@Test
public void update_last_connection_date_from_user_when_no_last_connection_date() {
UserDto user = db.users().insertUser();
underTest.updateLastConnectionDateIfNeeded(user);
UserDto userReloaded = db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid());
assertThat(userReloaded.getLastConnectionDate()).isEqualTo(NOW);
}
@Test
public void do_not_update_when_last_connection_from_user_was_less_than_one_hour() {
UserDto user = db.users().insertUser();
db.users().updateLastConnectionDate(user, NOW - ONE_MINUTE);
underTest.updateLastConnectionDateIfNeeded(user);
UserDto userReloaded = db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid());
assertThat(userReloaded.getLastConnectionDate()).isEqualTo(NOW - ONE_MINUTE);
}
@Test
public void update_last_connection_date_from_user_token_when_last_connection_was_more_than_one_hour() {
UserDto user = db.users().insertUser();
UserTokenDto userToken = db.users().insertToken(user);
db.getDbClient().userTokenDao().updateWithoutAudit(db.getSession(), userToken.setLastConnectionDate(NOW - TWO_HOUR));
db.commit();
underTest.updateLastConnectionDateIfNeeded(userToken);
UserTokenDto userTokenReloaded = db.getDbClient().userTokenDao().selectByTokenHash(db.getSession(), userToken.getTokenHash());
assertThat(userTokenReloaded.getLastConnectionDate()).isEqualTo(NOW);
}
@Test
public void update_last_connection_date_from_user_token_when_no_last_connection_date() {
UserDto user = db.users().insertUser();
UserTokenDto userToken = db.users().insertToken(user);
underTest.updateLastConnectionDateIfNeeded(userToken);
UserTokenDto userTokenReloaded = db.getDbClient().userTokenDao().selectByTokenHash(db.getSession(), userToken.getTokenHash());
assertThat(userTokenReloaded.getLastConnectionDate()).isEqualTo(NOW);
}
@Test
public void do_not_update_when_last_connection_from_user_token_was_less_than_one_hour() {
UserDto user = db.users().insertUser();
UserTokenDto userToken = db.users().insertToken(user);
db.getDbClient().userTokenDao().updateWithoutAudit(db.getSession(), userToken.setLastConnectionDate(NOW - ONE_MINUTE));
db.commit();
underTest.updateLastConnectionDateIfNeeded(userToken);
UserTokenDto userTokenReloaded = db.getDbClient().userTokenDao().selectByTokenHash(db.getSession(), userToken.getTokenHash());
assertThat(userTokenReloaded.getLastConnectionDate()).isEqualTo(NOW - ONE_MINUTE);
}
}
| 4,680 | 39.704348 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/UserRegistrarImplIT.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 java.util.Set;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
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.es.EsTester;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static java.util.Arrays.stream;
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.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.server.authentication.UserRegistrarImpl.GITHUB_PROVIDER;
import static org.sonar.server.authentication.UserRegistrarImpl.GITLAB_PROVIDER;
import static org.sonar.server.authentication.UserRegistrarImpl.LDAP_PROVIDER_PREFIX;
import static org.sonar.server.authentication.UserRegistrarImpl.SQ_AUTHORITY;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source.local;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source.realm;
public class UserRegistrarImplIT {
private static final String USER_LOGIN = "johndoo";
private static final UserIdentity USER_IDENTITY = UserIdentity.builder()
.setProviderId("ABCD")
.setProviderLogin(USER_LOGIN)
.setName("John")
.setEmail("john@email.com")
.build();
private static final TestIdentityProvider GH_IDENTITY_PROVIDER = new TestIdentityProvider()
.setKey("github")
.setName("name of github")
.setEnabled(true)
.setAllowsUsersToSignUp(true);
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
@Rule
public DbTester db = DbTester.create(new AlwaysIncreasingSystem2());
@Rule
public EsTester es = EsTester.create();
@Rule
public LogTester logTester = new LogTester();
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final DefaultGroupFinder groupFinder = new DefaultGroupFinder(db.getDbClient());
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private final UserUpdater userUpdater = new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), groupFinder, settings.asConfig(), auditPersister, localAuthentication);
private final UserRegistrarImpl underTest = new UserRegistrarImpl(db.getDbClient(), userUpdater, groupFinder, managedInstanceService);
private GroupDto defaultGroup;
@Before
public void setUp() {
defaultGroup = insertDefaultGroup();
}
@Test
public void authenticate_new_user() {
UserDto createdUser = underTest.register(newUserRegistration());
UserDto user = db.users().selectUserByLogin(createdUser.getLogin()).get();
assertThat(user).isNotNull();
assertThat(user.isActive()).isTrue();
assertThat(user.getName()).isEqualTo("John");
assertThat(user.getEmail()).isEqualTo("john@email.com");
assertThat(user.getExternalLogin()).isEqualTo(USER_LOGIN);
assertThat(user.getExternalIdentityProvider()).isEqualTo("github");
assertThat(user.getExternalId()).isEqualTo("ABCD");
checkGroupMembership(user, defaultGroup);
}
@Test
public void authenticate_new_user_with_sq_identity() {
TestIdentityProvider identityProvider = composeIdentityProvider(SQ_AUTHORITY, "sonarqube identity name", true, true);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, identityProvider, realm(BASIC, identityProvider.getName()));
UserDto createdUser = underTest.register(registration);
UserDto user = db.users().selectUserByLogin(createdUser.getLogin()).get();
assertThat(user).isNotNull();
assertThat(user.isActive()).isTrue();
assertThat(user.getLogin()).isEqualTo(USER_LOGIN);
assertThat(user.getName()).isEqualTo("John");
assertThat(user.getEmail()).isEqualTo("john@email.com");
assertThat(user.getExternalLogin()).isEqualTo(USER_LOGIN);
assertThat(user.getExternalIdentityProvider()).isEqualTo("sonarqube");
assertThat(user.getExternalId()).isEqualTo("ABCD");
assertThat(user.isLocal()).isFalse();
checkGroupMembership(user, defaultGroup);
}
@Test
public void authenticate_new_user_generates_login() {
underTest.register(newUserRegistration(UserIdentity.builder()
.setProviderId("ABCD")
.setProviderLogin(USER_LOGIN)
.setName("John Doe")
.setEmail("john@email.com")
.build()));
UserDto user = db.getDbClient().userDao().selectByEmail(db.getSession(), "john@email.com").get(0);
assertThat(user).isNotNull();
assertThat(user.isActive()).isTrue();
assertThat(user.getLogin()).isNotEqualTo("John Doe").startsWith("john-doe");
assertThat(user.getEmail()).isEqualTo("john@email.com");
assertThat(user.getExternalLogin()).isEqualTo(USER_LOGIN);
assertThat(user.getExternalIdentityProvider()).isEqualTo("github");
assertThat(user.getExternalId()).isEqualTo("ABCD");
}
@Test
public void authenticate_new_user_assigns_user_to_groups() {
GroupDto group1 = db.users().insertGroup("group1");
GroupDto group2 = db.users().insertGroup("group2");
UserDto loggedInUser = authenticate(USER_LOGIN, USER_IDENTITY.getEmail(), "group1", "group2", "group3");
Optional<UserDto> user = db.users().selectUserByLogin(loggedInUser.getLogin());
checkGroupMembership(user.get(), group1, group2, defaultGroup);
}
@Test
public void authenticate_new_user_sets_external_id_to_provider_login_when_id_is_null() {
UserIdentity newUser = UserIdentity.builder()
.setProviderId(null)
.setProviderLogin("johndoo")
.setName("JOhn")
.build();
UserDto user = underTest.register(newUserRegistration(newUser));
assertThat(db.users().selectUserByLogin(user.getLogin()).get())
.extracting(UserDto::getLogin, UserDto::getExternalId, UserDto::getExternalLogin)
.contains(user.getLogin(), "johndoo", "johndoo");
}
@Test
public void authenticate_new_user_with_gitlab_provider() {
TestIdentityProvider identityProvider = composeIdentityProvider(GITLAB_PROVIDER, "name of gitlab", true, true);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, identityProvider, local(BASIC));
UserDto newUser = underTest.register(registration);
assertThat(newUser)
.extracting(UserDto::getExternalIdentityProvider, UserDto::getExternalLogin)
.containsExactly("gitlab", USER_IDENTITY.getProviderLogin());
}
@Test
public void authenticate_new_user_throws_AuthenticationException_when_when_email_already_exists() {
db.users().insertUser(u -> u.setEmail("john@email.com"));
Source source = local(BASIC);
assertThatThrownBy(() -> underTest.register(newUserRegistration()))
.isInstanceOf(AuthenticationException.class)
.hasMessage("Email 'john@email.com' is already used")
.hasFieldOrPropertyWithValue("source", source)
.hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin())
.hasFieldOrPropertyWithValue("publicMessage", "This account is already associated with another authentication method."
+ " Sign in using the current authentication method,"
+ " or contact your administrator to transfer your account to a different authentication method.");
}
@Test
public void authenticate_new_user_throws_AuthenticationException_when_email_already_exists_multiple_times() {
db.users().insertUser(u -> u.setEmail("john@email.com"));
db.users().insertUser(u -> u.setEmail("john@email.com"));
Source source = realm(AuthenticationEvent.Method.FORM, GH_IDENTITY_PROVIDER.getName());
assertThatThrownBy(() -> underTest.register(newUserRegistration(source)))
.isInstanceOf(AuthenticationException.class)
.hasMessage("Email 'john@email.com' is already used")
.hasFieldOrPropertyWithValue("source", source)
.hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin())
.hasFieldOrPropertyWithValue("publicMessage", "This account is already associated with another authentication method."
+ " Sign in using the current authentication method,"
+ " or contact your administrator to transfer your account to a different authentication method.");
}
@Test
public void authenticate_new_user_fails_when_allow_users_to_signup_is_false() {
TestIdentityProvider identityProvider = composeIdentityProvider(GITHUB_PROVIDER, "Github", true, false);
Source source = realm(AuthenticationEvent.Method.FORM, identityProvider.getName());
UserRegistration registration = composeUserRegistration(USER_IDENTITY, identityProvider, source);
assertThatThrownBy(() -> underTest.register(registration))
.isInstanceOf(AuthenticationException.class)
.hasMessage("User signup disabled for provider 'github'")
.hasFieldOrPropertyWithValue("source", source)
.hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin())
.hasFieldOrPropertyWithValue("publicMessage", "'github' users are not allowed to sign up");
}
@Test
public void register_whenNewUnmanagedUserAndManagedInstance_shouldThrow() {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
TestIdentityProvider identityProvider = composeIdentityProvider("saml", "Okta", true, true);
Source source = realm(AuthenticationEvent.Method.FORM, identityProvider.getName());
UserRegistration registration = composeUserRegistration(USER_IDENTITY, identityProvider, source);
assertThatThrownBy(() -> underTest.register(registration))
.isInstanceOf(AuthenticationException.class)
.hasMessage("No account found for this user. As the instance is managed, make sure to provision the user from your IDP.")
.hasFieldOrPropertyWithValue("source", source)
.hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin());
}
@Test
public void register_whenNewManagedUserAndManagedInstance_shouldCreateAndReturnUser() {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
TestIdentityProvider identityProvider = composeIdentityProvider("saml", "Okta", true, true);
Source source = realm(AuthenticationEvent.Method.FORM, identityProvider.getName());
UserRegistration registration = composeUserRegistration(USER_IDENTITY, identityProvider, source, true);
UserDto userDto = underTest.register(registration);
assertThat(userDto.getExternalId()).isEqualTo(USER_IDENTITY.getProviderId());
assertThat(userDto.getExternalLogin()).isEqualTo(USER_IDENTITY.getProviderLogin());
assertThat(userDto.getName()).isEqualTo(USER_IDENTITY.getName());
assertThat(userDto.getEmail()).isEqualTo(USER_IDENTITY.getEmail());
}
@Test
public void authenticate_existing_user_doesnt_change_group_membership() {
UserDto user = db.users().insertUser(u -> u.setExternalIdentityProvider(GH_IDENTITY_PROVIDER.getKey()));
GroupDto group1 = db.users().insertGroup("group1");
db.users().insertMember(group1, user);
db.users().insertMember(defaultGroup, user);
authenticate(user.getExternalLogin(), user.getEmail(), "group1");
checkGroupMembership(user, group1, defaultGroup);
}
@Test
public void authenticate_and_update_existing_user_matching_external_id() {
UserDto user = insertUser("Old login", "Old name", "Old email", USER_IDENTITY.getProviderId(), "old identity", GH_IDENTITY_PROVIDER.getKey(), false, true);
underTest.register(newUserRegistration());
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider,
UserDto::isActive)
.contains(USER_LOGIN, "John", "john@email.com", "ABCD", "johndoo", "github", true);
}
@Test
public void authenticate_and_update_existing_user_matching_external_login_and_email() {
UserDto user = insertUser("Old login", "Old name", USER_IDENTITY.getEmail(), "Old id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, true);
underTest.register(newUserRegistration());
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider,
UserDto::isActive)
.contains("John", "john@email.com", "ABCD", "johndoo", "github", true);
}
@Test
public void authenticate_existing_user_should_not_update_login() {
UserDto user = insertUser("old login", USER_IDENTITY.getName(), USER_IDENTITY.getEmail(), USER_IDENTITY.getProviderId(), "old identity", GH_IDENTITY_PROVIDER.getKey(), false, true);
underTest.register(newUserRegistration());
// no new user should be created
assertThat(db.countRowsOfTable(db.getSession(), "users")).isOne();
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider,
UserDto::isActive)
.containsExactly("old login", USER_IDENTITY.getName(), USER_IDENTITY.getEmail(), USER_IDENTITY.getProviderId(), USER_IDENTITY.getProviderLogin(),
GH_IDENTITY_PROVIDER.getKey(), true);
verify(auditPersister, never()).updateUserPassword(any(), any());
}
@Test
public void authenticate_existing_user_matching_external_login_and_email_when_external_id_is_null() {
UserDto user = insertUser("", "Old name", "john@email.com", "Old id", "johndoo", GH_IDENTITY_PROVIDER.getKey(), false, true);
underTest.register(newUserRegistration(UserIdentity.builder()
.setProviderId(null)
.setProviderLogin("johndoo")
.setName("John")
.setEmail("john@email.com")
.build()));
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider,
UserDto::isActive)
.contains(user.getLogin(), "John", "john@email.com", "johndoo", "johndoo", "github", true);
}
@Test
public void do_not_authenticate_gitlab_user_matching_external_login() {
IdentityProvider provider = composeIdentityProvider(GITLAB_PROVIDER, "name of gitlab", true,false);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, provider, local(BASIC));
insertUser("Old login", "Old name", USER_IDENTITY.getEmail(), "Old id", USER_IDENTITY.getProviderLogin(), GITLAB_PROVIDER, false, true);
assertThatThrownBy(() -> underTest.register(registration))
.isInstanceOf(AuthenticationException.class)
.hasMessage(String.format("Failed to authenticate with login '%s'", USER_IDENTITY.getProviderLogin()));
}
@Test
public void do_not_authenticate_and_update_existing_github_user_matching_external_login_if_emails_do_not_match() {
insertUser("Old login", "Old name", "another-email@sonarsource.com", "Old id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, true);
assertThatThrownBy(() -> underTest.register(newUserRegistration()))
.isInstanceOf(AuthenticationException.class)
.hasMessage(String.format("Failed to authenticate with login '%s'", USER_IDENTITY.getProviderLogin()));
assertThat(logTester.logs()).contains(String.format("User with login '%s' tried to login with email '%s' which doesn't match the email on record '%s'",
USER_IDENTITY.getProviderLogin(), USER_IDENTITY.getEmail(), "another-email@sonarsource.com"));
}
@Test
public void authenticate_and_update_existing_github_user_matching_external_login_if_emails_match_case_insensitive() {
UserDto user = insertUser("Old login", "Old name", "John@Email.com", USER_IDENTITY.getProviderId(), "old identity", GH_IDENTITY_PROVIDER.getKey(), false, false);
underTest.register(newUserRegistration());
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider,
UserDto::isActive)
.contains(USER_LOGIN, "John", "john@email.com", "ABCD", "johndoo", "github", true);
}
@Test
public void authenticate_and_update_existing_user_matching_external_login_and_emails_mismatch() {
IdentityProvider provider = composeIdentityProvider("other", "name of other", true,false);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, provider, local(BASIC));
UserDto user = insertUser("Old login", "Old name", "another-email@sonarsource.com", "Old id", USER_IDENTITY.getProviderLogin(), registration.getProvider().getKey(), false, true);
underTest.register(registration);
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider,
UserDto::isActive)
.contains(user.getLogin(), "John", "john@email.com", "ABCD", "johndoo", "other", true);
}
@Test
public void authenticate_user_eligible_for_ldap_migration() {
String providerKey = LDAP_PROVIDER_PREFIX + "PROVIDER";
IdentityProvider provider = composeIdentityProvider(providerKey, "name of provider", true,false);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, provider, local(BASIC));
UserDto user = insertUser(USER_IDENTITY.getProviderLogin(), "name", "another-email@sonarsource.com", "login", "id", SQ_AUTHORITY, false, true);
underTest.register(registration);
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider, UserDto::isActive, UserDto::isLocal)
.contains(user.getLogin(), "John", "john@email.com", "ABCD", "johndoo", providerKey, true, false);
}
@Test
public void authenticate_user_for_ldap_migration_is_not_possible_when_user_is_local() {
String providerKey = LDAP_PROVIDER_PREFIX + "PROVIDER";
IdentityProvider provider = composeIdentityProvider(providerKey, "name of provider", true,true);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, provider, local(BASIC));
UserDto user = insertUser(USER_IDENTITY.getProviderLogin(), "name", "another-email@sonarsource.com","id", "login", SQ_AUTHORITY, true, true);
underTest.register(registration);
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalIdentityProvider, UserDto::isActive, UserDto::isLocal)
.contains(user.getLogin(), "name", "another-email@sonarsource.com", "id", "sonarqube", true, true);
}
@Test
public void authenticate_user_for_ldap_migration_is_not_possible_when_external_identity_provider_is_not_sonarqube() {
String providerKey = LDAP_PROVIDER_PREFIX + "PROVIDER";
IdentityProvider provider = composeIdentityProvider(providerKey, "name of provider", true,true);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, provider, local(BASIC));
UserDto user = insertUser(USER_IDENTITY.getProviderLogin(), "name", "another-email@sonarsource.com", "id", "login", "not_sonarqube", false, true);
underTest.register(registration);
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalIdentityProvider, UserDto::isActive, UserDto::isLocal)
.contains(user.getLogin(), "name", "another-email@sonarsource.com", "id", "not_sonarqube", true, false);
}
@Test
public void authenticate_user_for_ldap_migration_is_not_possible_when_identity_provider_key_is_not_prefixed_properly() {
String providerKey = "INVALID_PREFIX" + LDAP_PROVIDER_PREFIX + "PROVIDER";
IdentityProvider provider = composeIdentityProvider(providerKey, "name of provider", true,true);
UserRegistration registration = composeUserRegistration(USER_IDENTITY, provider, local(BASIC));
UserDto user = insertUser(USER_IDENTITY.getProviderLogin(), "name", "another-email@sonarsource.com", "id", "login", SQ_AUTHORITY, false, true);
underTest.register(registration);
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getName, UserDto::getEmail, UserDto::getExternalId, UserDto::getExternalIdentityProvider, UserDto::isActive, UserDto::isLocal)
.contains(user.getLogin(), "name", "another-email@sonarsource.com", "id", "sonarqube", true, false);
}
@Test
public void authenticate_and_update_existing_user_matching_external_login_if_email_is_missing() {
insertUser("Old login", "Old name", null, "Old id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, true);
underTest.register(newUserRegistration());
Optional<UserDto> user = db.users().selectUserByLogin("Old login");
assertThat(user).isPresent();
assertThat(user.get().getEmail()).isEqualTo(USER_IDENTITY.getEmail());
}
@Test
public void do_not_authenticate_and_update_existing_user_matching_external_id_if_external_provider_does_not_match() {
insertUser("Old login", "Old name", null, USER_IDENTITY.getProviderId(), USER_IDENTITY.getProviderLogin(), "Old provider", false, true);
underTest.register(newUserRegistration());
assertThat(db.countRowsOfTable("users")).isEqualTo(2);
}
@Test
public void authenticate_existing_user_should_update_login() {
UserDto user = insertUser("Old login", null, null, USER_IDENTITY.getProviderId(), "old identity", GH_IDENTITY_PROVIDER.getKey(), false, true);
underTest.register(newUserRegistration());
assertThat(db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid()))
.extracting(UserDto::getLogin, UserDto::getExternalLogin)
.contains(USER_LOGIN, USER_IDENTITY.getProviderLogin());
}
@Test
public void authenticate_existing_disabled_user_should_reactivate_it() {
insertUser(USER_LOGIN, "Old name", USER_IDENTITY.getEmail(), "Old id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, false);
underTest.register(newUserRegistration());
UserDto userDto = db.users().selectUserByLogin(USER_LOGIN).get();
assertThat(userDto.isActive()).isTrue();
assertThat(userDto.getName()).isEqualTo(USER_IDENTITY.getName());
assertThat(userDto.getEmail()).isEqualTo(USER_IDENTITY.getEmail());
assertThat(userDto.getExternalId()).isEqualTo(USER_IDENTITY.getProviderId());
assertThat(userDto.getExternalLogin()).isEqualTo(USER_IDENTITY.getProviderLogin());
assertThat(userDto.getExternalIdentityProvider()).isEqualTo(GH_IDENTITY_PROVIDER.getKey());
}
@Test
public void authenticating_existing_user_throws_AuthenticationException_when_email_already_exists() {
db.users().insertUser(u -> u.setEmail("john@email.com"));
db.users().insertUser(u -> u.setEmail(null));
UserIdentity userIdentity = UserIdentity.builder()
.setProviderLogin("johndoo")
.setName("John")
.setEmail("john@email.com")
.build();
Source source = realm(AuthenticationEvent.Method.FORM, GH_IDENTITY_PROVIDER.getName());
assertThatThrownBy(() -> underTest.register(newUserRegistration(userIdentity, source)))
.isInstanceOf(AuthenticationException.class)
.hasMessage("Email 'john@email.com' is already used")
.hasFieldOrPropertyWithValue("source", source)
.hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin())
.hasFieldOrPropertyWithValue("publicMessage", "This account is already associated with another authentication method."
+ " Sign in using the current authentication method,"
+ " or contact your administrator to transfer your account to a different authentication method.");
}
@Test
public void authenticate_existing_user_succeeds_when_email_has_not_changed() {
UserDto currentUser = insertUser("login", "John", "john@email.com", "id", "externalLogin", GH_IDENTITY_PROVIDER.getKey(), false, true);
UserIdentity userIdentity = UserIdentity.builder()
.setProviderId(currentUser.getExternalId())
.setProviderLogin(currentUser.getExternalLogin())
.setName("John")
.setEmail("john@email.com")
.build();
underTest.register(newUserRegistration(userIdentity));
UserDto currentUserReloaded = db.users().selectUserByLogin(currentUser.getLogin()).get();
assertThat(currentUserReloaded.getEmail()).isEqualTo("john@email.com");
}
@Test
public void authenticate_existing_user_and_add_new_groups() {
UserDto user = insertUser("login", "John", USER_IDENTITY.getEmail(), "id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, true);
GroupDto group1 = db.users().insertGroup("group1");
GroupDto group2 = db.users().insertGroup("group2");
authenticate(USER_IDENTITY.getProviderLogin(), USER_IDENTITY.getEmail(), "group1", "group2", "group3");
checkGroupMembership(user, group1, group2);
}
@Test
public void authenticate_existing_user_and_remove_groups() {
UserDto user = insertUser("login", "John", USER_IDENTITY.getEmail(), "id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, true);
GroupDto group1 = db.users().insertGroup("group1");
GroupDto group2 = db.users().insertGroup("group2");
db.users().insertMember(group1, user);
db.users().insertMember(group2, user);
authenticate(USER_IDENTITY.getProviderLogin(), USER_IDENTITY.getEmail(), "group1");
checkGroupMembership(user, group1);
}
@Test
public void authenticate_existing_user_and_remove_all_groups_expect_default() {
UserDto user = insertUser("login", "John", USER_IDENTITY.getEmail(), "id", USER_IDENTITY.getProviderLogin(), GH_IDENTITY_PROVIDER.getKey(), false, true);
GroupDto group1 = db.users().insertGroup("group1");
GroupDto group2 = db.users().insertGroup("group2");
db.users().insertMember(group1, user);
db.users().insertMember(group2, user);
db.users().insertMember(defaultGroup, user);
authenticate(user.getExternalLogin(), user.getEmail());
checkGroupMembership(user, defaultGroup);
}
private static UserRegistration newUserRegistration(UserIdentity userIdentity) {
return newUserRegistration(userIdentity, local(BASIC));
}
private static UserRegistration newUserRegistration(UserIdentity userIdentity, Source source) {
return UserRegistration.builder()
.setUserIdentity(userIdentity)
.setProvider(GH_IDENTITY_PROVIDER)
.setSource(source)
.build();
}
private static UserRegistration newUserRegistration(Source source) {
return newUserRegistration(USER_IDENTITY, source);
}
private static UserRegistration newUserRegistration() {
return newUserRegistration(USER_IDENTITY, local(BASIC));
}
private UserDto authenticate(String providerLogin, @Nullable String email, String... groups) {
return underTest.register(newUserRegistration(UserIdentity.builder()
.setProviderLogin(providerLogin)
.setName("John")
.setEmail(email)
.setGroups(Set.of(groups))
.build()));
}
private void checkGroupMembership(UserDto user, GroupDto... expectedGroups) {
assertThat(db.users().selectGroupUuidsOfUser(user)).containsOnly(stream(expectedGroups).map(GroupDto::getUuid).toList().toArray(new String[]{}));
}
private GroupDto insertDefaultGroup() {
return db.users().insertDefaultGroup();
}
private UserDto insertUser(String login, String name, String email, String externalId, String externalLogin, String externalIdentityProvider, boolean isLocal, boolean isActive) {
return db.users().insertUser(configureUser(login, name, email, externalId, externalLogin, externalIdentityProvider, isLocal, isActive));
}
private static Consumer<UserDto> configureUser(String login, String name, String email, String externalId, String externalLogin, String externalIdentityProvider, boolean isLocal, boolean isActive) {
return user -> user
.setLogin(login)
.setName(name)
.setEmail(email)
.setExternalId(externalId)
.setExternalLogin(externalLogin)
.setExternalIdentityProvider(externalIdentityProvider)
.setLocal(isLocal)
.setActive(isActive);
}
private static TestIdentityProvider composeIdentityProvider(String providerKey, String name, boolean enabled, boolean allowsUsersToSignUp) {
return new TestIdentityProvider()
.setKey(providerKey)
.setName(name)
.setEnabled(enabled)
.setAllowsUsersToSignUp(allowsUsersToSignUp);
}
private static UserRegistration composeUserRegistration(UserIdentity userIdentity, IdentityProvider identityProvider, Source source, Boolean managed) {
return UserRegistration.builder()
.setUserIdentity(userIdentity)
.setProvider(identityProvider)
.setSource(source)
.setManaged(managed)
.build();
}
private static UserRegistration composeUserRegistration(UserIdentity userIdentity, IdentityProvider identityProvider, Source source) {
return composeUserRegistration(userIdentity, identityProvider, source, false);
}
}
| 31,815 | 48.48056 | 200 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/UserSessionInitializerIT.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.time.LocalDateTime;
import java.time.ZoneOffset;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.BaseIdentityProvider;
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.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationEvent.Method;
import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.tester.AnonymousMockUserSession;
import org.sonar.server.tester.MockUserSession;
import org.sonar.server.user.ThreadLocalUserSession;
import org.sonar.server.user.TokenUserSession;
import org.sonar.server.user.UserSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.formatDateTime;
public class UserSessionInitializerIT {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private ThreadLocalUserSession threadLocalSession = mock(ThreadLocalUserSession.class);
private HttpRequest request = mock(HttpRequest.class);
private HttpResponse response = mock(HttpResponse.class);
private RequestAuthenticator authenticator = mock(RequestAuthenticator.class);
private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private MapSettings settings = new MapSettings();
private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
private UserSessionInitializer underTest = new UserSessionInitializer(settings.asConfig(), threadLocalSession, authenticationEvent, authenticator);
@Before
public void setUp() {
when(request.getContextPath()).thenReturn("");
when(request.getRequestURI()).thenReturn("/measures");
}
@Test
public void check_urls() {
assertPathIsNotIgnored("/");
assertPathIsNotIgnored("/foo");
assertPathIsNotIgnored("/api/server_id/show");
assertPathIsIgnored("/api/authentication/login");
assertPathIsIgnored("/api/authentication/logout");
assertPathIsIgnored("/api/authentication/validate");
assertPathIsIgnored("/batch/index");
assertPathIsIgnored("/batch/file");
assertPathIsIgnored("/maintenance/index");
assertPathIsIgnored("/setup/index");
assertPathIsIgnored("/sessions/new");
assertPathIsIgnored("/sessions/logout");
assertPathIsIgnored("/sessions/unauthorized");
assertPathIsIgnored("/oauth2/callback/github");
assertPathIsIgnored("/oauth2/callback/foo");
assertPathIsIgnored("/api/system/db_migration_status");
assertPathIsIgnored("/api/system/status");
assertPathIsIgnored("/api/system/migrate_db");
assertPathIsIgnored("/api/server/version");
assertPathIsIgnored("/api/users/identity_providers");
assertPathIsIgnored("/api/l10n/index");
// exclude project_badge url, as they can be auth. by a token as queryparam
assertPathIsIgnored("/api/project_badges/measure");
assertPathIsIgnored("/api/project_badges/quality_gate");
// exlude passcode urls
assertPathIsIgnoredWithAnonymousAccess("/api/ce/info");
assertPathIsIgnoredWithAnonymousAccess("/api/ce/pause");
assertPathIsIgnoredWithAnonymousAccess("/api/ce/resume");
assertPathIsIgnoredWithAnonymousAccess("/api/system/health");
assertPathIsIgnoredWithAnonymousAccess("/api/system/liveness");
assertPathIsIgnoredWithAnonymousAccess("/api/monitoring/metrics");
// exclude static resources
assertPathIsIgnored("/css/style.css");
assertPathIsIgnored("/images/logo.png");
assertPathIsIgnored("/js/jquery.js");
}
@Test
public void return_code_401_when_not_authenticated_and_with_force_authentication() {
ArgumentCaptor<AuthenticationException> exceptionArgumentCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
when(threadLocalSession.isLoggedIn()).thenReturn(false);
when(authenticator.authenticate(request, response)).thenReturn(new AnonymousMockUserSession());
assertThat(underTest.initUserSession(request, response)).isTrue();
verifyNoMoreInteractions(response);
verify(authenticationEvent).loginFailure(eq(request), exceptionArgumentCaptor.capture());
verifyNoMoreInteractions(threadLocalSession);
AuthenticationException authenticationException = exceptionArgumentCaptor.getValue();
assertThat(authenticationException.getSource()).isEqualTo(Source.local(Method.BASIC));
assertThat(authenticationException.getLogin()).isNull();
assertThat(authenticationException.getMessage()).isEqualTo("User must be authenticated");
assertThat(authenticationException.getPublicMessage()).isNull();
}
@Test
public void does_not_return_code_401_when_not_authenticated_and_with_force_authentication_off() {
when(threadLocalSession.isLoggedIn()).thenReturn(false);
when(authenticator.authenticate(request, response)).thenReturn(new AnonymousMockUserSession());
settings.setProperty("sonar.forceAuthentication", false);
assertThat(underTest.initUserSession(request, response)).isTrue();
verifyNoMoreInteractions(response);
}
@Test
public void return_401_and_stop_on_ws() {
when(request.getRequestURI()).thenReturn("/api/issues");
AuthenticationException authenticationException = AuthenticationException.newBuilder().setSource(Source.jwt()).setMessage("Token id hasn't been found").build();
doThrow(authenticationException).when(authenticator).authenticate(request, response);
assertThat(underTest.initUserSession(request, response)).isFalse();
verify(response).setStatus(401);
verify(authenticationEvent).loginFailure(request, authenticationException);
verifyNoMoreInteractions(threadLocalSession);
}
@Test
public void return_401_and_stop_on_batch_ws() {
when(request.getRequestURI()).thenReturn("/batch/global");
doThrow(AuthenticationException.newBuilder().setSource(Source.jwt()).setMessage("Token id hasn't been found").build())
.when(authenticator).authenticate(request, response);
assertThat(underTest.initUserSession(request, response)).isFalse();
verify(response).setStatus(401);
verifyNoMoreInteractions(threadLocalSession);
}
@Test
public void return_to_session_unauthorized_when_error_on_from_external_provider() throws Exception {
doThrow(AuthenticationException.newBuilder().setSource(Source.external(newBasicIdentityProvider("failing"))).setPublicMessage("Token id hasn't been found").build())
.when(authenticator).authenticate(request, response);
assertThat(underTest.initUserSession(request, response)).isFalse();
verify(response).sendRedirect("/sessions/unauthorized");
verify(response).addCookie(cookieArgumentCaptor.capture());
Cookie cookie = cookieArgumentCaptor.getValue();
assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR");
assertThat(cookie.getValue()).isEqualTo("Token%20id%20hasn%27t%20been%20found");
assertThat(cookie.getPath()).isEqualTo("/");
assertThat(cookie.isHttpOnly()).isFalse();
assertThat(cookie.getMaxAge()).isEqualTo(300);
assertThat(cookie.isSecure()).isFalse();
}
@Test
public void return_to_session_unauthorized_when_error_on_from_external_provider_with_context_path() throws Exception {
when(request.getContextPath()).thenReturn("/sonarqube");
doThrow(AuthenticationException.newBuilder().setSource(Source.external(newBasicIdentityProvider("failing"))).setPublicMessage("Token id hasn't been found").build())
.when(authenticator).authenticate(request, response);
assertThat(underTest.initUserSession(request, response)).isFalse();
verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
}
@Test
public void expiration_header_added_when_authenticating_with_an_expiring_token() {
long expirationTimestamp = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
UserDto userDto = new UserDto();
UserTokenDto userTokenDto = new UserTokenDto().setExpirationDate(expirationTimestamp);
UserSession session = new TokenUserSession(DbTester.create().getDbClient(), userDto, userTokenDto);
when(authenticator.authenticate(request, response)).thenReturn(session);
when(threadLocalSession.isLoggedIn()).thenReturn(true);
assertThat(underTest.initUserSession(request, response)).isTrue();
verify(response).addHeader("SonarQube-Authentication-Token-Expiration", formatDateTime(expirationTimestamp));
}
private void assertPathIsIgnored(String path) {
when(request.getRequestURI()).thenReturn(path);
assertThat(underTest.initUserSession(request, response)).isTrue();
verifyNoMoreInteractions(threadLocalSession, authenticator);
reset(threadLocalSession, authenticator);
}
private void assertPathIsIgnoredWithAnonymousAccess(String path) {
when(request.getRequestURI()).thenReturn(path);
UserSession session = new AnonymousMockUserSession();
when(authenticator.authenticate(request, response)).thenReturn(session);
assertThat(underTest.initUserSession(request, response)).isTrue();
verify(threadLocalSession).set(session);
reset(threadLocalSession, authenticator);
}
private void assertPathIsNotIgnored(String path) {
when(request.getRequestURI()).thenReturn(path);
UserSession session = new MockUserSession("foo");
when(authenticator.authenticate(request, response)).thenReturn(session);
assertThat(underTest.initUserSession(request, response)).isTrue();
verify(threadLocalSession).set(session);
reset(threadLocalSession, authenticator);
}
private static BaseIdentityProvider newBasicIdentityProvider(String name) {
BaseIdentityProvider mock = mock(BaseIdentityProvider.class);
when(mock.getName()).thenReturn(name);
return mock;
}
}
| 11,331 | 43.439216 | 168 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/purge/ExpiredSessionsCleanerIT.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.purge;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.testfixtures.log.LogAndArguments;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
import org.sonar.db.user.SamlMessageIdDto;
import org.sonar.db.user.SessionTokenDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.util.AbstractStoppableExecutorService;
import org.sonar.server.util.GlobalLockManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ExpiredSessionsCleanerIT {
private static final long NOW = 1_000_000_000L;
private TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public LogTester logTester = new LogTester();
private GlobalLockManager lockManager = mock(GlobalLockManager.class);
private SyncSessionTokensCleanerExecutorService executorService = new SyncSessionTokensCleanerExecutorService();
private ExpiredSessionsCleaner underTest = new ExpiredSessionsCleaner(executorService, db.getDbClient(), lockManager);
@Test
public void purge_expired_session_tokens() {
when(lockManager.tryLock(anyString())).thenReturn(true);
UserDto user = db.users().insertUser();
SessionTokenDto validSessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(NOW + 1_000_000L));
SessionTokenDto expiredSessionToken = db.users().insertSessionToken(user, st -> st.setExpirationDate(NOW - 1_000_000L));
underTest.start();
executorService.runCommand();
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(db.getSession(), validSessionToken.getUuid())).isPresent();
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(db.getSession(), expiredSessionToken.getUuid())).isNotPresent();
assertThat(logTester.getLogs(LoggerLevel.INFO))
.extracting(LogAndArguments::getFormattedMsg)
.contains("Purge of expired session tokens has removed 1 elements");
}
@Test
public void purge_expired_saml_message_ids() {
when(lockManager.tryLock(anyString())).thenReturn(true);
db.getDbClient().samlMessageIdDao().insert(db.getSession(), new SamlMessageIdDto().setMessageId("MESSAGE_1").setExpirationDate(NOW + 1_000_000L));
db.getDbClient().samlMessageIdDao().insert(db.getSession(), new SamlMessageIdDto().setMessageId("MESSAGE_2").setExpirationDate(NOW - 1_000_000L));
db.commit();
underTest.start();
executorService.runCommand();
assertThat(db.getDbClient().samlMessageIdDao().selectByMessageId(db.getSession(), "MESSAGE_1")).isPresent();
assertThat(db.getDbClient().samlMessageIdDao().selectByMessageId(db.getSession(), "MESSAGE_2")).isNotPresent();
assertThat(logTester.getLogs(LoggerLevel.INFO))
.extracting(LogAndArguments::getFormattedMsg)
.contains("Purge of expired SAML message ids has removed 1 elements");
}
@Test
public void do_not_execute_purge_when_fail_to_get_lock() {
when(lockManager.tryLock(anyString())).thenReturn(false);
SessionTokenDto expiredSessionToken = db.users().insertSessionToken(db.users().insertUser(), st -> st.setExpirationDate(NOW - 1_000_000L));
underTest.start();
executorService.runCommand();
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(db.getSession(), expiredSessionToken.getUuid())).isPresent();
}
private static class SyncSessionTokensCleanerExecutorService extends AbstractStoppableExecutorService<ScheduledExecutorService> implements ExpiredSessionsCleanerExecutorService {
private Runnable command;
public SyncSessionTokensCleanerExecutorService() {
super(null);
}
public void runCommand() {
command.run();
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
this.command = command;
return null;
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return null;
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return null;
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return null;
}
}
}
| 5,585 | 38.9 | 180 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/ServerUserSessionIT.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.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
import static com.google.common.base.Preconditions.checkState;
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.sonar.db.component.ComponentTesting.newChildComponent;
import static org.sonar.db.component.ComponentTesting.newProjectCopy;
public class ServerUserSessionIT {
@Rule
public final DbTester db = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = db.getDbClient();
@Test
public void anonymous_is_not_logged_in_and_does_not_have_login() {
UserSession session = newAnonymousSession();
assertThat(session.getLogin()).isNull();
assertThat(session.getUuid()).isNull();
assertThat(session.isLoggedIn()).isFalse();
}
@Test
public void shouldResetPassword_is_false_on_anonymous() {
assertThat(newAnonymousSession().shouldResetPassword()).isFalse();
}
@Test
public void shouldResetPassword_is_false_if_set_on_UserDto() {
UserDto user = db.users().insertUser(userDto -> userDto.setResetPassword(false));
assertThat(newUserSession(user).shouldResetPassword()).isFalse();
}
@Test
public void shouldResetPassword_is_true_if_set_on_UserDto() {
UserDto user = db.users().insertUser(userDto -> userDto.setResetPassword(true));
assertThat(newUserSession(user).shouldResetPassword()).isTrue();
}
@Test
public void getGroups_is_empty_on_anonymous() {
assertThat(newAnonymousSession().getGroups()).isEmpty();
}
@Test
public void getGroups_is_empty_if_user_is_not_member_of_any_group() {
UserDto user = db.users().insertUser();
assertThat(newUserSession(user).getGroups()).isEmpty();
}
@Test
public void getGroups_returns_the_groups_of_logged_in_user() {
UserDto user = db.users().insertUser();
GroupDto group1 = db.users().insertGroup();
GroupDto group2 = db.users().insertGroup();
db.users().insertMember(group1, user);
db.users().insertMember(group2, user);
assertThat(newUserSession(user).getGroups()).extracting(GroupDto::getUuid).containsOnly(group1.getUuid(), group2.getUuid());
}
@Test
public void getLastSonarlintConnectionDate() {
UserDto user = db.users().insertUser(p -> p.setLastSonarlintConnectionDate(1000L));
assertThat(newUserSession(user).getLastSonarlintConnectionDate()).isEqualTo(1000L);
}
@Test
public void getGroups_keeps_groups_in_cache() {
UserDto user = db.users().insertUser();
GroupDto group1 = db.users().insertGroup();
GroupDto group2 = db.users().insertGroup();
db.users().insertMember(group1, user);
ServerUserSession session = newUserSession(user);
assertThat(session.getGroups()).extracting(GroupDto::getUuid).containsOnly(group1.getUuid());
// membership updated but not cache
db.users().insertMember(group2, user);
assertThat(session.getGroups()).extracting(GroupDto::getUuid).containsOnly(group1.getUuid());
}
@Test
public void isActive_redirectsValueFromUserDto() {
UserDto active = db.users().insertUser();
active.setActive(true);
assertThat(newUserSession(active).isActive()).isTrue();
UserDto notActive = db.users().insertUser();
notActive.setActive(false);
assertThat(newUserSession(notActive).isActive()).isFalse();
}
@Test
public void checkComponentUuidPermission_fails_with_FE_when_user_has_not_permission_for_specified_uuid_in_db() {
UserDto user = db.users().insertUser();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project);
UserSession session = newUserSession(user);
assertThatForbiddenExceptionIsThrown(() -> session.checkComponentUuidPermission(UserRole.USER, "another-uuid"));
}
@Test
public void checkChildProjectsPermission_succeeds_if_user_has_permissions_on_all_application_child_projects() {
UserDto user = db.users().insertUser();
ProjectData project = db.components().insertPrivateProject();
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project.getProjectDto());
ProjectData application = db.components().insertPrivateApplication();
db.components().addApplicationProject(application, project);
UserSession underTest = newUserSession(user);
assertThat(underTest.checkChildProjectsPermission(UserRole.USER, application.getMainBranchComponent())).isSameAs(underTest);
}
@Test
public void checkChildProjectsPermission_succeeds_if_component_is_not_an_application() {
UserDto user = db.users().insertUser();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
UserSession underTest = newUserSession(user);
assertThat(underTest.checkChildProjectsPermission(UserRole.USER, project)).isSameAs(underTest);
}
@Test
public void checkChildProjectsPermission_fails_with_FE_when_user_has_not_permission_for_specified_uuid_in_db() {
UserDto user = db.users().insertUser();
ProjectData project = db.components().insertPrivateProject();
ProjectData application = db.components().insertPrivateApplication();
db.components().addApplicationProject(application, project);
// add computed project
db.components().insertComponent(newProjectCopy(project, application));
UserSession underTest = newUserSession(user);
assertThatForbiddenExceptionIsThrown(() -> underTest.checkChildProjectsPermission(UserRole.USER, application.getMainBranchComponent()));
}
@Test
public void checkPermission_throws_ForbiddenException_when_user_doesnt_have_the_specified_permission() {
UserDto user = db.users().insertUser();
assertThatForbiddenExceptionIsThrown(() -> newUserSession(user).checkPermission(GlobalPermission.PROVISION_PROJECTS));
}
@Test
public void checkPermission_succeeds_when_user_has_the_specified_permission() {
UserDto adminUser = db.users().insertAdminByUserPermission();
db.users().insertGlobalPermissionOnUser(adminUser, GlobalPermission.PROVISION_PROJECTS);
newUserSession(adminUser).checkPermission(GlobalPermission.PROVISION_PROJECTS);
}
@Test
public void test_hasPermission_for_logged_in_user() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.PROVISION_PROJECTS);
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, project);
UserSession session = newUserSession(user);
assertThat(session.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
assertThat(session.hasPermission(GlobalPermission.ADMINISTER)).isFalse();
}
@Test
public void test_hasPermission_for_anonymous_user() {
db.users().insertPermissionOnAnyone(GlobalPermission.PROVISION_PROJECTS);
UserSession session = newAnonymousSession();
assertThat(session.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
assertThat(session.hasPermission(GlobalPermission.ADMINISTER)).isFalse();
}
@Test
public void hasPermission_keeps_cache_of_permissions_of_logged_in_user() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.PROVISION_PROJECTS);
UserSession session = newUserSession(user);
// feed the cache
assertThat(session.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
// change permissions without updating the cache
db.users().deletePermissionFromUser(user, GlobalPermission.PROVISION_PROJECTS);
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
assertThat(session.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
assertThat(session.hasPermission(GlobalPermission.ADMINISTER)).isFalse();
assertThat(session.hasPermission(GlobalPermission.SCAN)).isFalse();
}
@Test
public void hasPermission_keeps_cache_of_permissions_of_anonymous_user() {
db.users().insertPermissionOnAnyone(GlobalPermission.PROVISION_PROJECTS);
UserSession session = newAnonymousSession();
// feed the cache
assertThat(session.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
// change permissions without updating the cache
db.users().insertPermissionOnAnyone(GlobalPermission.SCAN);
assertThat(session.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
assertThat(session.hasPermission(GlobalPermission.SCAN)).isFalse();
}
@Test
public void test_hasChildProjectsPermission_for_logged_in_user() {
ProjectData project1 = db.components().insertPrivateProject();
ProjectData project2 = db.components().insertPrivateProject();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project1.getProjectDto());
ProjectData application = db.components().insertPrivateApplication();
db.components().addApplicationProject(application, project1);
// add computed project
db.components().insertComponent(newProjectCopy(project1.getMainBranchComponent(), application.getMainBranchComponent()));
UserSession session = newUserSession(user);
assertThat(session.hasChildProjectsPermission(UserRole.USER, application.getMainBranchComponent())).isTrue();
db.components().addApplicationProject(application, project2);
db.components().insertComponent(newProjectCopy(project2.getMainBranchComponent(), application.getMainBranchComponent()));
assertThat(session.hasChildProjectsPermission(UserRole.USER, application.getMainBranchComponent())).isFalse();
}
@Test
public void test_hasChildProjectsPermission_for_anonymous_user() {
ProjectData project = db.components().insertPrivateProject();
db.users().insertPermissionOnAnyone(UserRole.USER);
ProjectData application = db.components().insertPrivateApplication();
db.components().addApplicationProject(application.getProjectDto(), project.getProjectDto());
// add computed project
db.components().insertComponent(newProjectCopy(project.getMainBranchComponent(), application.getMainBranchComponent()));
UserSession session = newAnonymousSession();
assertThat(session.hasChildProjectsPermission(UserRole.USER, application.getProjectDto())).isFalse();
}
@Test
public void hasChildProjectsPermission_keeps_cache_of_permissions_of_anonymous_user() {
db.users().insertPermissionOnAnyone(UserRole.USER);
ProjectDto project = db.components().insertPublicProject().getProjectDto();
ProjectDto application = db.components().insertPublicApplication().getProjectDto();
db.components().addApplicationProject(application, project);
UserSession session = newAnonymousSession();
// feed the cache
assertThat(session.hasChildProjectsPermission(UserRole.USER, application)).isTrue();
// change privacy of the project without updating the cache
db.getDbClient().componentDao().setPrivateForBranchUuidWithoutAudit(db.getSession(), project.getUuid(), true);
assertThat(session.hasChildProjectsPermission(UserRole.USER, application)).isTrue();
}
@Test
public void test_hasPortfolioChildProjectsPermission_for_logged_in_user() {
ProjectData project1 = db.components().insertPublicProject();
ProjectData project2 = db.components().insertPrivateProject();
ProjectData project3 = db.components().insertPrivateProject();
ProjectData project4 = db.components().insertPrivateProject();
ProjectData project5 = db.components().insertPrivateProject();
UserDto user = db.users().insertUser();
UserSession session = newUserSession(user);
ComponentDto portfolio = db.components().insertPrivatePortfolio();
ComponentDto subPortfolio = db.components().insertSubView(portfolio);
// Add public project1 to private portfolio
db.components().addPortfolioProject(portfolio, project1.getProjectDto().getUuid());
db.components().insertComponent(newProjectCopy(project1.getMainBranchComponent(), portfolio));
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isTrue();
// Add private project2 with USER permissions to private portfolio
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project2.getProjectDto());
db.components().addPortfolioProject(portfolio, project2.getProjectDto().getUuid());
db.components().insertComponent(newProjectCopy(project2.getMainBranchComponent(), portfolio));
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isTrue();
// Add private project4 with USER permissions to sub-portfolio
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project4.getProjectDto());
db.components().addPortfolioProject(subPortfolio, project4.getProjectDto().getUuid());
db.components().insertComponent(newProjectCopy(project4.getMainBranchComponent(), subPortfolio));
db.components().addPortfolioReference(portfolio, subPortfolio.uuid());
// The predicate should work both on view and subview components
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isTrue();
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, subPortfolio)).isTrue();
// Add private project3 without permissions to private portfolio
db.components().addPortfolioProject(portfolio, project3.getProjectDto().getUuid());
db.components().insertComponent(newProjectCopy(project3.getMainBranchComponent(), portfolio));
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isFalse();
// Add private project5 without permissions to sub-portfolio
db.components().addPortfolioProject(subPortfolio, project5.getProjectDto().getUuid());
db.components().insertComponent(newProjectCopy(project5.getMainBranchComponent(), subPortfolio));
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isFalse();
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, subPortfolio)).isFalse();
}
@Test
public void test_hasPortfolioChildProjectsPermission_for_anonymous_user() {
ProjectData project = db.components().insertPrivateProject();
db.users().insertPermissionOnAnyone(UserRole.USER);
ComponentDto portfolio = db.components().insertPrivatePortfolio();
db.components().addPortfolioProject(portfolio, project.getProjectDto().getUuid());
// add computed project
db.components().insertComponent(newProjectCopy(project.getMainBranchComponent(), portfolio));
UserSession session = newAnonymousSession();
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isFalse();
}
@Test
public void hasPortfolioChildProjectsPermission_keeps_cache_of_permissions_of_anonymous_user() {
db.users().insertPermissionOnAnyone(UserRole.USER);
ProjectDto project = db.components().insertPublicProject().getProjectDto();
ComponentDto portfolio = db.components().insertPublicPortfolio();
db.components().addPortfolioProject(portfolio, project.getUuid());
UserSession session = newAnonymousSession();
// feed the cache
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isTrue();
// change privacy of the project without updating the cache
db.getDbClient().componentDao().setPrivateForBranchUuidWithoutAudit(db.getSession(), project.getUuid(), true);
assertThat(session.hasPortfolioChildProjectsPermission(UserRole.USER, portfolio)).isTrue();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_true_for_anonymous_user_for_permissions_USER_and_CODEVIEWER_on_public_projects_without_permissions() {
ProjectData publicProject = db.components().insertPublicProject();
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, publicProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, publicProject.getMainBranchComponent())).isTrue();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_true_for_anonymous_user_for_permissions_USER_and_CODEVIEWER_on_public_projects_with_global_permissions() {
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertEntityPermissionOnAnyone("p1", publicProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, publicProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, publicProject.getMainBranchComponent())).isTrue();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_true_for_anonymous_user_for_permissions_USER_and_CODEVIEWER_on_public_projects_with_group_permissions() {
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertEntityPermissionOnGroup(db.users().insertGroup(), "p1", publicProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, publicProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, publicProject.getMainBranchComponent())).isTrue();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_true_for_anonymous_user_for_permissions_USER_and_CODEVIEWER_on_public_projects_with_user_permissions() {
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertProjectPermissionOnUser(db.users().insertUser(), "p1", publicProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, publicProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, publicProject.getMainBranchComponent())).isTrue();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_authenticated_user_for_permissions_USER_and_CODEVIEWER_on_private_projects_without_permissions() {
UserDto user = db.users().insertUser();
ProjectData privateProject = db.components().insertPrivateProject();
ServerUserSession underTest = newUserSession(user);
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, privateProject.getMainBranchComponent())).isFalse();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, privateProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_authenticated_user_for_permissions_USER_and_CODEVIEWER_on_private_projects_with_group_permissions() {
UserDto user = db.users().insertUser();
ProjectData privateProject = db.components().insertPrivateProject();
db.users().insertEntityPermissionOnGroup(db.users().insertGroup(), "p1", privateProject.getProjectDto());
ServerUserSession underTest = newUserSession(user);
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, privateProject.getMainBranchComponent())).isFalse();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, privateProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_authenticated_user_for_permissions_USER_and_CODEVIEWER_on_private_projects_with_user_permissions() {
UserDto user = db.users().insertUser();
ProjectData privateProject = db.components().insertPrivateProject();
db.users().insertProjectPermissionOnUser(db.users().insertUser(), "p1", privateProject.getProjectDto());
ServerUserSession underTest = newUserSession(user);
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.USER, privateProject.getMainBranchComponent())).isFalse();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.CODEVIEWER, privateProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_true_for_anonymous_user_for_inserted_permissions_on_group_AnyOne_on_public_projects() {
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertEntityPermissionOnAnyone("p1", publicProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", publicProject.getMainBranchComponent())).isTrue();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_anonymous_user_for_inserted_permissions_on_group_on_public_projects() {
ProjectData publicProject = db.components().insertPublicProject();
GroupDto group = db.users().insertGroup();
db.users().insertEntityPermissionOnGroup(group, "p1", publicProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", publicProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_anonymous_user_for_inserted_permissions_on_group_on_private_projects() {
ProjectData privateProject = db.components().insertPrivateProject();
GroupDto group = db.users().insertGroup();
db.users().insertEntityPermissionOnGroup(group, "p1", privateProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", privateProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_anonymous_user_for_inserted_permissions_on_user_on_public_projects() {
UserDto user = db.users().insertUser();
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertProjectPermissionOnUser(user, "p1", publicProject.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", publicProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_returns_false_for_anonymous_user_for_inserted_permissions_on_user_on_private_projects() {
UserDto user = db.users().insertUser();
ProjectData project = db.components().insertPrivateProject();
db.users().insertProjectPermissionOnUser(user, "p1", project.getProjectDto());
ServerUserSession underTest = newAnonymousSession();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", project.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_keeps_cache_of_permissions_of_logged_in_user() {
UserDto user = db.users().insertUser();
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, publicProject.getProjectDto());
UserSession underTest = newUserSession(user);
// feed the cache
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.ADMIN, publicProject.getMainBranchComponent())).isTrue();
// change permissions without updating the cache
db.users().deletePermissionFromUser(publicProject.getProjectDto(), user, UserRole.ADMIN);
db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, publicProject.getProjectDto());
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.ADMIN, publicProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.ISSUE_ADMIN, publicProject.getMainBranchComponent())).isFalse();
}
@Test
public void hasComponentPermissionByDtoOrUuid_keeps_cache_of_permissions_of_anonymous_user() {
ProjectData publicProject = db.components().insertPublicProject();
db.users().insertEntityPermissionOnAnyone(UserRole.ADMIN, publicProject.getProjectDto());
UserSession underTest = newAnonymousSession();
// feed the cache
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.ADMIN, publicProject.getMainBranchComponent())).isTrue();
// change permissions without updating the cache
db.users().deleteProjectPermissionFromAnyone(publicProject.getProjectDto(), UserRole.ADMIN);
db.users().insertEntityPermissionOnAnyone(UserRole.ISSUE_ADMIN, publicProject.getProjectDto());
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.ADMIN, publicProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, UserRole.ISSUE_ADMIN, publicProject.getMainBranchComponent())).isFalse();
}
private boolean hasComponentPermissionByDtoOrUuid(UserSession underTest, String permission, ComponentDto component) {
boolean b1 = underTest.hasComponentPermission(permission, component);
boolean b2 = underTest.hasComponentUuidPermission(permission, component.uuid());
checkState(b1 == b2, "Different behaviors");
return b1;
}
@Test
public void keepAuthorizedComponents_returns_empty_list_if_no_permissions_are_granted() {
ProjectData publicProject = db.components().insertPublicProject();
ProjectData privateProject = db.components().insertPrivateProject();
UserSession underTest = newAnonymousSession();
assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, Arrays.asList(privateProject.getMainBranchComponent(), publicProject.getMainBranchComponent()))).isEmpty();
}
@Test
public void keepAuthorizedComponents_filters_components_with_granted_permissions_for_anonymous() {
ProjectData publicProject = db.components().insertPublicProject();
ProjectData privateProject = db.components().insertPrivateProject();
db.users().insertEntityPermissionOnAnyone(UserRole.ISSUE_ADMIN, publicProject.getProjectDto());
UserSession underTest = newAnonymousSession();
assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, Arrays.asList(privateProject.getMainBranchComponent(), publicProject.getMainBranchComponent()))).isEmpty();
assertThat(underTest.keepAuthorizedComponents(UserRole.ISSUE_ADMIN, Arrays.asList(privateProject.getMainBranchComponent(), publicProject.getMainBranchComponent())))
.containsExactly(publicProject.getMainBranchComponent());
}
@Test
public void keepAuthorizedComponents_on_branches() {
UserDto user = db.users().insertUser();
ProjectData privateProject = db.components().insertPrivateProject();
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, privateProject.getProjectDto());
ComponentDto privateBranchProject = db.components().insertProjectBranch(privateProject.getMainBranchComponent());
UserSession underTest = newUserSession(user);
assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, asList(privateProject.getMainBranchComponent(), privateBranchProject)))
.containsExactlyInAnyOrder(privateProject.getMainBranchComponent(), privateBranchProject);
}
@Test
public void keepAuthorizedComponents_filters_components_with_granted_permissions_for_logged_in_user() {
ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project3 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project4 = db.components().insertPrivateProject().getMainBranchComponent();
ProjectData project5 = db.components().insertPrivateProject();
ProjectData project6 = db.components().insertPrivateProject();
UserDto user = db.users().insertUser();
UserSession underTest = newUserSession(user);
ComponentDto portfolio = db.components().insertPrivatePortfolio();
db.users().insertProjectPermissionOnUser(user, UserRole.USER, portfolio);
ComponentDto subPortfolio = db.components().insertSubportfolio(portfolio);
db.users().insertProjectPermissionOnUser(user, UserRole.USER, subPortfolio);
ProjectData app = db.components().insertPrivateApplication();
db.users().insertProjectPermissionOnUser(user, UserRole.USER, app.getProjectDto());
ProjectData app2 = db.components().insertPrivateApplication();
// Add public project1 to private portfolio
db.components().addPortfolioProject(portfolio, project1);
var copyProject1 = db.components().insertComponent(newProjectCopy(project1, portfolio));
// Add private project2 with USER permissions to private portfolio
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project2);
db.components().addPortfolioProject(portfolio, project2);
var copyProject2 = db.components().insertComponent(newProjectCopy(project2, portfolio));
// Add private project4 with USER permissions to sub-portfolio
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project4);
db.components().addPortfolioProject(subPortfolio, project4);
var copyProject4 = db.components().insertComponent(newProjectCopy(project4, subPortfolio));
db.components().addPortfolioReference(portfolio, subPortfolio.uuid());
// Add private project3 without permissions to private portfolio
db.components().addPortfolioProject(portfolio, project3);
var copyProject3 = db.components().insertComponent(newProjectCopy(project3, portfolio));
// Add private project5 with USER permissions to app
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project5.getProjectDto());
db.components().addApplicationProject(app, project5);
var copyProject5 = db.components().insertComponent(newProjectCopy(project5, app));
db.components().addPortfolioReference(portfolio, app.getProjectDto().getUuid());
// Add private project6 to private app2
db.components().addApplicationProject(app2, project6);
var copyProject6 = db.components().insertComponent(newProjectCopy(project6, app2));
db.components().addPortfolioReference(portfolio, app2.getProjectDto().getUuid());
assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, List.of(portfolio))).isEmpty();
assertThat(underTest.keepAuthorizedComponents(UserRole.USER, List.of(portfolio))).containsExactly(portfolio);
assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, Arrays.asList(app.getMainBranchComponent(), subPortfolio, app2.getMainBranchComponent()))).isEmpty();
assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(app.getMainBranchComponent(), subPortfolio, app2.getMainBranchComponent()))).containsExactly(app.getMainBranchComponent(), subPortfolio);
assertThat(underTest.keepAuthorizedComponents(UserRole.ADMIN, Arrays.asList(project1, project2, project3, project4, project5.getMainBranchComponent(), project6.getMainBranchComponent()))).isEmpty();
assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(project1, project2, project3, project4, project5.getMainBranchComponent(), project6.getMainBranchComponent())))
.containsExactly(project1, project2, project4, project5.getMainBranchComponent());
assertThat(underTest.keepAuthorizedComponents(UserRole.USER, Arrays.asList(copyProject1, copyProject2, copyProject3, copyProject4, copyProject5, copyProject6)))
.containsExactly(copyProject1, copyProject2, copyProject4, copyProject5);
}
@Test
public void keepAuthorizedComponents_filters__files_with_granted_permissions_for_logged_in_user() {
ProjectData project1 = db.components().insertPrivateProject();
ProjectData project2 = db.components().insertPrivateProject();
UserDto user = db.users().insertUser();
UserSession underTest = newUserSession(user);
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project1.getProjectDto());
ComponentDto file1Project1 = db.components().insertFile(project1.getMainBranchDto());
ComponentDto file2Project1 = db.components().insertFile(project1.getMainBranchDto());
ComponentDto file1Project2 = db.components().insertFile(project2.getMainBranchDto());
assertThat(underTest.keepAuthorizedComponents(UserRole.USER, List.of(file1Project1, file2Project1, file1Project2))).containsExactly(file1Project1, file2Project1);
}
@Test
public void isSystemAdministrator_returns_false_if_org_feature_is_enabled_and_user_is_not_root() {
UserDto user = db.users().insertUser();
UserSession session = newUserSession(user);
assertThat(session.isSystemAdministrator()).isFalse();
}
@Test
public void isSystemAdministrator_returns_true_if_user_is_administrator() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER);
UserSession session = newUserSession(user);
assertThat(session.isSystemAdministrator()).isTrue();
}
@Test
public void isSystemAdministrator_returns_false_if_user_is_not_administrator() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.PROVISION_PROJECTS);
UserSession session = newUserSession(user);
assertThat(session.isSystemAdministrator()).isFalse();
}
@Test
public void keep_isSystemAdministrator_flag_in_cache() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER);
UserSession session = newUserSession(user);
session.checkIsSystemAdministrator();
db.getDbClient().userDao().deactivateUser(db.getSession(), user);
db.commit();
// should fail but succeeds because flag is kept in cache
session.checkIsSystemAdministrator();
}
@Test
public void checkIsSystemAdministrator_throws_ForbiddenException_if_not_system_administrator() {
UserDto user = db.users().insertUser();
UserSession session = newUserSession(user);
assertThatThrownBy(session::checkIsSystemAdministrator)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void hasComponentPermission_on_branch_checks_permissions_of_its_project() {
UserDto user = db.users().insertUser();
ProjectData privateProject = db.components().insertPrivateProject();
ComponentDto branch = db.components().insertProjectBranch(privateProject.getMainBranchComponent(), b -> b.setKey("feature/foo"));
ComponentDto fileInBranch = db.components().insertComponent(newChildComponent("fileUuid", branch, branch));
// permissions are defined on the project, not on the branch
db.users().insertProjectPermissionOnUser(user, "p1", privateProject.getProjectDto());
UserSession underTest = newUserSession(user);
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", privateProject.getMainBranchComponent())).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", branch)).isTrue();
assertThat(hasComponentPermissionByDtoOrUuid(underTest, "p1", fileInBranch)).isTrue();
}
@Test
public void keepAuthorizedProjects_shouldAcceptsPublicProjects_whenCalledWithPublicPermissionAndNoUser() {
ProjectData publicProject = db.components().insertPublicProject();
ProjectData privateProject = db.components().insertPrivateProject();
Set<ProjectDto> projectDto = Set.of(publicProject.getProjectDto(), privateProject.getProjectDto());
List<ProjectDto> projectDtos = newUserSession(null).keepAuthorizedEntities(UserRole.USER, projectDto);
assertThat(projectDtos).containsExactly(publicProject.getProjectDto());
}
@Test
public void keepAuthorizedProjects_shouldAcceptsPublicProjects_whenCalledWithPublicPermissionAndAnUser() {
UserDto userDto = db.users().insertUser();
ProjectData publicProject = db.components().insertPublicProject();
ProjectData privateProject = db.components().insertPrivateProject();
Set<ProjectDto> projectDto = Set.of(publicProject.getProjectDto(), privateProject.getProjectDto());
List<ProjectDto> projectDtos = newUserSession(userDto).keepAuthorizedEntities(UserRole.USER, projectDto);
assertThat(projectDtos).containsExactly(publicProject.getProjectDto());
}
@Test
public void keepAuthorizedProjects_shouldAcceptsOnlyPrivateProject_whenCalledWithGoodPermissionAndAnUser() {
String permission = "aNewPermission";
UserDto userDto = db.users().insertUser();
ProjectDto publicProject = db.components().insertPublicProject().getProjectDto();
ProjectDto privateProject = db.components().insertPrivateProject().getProjectDto();
db.users().insertProjectPermissionOnUser(userDto, permission, privateProject);
ProjectDto privateProjectWithoutPermission = db.components().insertPrivateProject().getProjectDto();
Set<ProjectDto> projectDto = Set.of(publicProject, privateProject, privateProjectWithoutPermission);
List<ProjectDto> projectDtos = newUserSession(userDto).keepAuthorizedEntities(permission, projectDto);
assertThat(projectDtos).containsExactly(privateProject);
}
@Test
public void keepAuthorizedProjects_shouldRejectPrivateAndPublicProject_whenCalledWithWrongPermissionAndNoUser() {
String permission = "aNewPermission";
UserDto userDto = db.users().insertUser();
ProjectDto publicProject = db.components().insertPublicProject().getProjectDto();
ProjectDto privateProject = db.components().insertPrivateProject().getProjectDto();
db.users().insertProjectPermissionOnUser(userDto, permission, privateProject);
ProjectDto privateProjectWithoutPermission = db.components().insertPrivateProject().getProjectDto();
Set<ProjectDto> projectDto = Set.of(publicProject, privateProject, privateProjectWithoutPermission);
List<ProjectDto> projectDtos = newUserSession(null).keepAuthorizedEntities(permission, projectDto);
assertThat(projectDtos).isEmpty();
}
private ServerUserSession newUserSession(@Nullable UserDto userDto) {
return new ServerUserSession(dbClient, userDto);
}
private ServerUserSession newAnonymousSession() {
return newUserSession(null);
}
private void assertThatForbiddenExceptionIsThrown(ThrowingCallable shouldRaiseThrowable) {
assertThatThrownBy(shouldRaiseThrowable)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
}
| 39,935 | 47.643118 | 216 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/TokenUserSessionIT.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.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.web.UserRole.SCAN;
import static org.sonar.db.user.TokenType.GLOBAL_ANALYSIS_TOKEN;
import static org.sonar.db.user.TokenType.PROJECT_ANALYSIS_TOKEN;
import static org.sonar.db.user.TokenType.USER_TOKEN;
public class TokenUserSessionIT {
@Rule
public final DbTester db = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = db.getDbClient();
@Test
public void token_can_be_retrieved_from_the_session() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, SCAN, project1);
TokenUserSession userSession = mockTokenUserSession(user);
assertThat(userSession.getUserToken()).isNotNull();
assertThat(userSession.getUserToken().getName()).isEqualTo("User Token");
assertThat(userSession.getUserToken().getUserUuid()).isEqualTo("userUid");
assertThat(userSession.getUserToken().getType()).isEqualTo("USER_TOKEN");
}
@Test
public void test_hasProjectsPermission_for_UserToken() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, SCAN, project1);
TokenUserSession userSession = mockTokenUserSession(user);
assertThat(userSession.hasEntityUuidPermission(SCAN, project1.getUuid())).isTrue();
assertThat(userSession.hasEntityUuidPermission(SCAN, project2.getUuid())).isFalse();
}
@Test
public void test_hasProjectsPermission_for_ProjecAnalysisToken() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, SCAN, project1);
db.users().insertProjectPermissionOnUser(user, SCAN, project2);
TokenUserSession userSession = mockProjectAnalysisTokenUserSession(user,project1);
assertThat(userSession.hasEntityUuidPermission(SCAN, project1.getUuid())).isTrue();
assertThat(userSession.hasEntityUuidPermission(SCAN, project2.getUuid())).isFalse();
}
@Test
public void test_hasProjectsPermission_for_ProjectAnalysisToken_with_global_permission() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
TokenUserSession userSession = mockProjectAnalysisTokenUserSession(user,project1);
assertThat(userSession.hasEntityUuidPermission(SCAN, project1.getUuid())).isTrue();
assertThat(userSession.hasEntityUuidPermission(SCAN, project2.getUuid())).isFalse();
}
@Test
public void test_hasGlobalPermission_for_UserToken() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
TokenUserSession userSession = mockTokenUserSession(user);
assertThat(userSession.hasPermission(GlobalPermission.SCAN)).isTrue();
}
@Test
public void test_hasGlobalPermission_for_ProjecAnalysisToken() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, SCAN, project1);
db.users().insertProjectPermissionOnUser(user, SCAN, project2);
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
TokenUserSession userSession = mockProjectAnalysisTokenUserSession(user,project1);
assertThat(userSession.hasPermission(GlobalPermission.SCAN)).isFalse();
}
@Test
public void test_hasGlobalPermission_for_GlobalAnalysisToken() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
TokenUserSession userSession = mockGlobalAnalysisTokenUserSession(user);
assertThat(userSession.hasEntityUuidPermission(SCAN, project1.getUuid())).isFalse();
assertThat(userSession.hasPermission(GlobalPermission.SCAN)).isTrue();
}
@Test
public void test_hasProvisionProjectsGlobalPermission_for_GlobalAnalysisToken_returnsTrueIfUserIsGranted() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.PROVISION_PROJECTS);
TokenUserSession userSession = mockGlobalAnalysisTokenUserSession(user);
assertThat(userSession.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isTrue();
}
@Test
public void test_hasProvisionProjectsGlobalPermission_for_GlobalAnalysisToken_returnsFalseIfUserIsNotGranted() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
TokenUserSession userSession = mockGlobalAnalysisTokenUserSession(user);
assertThat(userSession.hasPermission(GlobalPermission.PROVISION_PROJECTS)).isFalse();
}
@Test
public void test_hasAdministerGlobalPermission_for_GlobalAnalysisToken_returnsFalse() {
UserDto user = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER);
TokenUserSession userSession = mockGlobalAnalysisTokenUserSession(user);
assertThat(userSession.hasPermission(GlobalPermission.ADMINISTER)).isFalse();
}
private TokenUserSession mockTokenUserSession(UserDto userDto) {
return new TokenUserSession(dbClient, userDto, mockUserTokenDto());
}
private TokenUserSession mockProjectAnalysisTokenUserSession(UserDto userDto, ProjectDto projectDto) {
return new TokenUserSession(dbClient, userDto, mockProjectAnalysisTokenDto(projectDto));
}
private TokenUserSession mockGlobalAnalysisTokenUserSession(UserDto userDto) {
return new TokenUserSession(dbClient, userDto, mockGlobalAnalysisTokenDto());
}
private static UserTokenDto mockUserTokenDto() {
UserTokenDto userTokenDto = new UserTokenDto();
userTokenDto.setType(USER_TOKEN.name());
userTokenDto.setName("User Token");
userTokenDto.setUserUuid("userUid");
return userTokenDto;
}
private static UserTokenDto mockProjectAnalysisTokenDto(ProjectDto projectDto) {
UserTokenDto userTokenDto = new UserTokenDto();
userTokenDto.setType(PROJECT_ANALYSIS_TOKEN.name());
userTokenDto.setName("Project Analysis Token");
userTokenDto.setUserUuid("userUid");
userTokenDto.setProjectKey(projectDto.getKey());
userTokenDto.setProjectName(projectDto.getName());
userTokenDto.setProjectUuid(projectDto.getUuid());
return userTokenDto;
}
private static UserTokenDto mockGlobalAnalysisTokenDto() {
UserTokenDto userTokenDto = new UserTokenDto();
userTokenDto.setType(GLOBAL_ANALYSIS_TOKEN.name());
userTokenDto.setName("Global Analysis Token");
userTokenDto.setUserUuid("userUid");
return userTokenDto;
}
}
| 8,566 | 37.764706 | 114 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterCreateIT.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.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.platform.NewUserHandler;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.authentication.CredentialsLocalAuthentication.HashMethod;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.db.user.UserTesting.newLocalUser;
import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY;
@RunWith(DataProviderRunner.class)
public class UserUpdaterCreateIT {
private static final String DEFAULT_LOGIN = "marius";
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public EsTester es = EsTester.create();
@Rule
public DbTester db = DbTester.create(system2);
private final DbClient dbClient = db.getDbClient();
private final NewUserNotifier newUserNotifier = mock(NewUserNotifier.class);
private final ArgumentCaptor<NewUserHandler.Context> newUserHandler = ArgumentCaptor.forClass(NewUserHandler.Context.class);
private final DbSession session = db.getSession();
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final UserUpdater underTest = new UserUpdater(newUserNotifier, dbClient,
new DefaultGroupFinder(dbClient), settings.asConfig(), null, localAuthentication);
@Test
public void create_user() {
createDefaultGroup();
UserDto dto = underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setEmail("user@mail.com")
.setPassword("PASSWORD")
.setScmAccounts(ImmutableList.of("u1", "u_1", "User 1"))
.build(), u -> {
});
assertThat(dto.getUuid()).isNotNull();
assertThat(dto.getLogin()).isEqualTo("user");
assertThat(dto.getName()).isEqualTo("User");
assertThat(dto.getEmail()).isEqualTo("user@mail.com");
assertThat(dto.getSortedScmAccounts()).containsOnly("u1", "u_1", "User 1");
assertThat(dto.isActive()).isTrue();
assertThat(dto.isLocal()).isTrue();
assertThat(dto.getSalt()).isNotNull();
assertThat(dto.getHashMethod()).isEqualTo(HashMethod.PBKDF2.name());
assertThat(dto.getCryptedPassword()).isNotNull();
assertThat(dto.getCreatedAt())
.isPositive()
.isEqualTo(dto.getUpdatedAt());
assertThat(dbClient.userDao().selectByLogin(session, "user").getUuid()).isEqualTo(dto.getUuid());
}
@Test
public void create_user_with_minimum_fields() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("us")
.setName("User")
.build(), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, "us");
assertThat(dto.getUuid()).isNotNull();
assertThat(dto.getLogin()).isEqualTo("us");
assertThat(dto.getName()).isEqualTo("User");
assertThat(dto.getEmail()).isNull();
assertThat(dto.getSortedScmAccounts()).isEmpty();
assertThat(dto.isActive()).isTrue();
}
@Test
public void create_user_generates_unique_login_no_login_provided() {
createDefaultGroup();
UserDto user = underTest.createAndCommit(session, NewUser.builder()
.setName("John Doe")
.build(), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, user.getLogin());
assertThat(dto.getLogin()).startsWith("john-doe");
assertThat(dto.getName()).isEqualTo("John Doe");
}
@Test
public void create_user_generates_unique_login_when_login_is_empty() {
createDefaultGroup();
UserDto user = underTest.createAndCommit(session, NewUser.builder()
.setLogin("")
.setName("John Doe")
.build(), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, user.getLogin());
assertThat(dto.getLogin()).startsWith("john-doe");
assertThat(dto.getName()).isEqualTo("John Doe");
}
@Test
public void create_user_with_sq_authority_when_no_authority_set() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setPassword("password")
.build(), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, "user");
assertThat(dto.getExternalLogin()).isEqualTo("user");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("sonarqube");
assertThat(dto.isLocal()).isTrue();
}
@Test
public void create_user_with_identity_provider() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setExternalIdentity(new ExternalIdentity("github", "github-user", "ABCD"))
.build(), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, "user");
assertThat(dto.isLocal()).isFalse();
assertThat(dto.getExternalId()).isEqualTo("ABCD");
assertThat(dto.getExternalLogin()).isEqualTo("github-user");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("github");
assertThat(dto.getCryptedPassword()).isNull();
assertThat(dto.getSalt()).isNull();
}
@Test
public void create_user_with_sonarqube_external_identity() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setExternalIdentity(new ExternalIdentity(SQ_AUTHORITY, "user", "user"))
.build(), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, "user");
assertThat(dto).isNotNull();
assertThat(dto.isLocal()).isFalse();
assertThat(dto.getExternalId()).isEqualTo("user");
assertThat(dto.getExternalLogin()).isEqualTo("user");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("sonarqube");
assertThat(dto.getCryptedPassword()).isNull();
assertThat(dto.getSalt()).isNull();
}
@Test
public void create_user_with_scm_accounts_containing_blank_or_null_entries() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setPassword("password")
.setScmAccounts(asList("u1", "", null))
.build(), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, "user").getSortedScmAccounts()).containsOnly("u1");
}
@Test
public void create_user_with_scm_accounts_containing_one_blank_entry() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setPassword("password")
.setScmAccounts(List.of(""))
.build(), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, "user").getSortedScmAccounts()).isEmpty();
}
@Test
public void create_user_with_scm_accounts_containing_duplications() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setPassword("password")
.setScmAccounts(asList("u1", "u1"))
.build(), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, "user").getSortedScmAccounts()).containsOnly("u1");
}
@Test
@UseDataProvider("loginWithAuthorizedSuffix")
public void createAndCommit_should_createUserWithoutException_when_loginHasAuthorizedSuffix(String login) {
createDefaultGroup();
NewUser user = NewUser.builder().setLogin(login).setName("aName").build();
underTest.createAndCommit(session, user, u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, login);
assertNotNull(dto);
}
@DataProvider
public static Object[][] loginWithAuthorizedSuffix() {
return new Object[][] {
{"1Login"},
{"AnotherLogin"},
{"alogin"},
{"_technicalUser"},
{"_.toto"}
};
}
@Test
public void fail_to_create_user_with_invalid_characters_in_login() {
NewUser newUser = newUserBuilder().setLogin("_amarius/").build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login should contain only letters, numbers, and .-_@");
}
@Test
public void fail_to_create_user_with_space_in_login() {
NewUser newUser = newUserBuilder().setLogin("mari us").build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login should contain only letters, numbers, and .-_@");
}
@Test
public void fail_to_create_user_with_too_short_login() {
NewUser newUser = newUserBuilder().setLogin("m").build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login is too short (minimum is 2 characters)");
}
@Test
@UseDataProvider("loginWithUnauthorizedSuffix")
public void createAndCommit_should_ThrowBadRequestExceptionWithSpecificMessage_when_loginHasUnauthorizedSuffix(String login) {
NewUser newUser = NewUser.builder().setLogin(login).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login should start with _ or alphanumeric.");
}
@DataProvider
public static Object[][] loginWithUnauthorizedSuffix() {
return new Object[][] {
{".Toto"},
{"@Toto"},
{"-Tutu"},
{" Tutut"},
{"#nesp"},
};
}
@Test
public void create_user_login_contains_underscore() {
createDefaultGroup();
String login = "name_with_underscores";
NewUser newUser = newUserBuilder().setLogin(login).build();
underTest.createAndCommit(session, newUser, u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, login)).isNotNull();
}
@Test
public void fail_to_create_user_with_too_long_login() {
NewUser newUser = newUserBuilder().setLogin(randomAlphabetic(256)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login is too long (maximum is 255 characters)");
}
@Test
public void fail_to_create_user_with_missing_name() {
NewUser newUser = NewUser.builder()
.setLogin(DEFAULT_LOGIN)
.setEmail("marius@mail.com")
.setPassword("password")
.build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Name can't be empty");
}
@Test
public void fail_to_create_user_with_too_long_name() {
NewUser newUser = newUserBuilder().setName(randomAlphabetic(201)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Name is too long (maximum is 200 characters)");
}
@Test
public void fail_to_create_user_with_too_long_email() {
NewUser newUser = newUserBuilder().setEmail(randomAlphabetic(101)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Email is too long (maximum is 100 characters)");
}
@Test
public void fail_to_create_user_with_many_errors() {
NewUser newUser = NewUser.builder()
.setLogin("")
.setName("")
.setEmail("marius@mail.com")
.setPassword("")
.build();
try {
underTest.createAndCommit(session, newUser, u -> {
});
fail();
} catch (BadRequestException e) {
assertThat(e.errors()).containsExactlyInAnyOrder("Name can't be empty", "Password can't be empty");
}
}
@Test
public void fail_to_create_user_when_scm_account_is_already_used() {
db.users().insertUser(newLocalUser("john", "John", null).setScmAccounts(singletonList("jo")));
NewUser newUser = newUserBuilder().setScmAccounts(singletonList("jo")).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("The scm account 'jo' is already used by user(s) : 'John (john)'");
}
@Test
public void fail_to_create_user_when_scm_account_is_already_used_by_many_users() {
db.users().insertUser(newLocalUser("john", "John", null).setScmAccounts(singletonList("john@email.com")));
db.users().insertUser(newLocalUser("technical-account", "Technical account", null).setScmAccounts(singletonList("john@email.com")));
NewUser newUser = newUserBuilder().setScmAccounts(List.of("john@email.com")).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("The scm account 'john@email.com' is already used by user(s) : 'John (john), Technical account (technical-account)'");
}
@Test
public void fail_to_create_user_when_scm_account_is_user_login() {
NewUser newUser = newUserBuilder().setLogin(DEFAULT_LOGIN).setScmAccounts(singletonList(DEFAULT_LOGIN)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login and email are automatically considered as SCM accounts");
}
@Test
public void fail_to_create_user_when_scm_account_is_user_email() {
NewUser newUser = newUserBuilder().setEmail("marius2@mail.com").setScmAccounts(singletonList("marius2@mail.com")).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login and email are automatically considered as SCM accounts");
}
@Test
public void fail_to_create_user_when_login_already_exists() {
createDefaultGroup();
UserDto existingUser = db.users().insertUser(u -> u.setLogin("existing_login"));
NewUser newUser = newUserBuilder().setLogin(existingUser.getLogin()).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A user with login 'existing_login' already exists");
}
@Test
public void fail_to_create_user_when_external_id_and_external_provider_already_exists() {
createDefaultGroup();
UserDto existingUser = db.users().insertUser(u -> u.setExternalId("existing_external_id").setExternalIdentityProvider("existing_external_provider"));
NewUser newUser = NewUser.builder()
.setLogin("new_login")
.setName("User")
.setExternalIdentity(new ExternalIdentity(existingUser.getExternalIdentityProvider(), existingUser.getExternalLogin(), existingUser.getExternalId()))
.build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists");
}
@Test
public void notify_new_user() {
createDefaultGroup();
underTest.createAndCommit(session, NewUser.builder()
.setLogin("user")
.setName("User")
.setEmail("user@mail.com")
.setPassword("password")
.setScmAccounts(asList("u1", "u_1"))
.build(), u -> {
});
verify(newUserNotifier).onNewUser(newUserHandler.capture());
assertThat(newUserHandler.getValue().getLogin()).isEqualTo("user");
assertThat(newUserHandler.getValue().getName()).isEqualTo("User");
assertThat(newUserHandler.getValue().getEmail()).isEqualTo("user@mail.com");
}
@Test
public void associate_default_group_when_creating_user() {
GroupDto defaultGroup = createDefaultGroup();
NewUser newUser = newUserBuilder().build();
underTest.createAndCommit(session, newUser, u -> {
});
Multimap<String, String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, singletonList(newUser.login()));
assertThat(groups.get(newUser.login())).containsOnly(defaultGroup.getName());
}
@Test
public void fail_to_associate_default_group_when_default_group_does_not_exist() {
NewUser newUser = newUserBuilder().setScmAccounts(asList("u1", "u_1")).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Default group cannot be found");
}
private GroupDto createDefaultGroup() {
return db.users().insertDefaultGroup();
}
private NewUser.Builder newUserBuilder() {
return NewUser.builder()
.setLogin(DEFAULT_LOGIN)
.setName("Marius")
.setEmail("marius@mail.com")
.setPassword("password");
}
}
| 19,019 | 34.954631 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterReactivateIT.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.collect.Multimap;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.GroupTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.authentication.CredentialsLocalAuthentication.HashMethod;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
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.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class UserUpdaterReactivateIT {
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
private final DbClient dbClient = db.getDbClient();
private final NewUserNotifier newUserNotifier = mock(NewUserNotifier.class);
private final DbSession session = db.getSession();
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final UserUpdater underTest = new UserUpdater(newUserNotifier, dbClient,
new DefaultGroupFinder(dbClient),
settings.asConfig(), auditPersister, localAuthentication);
@Test
public void reactivate_user() {
UserDto user = db.users().insertUser(u -> u.setActive(false));
createDefaultGroup();
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin("marius")
.setName("Marius2")
.setEmail("marius2@mail.com")
.setPassword("password2")
.build(),
u -> {
});
UserDto reloaded = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(reloaded.isActive()).isTrue();
assertThat(reloaded.getLogin()).isEqualTo("marius");
assertThat(reloaded.getName()).isEqualTo("Marius2");
assertThat(reloaded.getEmail()).isEqualTo("marius2@mail.com");
assertThat(reloaded.getSortedScmAccounts()).isEmpty();
assertThat(reloaded.isLocal()).isTrue();
assertThat(reloaded.getSalt()).isNotNull();
assertThat(reloaded.getHashMethod()).isEqualTo(HashMethod.PBKDF2.name());
assertThat(reloaded.getCryptedPassword()).isNotNull().isNotEqualTo("650d2261c98361e2f67f90ce5c65a95e7d8ea2fg");
assertThat(reloaded.getCreatedAt()).isEqualTo(user.getCreatedAt());
assertThat(reloaded.getUpdatedAt()).isGreaterThan(user.getCreatedAt());
verify(auditPersister, times(1)).updateUserPassword(any(), any());
}
@Test
public void reactivate_user_without_providing_login() {
UserDto user = db.users().insertUser(u -> u.setActive(false));
createDefaultGroup();
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setName("Marius2")
.setEmail("marius2@mail.com")
.setPassword("password2")
.build(),
u -> {
});
UserDto reloaded = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(reloaded.isActive()).isTrue();
assertThat(reloaded.getLogin()).isEqualTo(user.getLogin());
}
@Test
public void reactivate_user_not_having_password() {
UserDto user = db.users().insertDisabledUser(u -> u.setSalt(null).setCryptedPassword(null));
createDefaultGroup();
UserDto dto = underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(user.getLogin())
.setName(user.getName())
.build(),
u -> {
});
assertThat(dto.isActive()).isTrue();
assertThat(dto.getName()).isEqualTo(user.getName());
assertThat(dto.getSortedScmAccounts()).isEmpty();
assertThat(dto.getSalt()).isNull();
assertThat(dto.getCryptedPassword()).isNull();
assertThat(dto.getCreatedAt()).isEqualTo(user.getCreatedAt());
assertThat(dto.getUpdatedAt()).isGreaterThan(user.getCreatedAt());
verify(auditPersister, never()).updateUserPassword(any(), any());
}
@Test
public void reactivate_user_with_external_provider() {
UserDto user = db.users().insertDisabledUser(u -> u.setLocal(true));
createDefaultGroup();
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(user.getLogin())
.setName(user.getName())
.setExternalIdentity(new ExternalIdentity("github", "john", "ABCD"))
.build(), u -> {
});
session.commit();
UserDto dto = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(dto.isLocal()).isFalse();
assertThat(dto.getExternalId()).isEqualTo("ABCD");
assertThat(dto.getExternalLogin()).isEqualTo("john");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("github");
}
@Test
public void reactivate_user_using_same_external_info_but_was_local() {
UserDto user = db.users().insertDisabledUser(u -> u.setLocal(true)
.setExternalId("ABCD")
.setExternalLogin("john")
.setExternalIdentityProvider("github"));
createDefaultGroup();
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(user.getLogin())
.setName(user.getName())
.setExternalIdentity(new ExternalIdentity("github", "john", "ABCD"))
.build(), u -> {
});
session.commit();
UserDto dto = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(dto.isLocal()).isFalse();
assertThat(dto.getExternalId()).isEqualTo("ABCD");
assertThat(dto.getExternalLogin()).isEqualTo("john");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("github");
}
@Test
public void reactivate_user_with_local_provider() {
UserDto user = db.users().insertDisabledUser(u -> u.setLocal(false)
.setExternalId("ABCD")
.setExternalLogin("john")
.setExternalIdentityProvider("github"));
createDefaultGroup();
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(user.getLogin())
.setName(user.getName())
.build(), u -> {
});
session.commit();
UserDto dto = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(dto.isLocal()).isTrue();
assertThat(dto.getExternalId()).isEqualTo(user.getLogin());
assertThat(dto.getExternalLogin()).isEqualTo(user.getLogin());
assertThat(dto.getExternalIdentityProvider()).isEqualTo("sonarqube");
}
@Test
public void fail_to_reactivate_user_if_active() {
UserDto user = db.users().insertUser();
createDefaultGroup();
assertThatThrownBy(() -> {
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(user.getLogin())
.setName(user.getName())
.build(), u -> {
});
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("An active user with login '%s' already exists", user.getLogin()));
}
@Test
public void associate_default_groups_when_reactivating_user() {
UserDto userDto = db.users().insertDisabledUser();
GroupDto groupDto = db.users().insertGroup(GroupTesting.newGroupDto().setName("sonar-devs"));
db.users().insertMember(groupDto, userDto);
GroupDto defaultGroup = createDefaultGroup();
underTest.reactivateAndCommit(db.getSession(), userDto, NewUser.builder()
.setLogin(userDto.getLogin())
.setName(userDto.getName())
.build(), u -> {
});
session.commit();
Multimap<String, String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, singletonList(userDto.getLogin()));
assertThat(groups.get(userDto.getLogin()).stream().anyMatch(g -> g.equals(defaultGroup.getName()))).isTrue();
}
@Test
public void fail_to_reactivate_user_when_login_already_exists() {
createDefaultGroup();
UserDto user = db.users().insertUser(u -> u.setActive(false));
UserDto existingUser = db.users().insertUser(u -> u.setLogin("existing_login"));
assertThatThrownBy(() -> {
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(existingUser.getLogin())
.setName("Marius2")
.setPassword("password2")
.build(),
u -> {
});
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A user with login 'existing_login' already exists");
}
@Test
public void fail_to_reactivate_user_when_external_id_and_external_provider_already_exists() {
createDefaultGroup();
UserDto user = db.users().insertUser(u -> u.setActive(false));
UserDto existingUser = db.users().insertUser(u -> u.setExternalId("existing_external_id").setExternalIdentityProvider("existing_external_provider"));
assertThatThrownBy(() -> {
underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder()
.setLogin(user.getLogin())
.setName("Marius2")
.setExternalIdentity(new ExternalIdentity(existingUser.getExternalIdentityProvider(), existingUser.getExternalLogin(), existingUser.getExternalId()))
.build(),
u -> {
});
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists");
}
private GroupDto createDefaultGroup() {
return db.users().insertDefaultGroup();
}
}
| 10,858 | 38.202166 | 159 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterUpdateIT.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.collect.Multimap;
import java.util.function.Consumer;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.sonar.api.CoreProperties.DEFAULT_ISSUE_ASSIGNEE;
import static org.sonar.db.user.UserTesting.newExternalUser;
import static org.sonar.db.user.UserTesting.newLocalUser;
import static org.sonar.db.user.UserTesting.newUserDto;
public class UserUpdaterUpdateIT {
private static final String DEFAULT_LOGIN = "marius";
private static final Consumer<UserDto> EMPTY_USER_CONSUMER = userDto -> {
};
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
private final DbClient dbClient = db.getDbClient();
private final NewUserNotifier newUserNotifier = mock(NewUserNotifier.class);
private final DbSession session = db.getSession();
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final UserUpdater underTest = new UserUpdater(newUserNotifier, dbClient,
new DefaultGroupFinder(dbClient), settings.asConfig(), auditPersister, localAuthentication);
@Test
public void update_user_without_password() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@email.com")
.setScmAccounts(asList("ma", "marius33")));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2")
.setEmail("marius2@mail.com")
.setScmAccounts(singletonList("ma2")), u -> {
});
UserDto updatedUser = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(updatedUser.isActive()).isTrue();
assertThat(updatedUser.getName()).isEqualTo("Marius2");
assertThat(updatedUser.getEmail()).isEqualTo("marius2@mail.com");
assertThat(updatedUser.getSortedScmAccounts()).containsOnly("ma2");
assertThat(updatedUser.getCreatedAt()).isEqualTo(user.getCreatedAt());
assertThat(updatedUser.getUpdatedAt()).isGreaterThan(user.getCreatedAt());
verify(auditPersister, never()).updateUserPassword(any(), any());
}
@Test
public void update_user_external_identity_when_user_was_not_local() {
UserDto user = db.users().insertUser(newExternalUser(DEFAULT_LOGIN, "Marius", "marius@email.com"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2")
.setEmail("marius2@email.com")
.setExternalIdentity(new ExternalIdentity("github", "john", "ABCD")), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getExternalId()).isEqualTo("ABCD");
assertThat(dto.getExternalLogin()).isEqualTo("john");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("github");
assertThat(dto.getUpdatedAt()).isGreaterThan(user.getCreatedAt());
}
@Test
public void update_user_external_identity_when_user_was_local() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@email.com"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2")
.setEmail("marius2@email.com")
.setExternalIdentity(new ExternalIdentity("github", "john", "ABCD")), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getExternalId()).isEqualTo("ABCD");
assertThat(dto.getExternalLogin()).isEqualTo("john");
assertThat(dto.getExternalIdentityProvider()).isEqualTo("github");
// Password must be removed
assertThat(dto.getCryptedPassword()).isNull();
assertThat(dto.getSalt()).isNull();
assertThat(dto.getUpdatedAt()).isGreaterThan(user.getCreatedAt());
}
@Test
public void update_user_with_scm_accounts_containing_blank_entry() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33")));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2")
.setEmail("marius2@mail.com")
.setPassword("password2")
.setScmAccounts(asList("ma2", "", null)), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getSortedScmAccounts()).containsOnly("ma2");
verify(auditPersister, times(1)).updateUserPassword(any(), any());
}
@Test
public void update_only_login_of_local_account() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setLogin("new_login"), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN)).isNull();
UserDto userReloaded = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(userReloaded.getLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalIdentityProvider()).isEqualTo("sonarqube");
assertThat(userReloaded.getExternalLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalId()).isEqualTo("new_login");
// Following fields has not changed
assertThat(userReloaded.isLocal()).isTrue();
assertThat(userReloaded.getName()).isEqualTo(user.getName());
assertThat(userReloaded.getEmail()).isEqualTo(user.getEmail());
assertThat(userReloaded.getSortedScmAccounts()).containsAll(user.getSortedScmAccounts());
assertThat(userReloaded.getSalt()).isEqualTo(user.getSalt());
assertThat(userReloaded.getCryptedPassword()).isEqualTo(user.getCryptedPassword());
}
@Test
public void update_only_login_of_external_account() {
UserDto user = db.users().insertUser(newExternalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setLogin("new_login"), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN)).isNull();
UserDto userReloaded = dbClient.userDao().selectByUuid(session, user.getUuid());
assertThat(userReloaded.getLogin()).isEqualTo("new_login");
// Following fields has not changed
assertThat(userReloaded.isLocal()).isFalse();
assertThat(userReloaded.getExternalLogin()).isEqualTo(user.getExternalLogin());
assertThat(userReloaded.getExternalId()).isEqualTo(user.getExternalId());
assertThat(userReloaded.getName()).isEqualTo(user.getName());
assertThat(userReloaded.getEmail()).isEqualTo(user.getEmail());
assertThat(userReloaded.getSortedScmAccounts()).containsAll(user.getSortedScmAccounts());
assertThat(userReloaded.getSalt()).isEqualTo(user.getSalt());
assertThat(userReloaded.getCryptedPassword()).isEqualTo(user.getCryptedPassword());
}
@Test
public void update_default_assignee_when_updating_login() {
createDefaultGroup();
UserDto oldUser = db.users().insertUser();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto anotherProject = db.components().insertPrivateProject().getMainBranchComponent();
db.properties().insertProperties(oldUser.getLogin(), project1.getKey(), project1.name(), project1.qualifier(),
new PropertyDto().setKey(DEFAULT_ISSUE_ASSIGNEE).setValue(oldUser.getLogin()),
new PropertyDto().setKey(DEFAULT_ISSUE_ASSIGNEE).setValue(oldUser.getLogin()).setEntityUuid(project1.uuid()));
db.properties().insertProperties(oldUser.getLogin(), project2.getKey(), project2.name(), project2.qualifier(),
new PropertyDto().setKey(DEFAULT_ISSUE_ASSIGNEE).setValue(oldUser.getLogin()).setEntityUuid(project2.uuid()));
db.properties().insertProperties(oldUser.getLogin(), anotherProject.getKey(), anotherProject.name(), anotherProject.qualifier(),
new PropertyDto().setKey(DEFAULT_ISSUE_ASSIGNEE).setValue("another login").setEntityUuid(anotherProject.uuid()));
underTest.updateAndCommit(session, oldUser, new UpdateUser()
.setLogin("new_login"), u -> {
});
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setKey(DEFAULT_ISSUE_ASSIGNEE).build(), db.getSession()))
.extracting(PropertyDto::getValue, PropertyDto::getEntityUuid)
.containsOnly(
tuple("new_login", null),
tuple("new_login", project1.uuid()),
tuple("new_login", project2.uuid()),
tuple("another login", anotherProject.uuid()));
}
@Test
public void update_only_user_name() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33"))
.setSalt("salt")
.setCryptedPassword("crypted password"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2"), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getName()).isEqualTo("Marius2");
// Following fields has not changed
assertThat(dto.getEmail()).isEqualTo("marius@lesbronzes.fr");
assertThat(dto.getSortedScmAccounts()).containsOnly("ma", "marius33");
assertThat(dto.getSalt()).isEqualTo("salt");
assertThat(dto.getCryptedPassword()).isEqualTo("crypted password");
}
@Test
public void update_only_user_email() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33"))
.setSalt("salt")
.setCryptedPassword("crypted password"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setEmail("marius2@mail.com"), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getEmail()).isEqualTo("marius2@mail.com");
// Following fields has not changed
assertThat(dto.getName()).isEqualTo("Marius");
assertThat(dto.getSortedScmAccounts()).containsOnly("ma", "marius33");
assertThat(dto.getSalt()).isEqualTo("salt");
assertThat(dto.getCryptedPassword()).isEqualTo("crypted password");
}
@Test
public void update_only_scm_accounts() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33"))
.setSalt("salt")
.setCryptedPassword("crypted password"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setScmAccounts(asList("ma2")), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getSortedScmAccounts()).containsOnly("ma2");
// Following fields has not changed
assertThat(dto.getName()).isEqualTo("Marius");
assertThat(dto.getEmail()).isEqualTo("marius@lesbronzes.fr");
assertThat(dto.getSalt()).isEqualTo("salt");
assertThat(dto.getCryptedPassword()).isEqualTo("crypted password");
}
@Test
public void update_scm_accounts_with_same_values() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33")));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setScmAccounts(asList("ma", "marius33")), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getSortedScmAccounts()).containsOnly("ma", "marius33");
}
@Test
public void remove_scm_accounts() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33")));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setScmAccounts(null), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getSortedScmAccounts()).isEmpty();
}
@Test
public void update_only_user_password() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33"))
.setSalt("salt")
.setCryptedPassword("crypted password"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setPassword("password2"), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getSalt()).isNotEqualTo("salt");
assertThat(dto.getCryptedPassword()).isNotEqualTo("crypted password");
// Following fields has not changed
assertThat(dto.getName()).isEqualTo("Marius");
assertThat(dto.getSortedScmAccounts()).containsOnly("ma", "marius33");
assertThat(dto.getEmail()).isEqualTo("marius@lesbronzes.fr");
}
@Test
public void update_user_password_set_reset_password_flag_to_false() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr")
.setScmAccounts(asList("ma", "marius33"))
.setSalt("salt")
.setResetPassword(true)
.setCryptedPassword("crypted password"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setPassword("password2"), u -> {
});
UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN);
assertThat(dto.getSalt()).isNotEqualTo("salt");
assertThat(dto.getCryptedPassword()).isNotEqualTo("crypted password");
assertThat(dto.isResetPassword()).isFalse();
// Following fields has not changed
assertThat(dto.getName()).isEqualTo("Marius");
assertThat(dto.getSortedScmAccounts()).containsOnly("ma", "marius33");
assertThat(dto.getEmail()).isEqualTo("marius@lesbronzes.fr");
}
@Test
public void update_only_external_id() {
UserDto user = db.users().insertUser(newExternalUser(DEFAULT_LOGIN, "Marius", "marius@email.com")
.setExternalId("1234")
.setExternalLogin("john.smith")
.setExternalIdentityProvider("github"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser().setExternalIdentity(new ExternalIdentity("github", "john.smith", "ABCD")), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN))
.extracting(UserDto::getExternalId)
.isEqualTo("ABCD");
}
@Test
public void update_only_external_login() {
UserDto user = db.users().insertUser(newExternalUser(DEFAULT_LOGIN, "Marius", "marius@email.com")
.setExternalId("ABCD")
.setExternalLogin("john")
.setExternalIdentityProvider("github"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser().setExternalIdentity(new ExternalIdentity("github", "john.smith", "ABCD")), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN))
.extracting(UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.containsOnly("john.smith", "github");
}
@Test
public void update_only_external_identity_provider() {
UserDto user = db.users().insertUser(newExternalUser(DEFAULT_LOGIN, "Marius", "marius@email.com")
.setExternalId("ABCD")
.setExternalLogin("john")
.setExternalIdentityProvider("github"));
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser().setExternalIdentity(new ExternalIdentity("bitbucket", "john", "ABCD")), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN))
.extracting(UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.containsOnly("john", "bitbucket");
}
@Test
public void does_not_update_user_when_no_change() {
UserDto user = newExternalUser(DEFAULT_LOGIN, "Marius", "marius@email.com")
.setScmAccounts(asList("ma1", "ma2"));
db.users().insertUser(user);
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName(user.getName())
.setEmail(user.getEmail())
.setScmAccounts(user.getSortedScmAccounts())
.setExternalIdentity(new ExternalIdentity(user.getExternalIdentityProvider(), user.getExternalLogin(), user.getExternalId())), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN).getUpdatedAt()).isEqualTo(user.getUpdatedAt());
}
@Test
public void does_not_update_user_when_no_change_and_scm_account_reordered() {
UserDto user = newExternalUser(DEFAULT_LOGIN, "Marius", "marius@email.com")
.setScmAccounts(asList("ma1", "ma2"));
db.users().insertUser(user);
createDefaultGroup();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName(user.getName())
.setEmail(user.getEmail())
.setScmAccounts(asList("ma2", "ma1"))
.setExternalIdentity(new ExternalIdentity(user.getExternalIdentityProvider(), user.getExternalLogin(), user.getExternalId())), u -> {
});
assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN).getUpdatedAt()).isEqualTo(user.getUpdatedAt());
}
@Test
public void fail_to_set_null_password_when_local_user() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@email.com"));
createDefaultGroup();
UpdateUser updateUser = new UpdateUser().setPassword(null);
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Password can't be empty");
}
@Test
public void fail_to_update_password_when_user_is_not_local() {
UserDto user = db.users().insertUser(newUserDto()
.setLogin(DEFAULT_LOGIN)
.setLocal(false));
createDefaultGroup();
UpdateUser updateUser = new UpdateUser().setPassword("password2");
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Password cannot be changed when external authentication is used");
}
@Test
public void not_associate_default_group_when_updating_user() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@email.com"));
GroupDto defaultGroup = createDefaultGroup();
// Existing user, he has no group, and should not be associated to the default one
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2")
.setEmail("marius2@mail.com")
.setPassword("password2")
.setScmAccounts(asList("ma2")), u -> {
});
Multimap<String, String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN));
assertThat(groups.get(DEFAULT_LOGIN).stream().anyMatch(g -> g.equals(defaultGroup.getName()))).isFalse();
}
@Test
public void not_associate_default_group_when_updating_user_if_already_existing() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@email.com"));
GroupDto defaultGroup = createDefaultGroup();
db.users().insertMember(defaultGroup, user);
// User is already associate to the default group
Multimap<String, String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN));
assertThat(groups.get(DEFAULT_LOGIN).stream().anyMatch(g -> g.equals(defaultGroup.getName()))).as("Current user groups : %s", groups.get(defaultGroup.getName())).isTrue();
underTest.updateAndCommit(session, user, new UpdateUser()
.setName("Marius2")
.setEmail("marius2@mail.com")
.setPassword("password2")
.setScmAccounts(asList("ma2")), u -> {
});
// Nothing as changed
groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN));
assertThat(groups.get(DEFAULT_LOGIN).stream().anyMatch(g -> g.equals(defaultGroup.getName()))).isTrue();
}
@Test
public void fail_to_update_user_when_scm_account_is_already_used() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@email.com").setScmAccounts(singletonList("ma")));
db.users().insertUser(newLocalUser("john", "John", "john@email.com").setScmAccounts(singletonList("jo")));
createDefaultGroup();
UpdateUser updateUser = new UpdateUser()
.setName("Marius2")
.setEmail("marius2@mail.com")
.setPassword("password2")
.setScmAccounts(asList("jo"));
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("The scm account 'jo' is already used by user(s) : 'John (john)'");
}
@Test
public void fail_to_update_user_when_scm_account_is_user_login() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr"));
createDefaultGroup();
UpdateUser updateUser = new UpdateUser().setScmAccounts(asList(DEFAULT_LOGIN));
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login and email are automatically considered as SCM accounts");
}
@Test
public void fail_to_update_user_when_scm_account_is_existing_user_email() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr"));
createDefaultGroup();
UpdateUser updateUser = new UpdateUser().setScmAccounts(asList("marius@lesbronzes.fr"));
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login and email are automatically considered as SCM accounts");
}
@Test
public void fail_to_update_user_when_scm_account_is_new_user_email() {
UserDto user = db.users().insertUser(newLocalUser(DEFAULT_LOGIN, "Marius", "marius@lesbronzes.fr"));
createDefaultGroup();
UpdateUser updateUser = new UpdateUser()
.setEmail("marius@newmail.com")
.setScmAccounts(singletonList("marius@newmail.com"));
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login and email are automatically considered as SCM accounts");
}
@Test
public void fail_to_update_login_when_format_is_invalid() {
UserDto user = db.users().insertUser();
createDefaultGroup();
UpdateUser updateUser = new UpdateUser().setLogin("With space");
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login should contain only letters, numbers, and .-_@");
}
@Test
public void fail_to_update_login_when_login_start_with_unauthorized_characters() {
UserDto user = db.users().insertUser();
createDefaultGroup();
UpdateUser updateUser = new UpdateUser().setLogin("#StartWithUnderscore");
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(BadRequestException.class)
.hasMessage("Login should start with _ or alphanumeric.");
}
@Test
public void fail_to_update_user_when_login_already_exists() {
createDefaultGroup();
UserDto user = db.users().insertUser(u -> u.setActive(false));
UserDto existingUser = db.users().insertUser(u -> u.setLogin("existing_login"));
UpdateUser updateUser = new UpdateUser().setLogin(existingUser.getLogin());
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A user with login 'existing_login' already exists");
}
@Test
public void fail_to_update_user_when_external_id_and_external_provider_already_exists() {
createDefaultGroup();
UserDto user = db.users().insertUser(u -> u.setActive(false));
UserDto existingUser = db.users().insertUser(u -> u.setExternalId("existing_external_id").setExternalIdentityProvider("existing_external_provider"));
UpdateUser updateUser = new UpdateUser()
.setExternalIdentity(
new ExternalIdentity(
existingUser.getExternalIdentityProvider(),
existingUser.getExternalLogin(),
existingUser.getExternalId()));
assertThatThrownBy(() -> underTest.updateAndCommit(session, user, updateUser, EMPTY_USER_CONSUMER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists");
}
private GroupDto createDefaultGroup() {
return db.users().insertDefaultGroup();
}
}
| 27,249 | 42.253968 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/usergroups/DefaultGroupFinderIT.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.junit.Rule;
import org.junit.Test;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DefaultGroupFinderIT {
@Rule
public DbTester db = DbTester.create();
private final DefaultGroupFinder underTest = new DefaultGroupFinder(db.getDbClient());
@Test
public void find_default_group() {
GroupDto defaultGroup = db.users().insertDefaultGroup();
GroupDto result = underTest.findDefaultGroup(db.getSession());
assertThat(result.getUuid()).isEqualTo(defaultGroup.getUuid());
assertThat(result.getName()).isEqualTo("sonar-users");
}
@Test
public void fail_with_ISE_when_no_default_group() {
db.users().insertGroup();
DbSession session = db.getSession();
assertThatThrownBy(() -> underTest.findDefaultGroup(session))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Default group cannot be found");
}
@Test
public void fail_with_ISE_when_default_group_does_not_exist() {
GroupDto defaultGroup = db.users().insertDefaultGroup();
db.getDbClient().groupDao().deleteByUuid(db.getSession(), defaultGroup.getUuid(), defaultGroup.getName());
DbSession session = db.getSession();
assertThatThrownBy(() -> underTest.findDefaultGroup(session))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Default group cannot be found");
}
}
| 2,401 | 33.811594 | 110 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/it/java/org/sonar/server/usertoken/UserTokenAuthenticationIT.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 com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Base64;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
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 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.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;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.db.user.TokenType.GLOBAL_ANALYSIS_TOKEN;
import static org.sonar.db.user.TokenType.PROJECT_ANALYSIS_TOKEN;
import static org.sonar.db.user.TokenType.USER_TOKEN;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method.SONARQUBE_TOKEN;
@RunWith(DataProviderRunner.class)
public class UserTokenAuthenticationIT {
private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String EXAMPLE_OLD_USER_TOKEN = "StringWith40CharactersThatIsOldUserToken";
private static final String EXAMPLE_NEW_USER_TOKEN = "squ_StringWith44CharactersThatIsNewUserToken";
private static final String EXAMPLE_GLOBAL_ANALYSIS_TOKEN = "sqa_StringWith44CharactersWhichIsGlobalToken";
private static final String EXAMPLE_PROJECT_ANALYSIS_TOKEN = "sqp_StringWith44CharactersThatIsProjectToken";
private static final String OLD_USER_TOKEN_HASH = "old-user-token-hash";
private static final String NEW_USER_TOKEN_HASH = "new-user-token-hash";
private static final String PROJECT_ANALYSIS_TOKEN_HASH = "project-analysis-token-hash";
private static final String GLOBAL_ANALYSIS_TOKEN_HASH = "global-analysis-token-hash";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final TokenGenerator tokenGenerator = mock(TokenGenerator.class);
private final UserLastConnectionDatesUpdater userLastConnectionDatesUpdater = mock(UserLastConnectionDatesUpdater.class);
private final AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private final HttpRequest request = mock(HttpRequest.class);
private final UserTokenAuthentication underTest = new UserTokenAuthentication(tokenGenerator, db.getDbClient(), userLastConnectionDatesUpdater, authenticationEvent);
@Before
public void before() {
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64("token:"));
when(request.getServletPath()).thenReturn("/api/anypath");
when(tokenGenerator.hash(EXAMPLE_OLD_USER_TOKEN)).thenReturn(OLD_USER_TOKEN_HASH);
when(tokenGenerator.hash(EXAMPLE_NEW_USER_TOKEN)).thenReturn(NEW_USER_TOKEN_HASH);
when(tokenGenerator.hash(EXAMPLE_PROJECT_ANALYSIS_TOKEN)).thenReturn(PROJECT_ANALYSIS_TOKEN_HASH);
when(tokenGenerator.hash(EXAMPLE_GLOBAL_ANALYSIS_TOKEN)).thenReturn(GLOBAL_ANALYSIS_TOKEN_HASH);
}
@Test
public void return_login_when_token_hash_found_in_db_and_basic_auth_used() {
String token = "known-token";
String tokenHash = "123456789";
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(token + ":"));
when(tokenGenerator.hash(token)).thenReturn(tokenHash);
UserDto user1 = db.users().insertUser();
UserTokenDto userTokenDto = db.users().insertToken(user1, t -> t.setTokenHash(tokenHash));
UserDto user2 = db.users().insertUser();
db.users().insertToken(user2, t -> t.setTokenHash("another-token-hash"));
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isPresent();
assertThat(result.get().getTokenDto().getUuid()).isEqualTo(userTokenDto.getUuid());
assertThat(result.get().getUserDto().getUuid())
.isNotNull()
.contains(user1.getUuid());
verify(userLastConnectionDatesUpdater).updateLastConnectionDateIfNeeded(any(UserTokenDto.class));
}
@DataProvider
public static Object[][] bearerHeaderName() {
return new Object[][] {
{"bearer"},
{"BEARER"},
{"Bearer"},
{"bEarer"},
};
}
@Test
@UseDataProvider("bearerHeaderName")
public void authenticate_withDifferentBearerHeaderNameCase_succeeds(String headerName) {
String token = setUpValidAuthToken();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn(headerName + " " + token);
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isPresent();
verify(userLastConnectionDatesUpdater).updateLastConnectionDateIfNeeded(any(UserTokenDto.class));
}
@Test
public void authenticate_withValidCamelcaseBearerTokenForMetricsAction_fails() {
String token = setUpValidAuthToken();
when(request.getServletPath()).thenReturn("/api/monitoring/metrics");
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Bearer " + token);
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isEmpty();
}
private String setUpValidAuthToken() {
String token = "known-token";
String tokenHash = "123456789";
when(tokenGenerator.hash(token)).thenReturn(tokenHash);
UserDto user1 = db.users().insertUser();
UserTokenDto userTokenDto = db.users().insertToken(user1, t -> t.setTokenHash(tokenHash));
UserDto user2 = db.users().insertUser();
db.users().insertToken(user2, t -> t.setTokenHash("another-token-hash"));
return token;
}
@Test
public void return_login_when_token_hash_found_in_db_and_future_expiration_date() {
String token = "known-token";
String tokenHash = "123456789";
long expirationTimestamp = ZonedDateTime.now(ZoneOffset.UTC).plusDays(10).toInstant().toEpochMilli();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(token + ":"));
when(tokenGenerator.hash(token)).thenReturn(tokenHash);
UserDto user1 = db.users().insertUser();
UserTokenDto userTokenDto = db.users().insertToken(user1, t -> t.setTokenHash(tokenHash).setExpirationDate(expirationTimestamp));
UserDto user2 = db.users().insertUser();
db.users().insertToken(user2, t -> t.setTokenHash("another-token-hash"));
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isPresent();
assertThat(result.get().getTokenDto().getUuid()).isEqualTo(userTokenDto.getUuid());
assertThat(result.get().getTokenDto().getExpirationDate()).isEqualTo(expirationTimestamp);
assertThat(result.get().getUserDto().getUuid())
.isNotNull()
.contains(user1.getUuid());
verify(userLastConnectionDatesUpdater).updateLastConnectionDateIfNeeded(any(UserTokenDto.class));
}
@Test
public void return_absent_if_username_password_used() {
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64("login:password"));
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isEmpty();
verify(userLastConnectionDatesUpdater, never()).updateLastConnectionDateIfNeeded(any(UserTokenDto.class));
verifyNoInteractions(authenticationEvent);
}
@Test
public void throw_authentication_exception_if_token_hash_is_not_found() {
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(EXAMPLE_OLD_USER_TOKEN + ":"));
assertThatThrownBy(() -> underTest.authenticate(request))
.hasMessageContaining("Token doesn't exist")
.isInstanceOf(AuthenticationException.class);
verify(userLastConnectionDatesUpdater, never()).updateLastConnectionDateIfNeeded(any(UserTokenDto.class));
verifyNoInteractions(authenticationEvent);
}
@Test
public void throw_authentication_exception_if_token_is_expired() {
String token = "known-token";
String tokenHash = "123456789";
long expirationTimestamp = System.currentTimeMillis();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(token + ":"));
when(tokenGenerator.hash(token)).thenReturn(tokenHash);
UserDto user1 = db.users().insertUser();
db.users().insertToken(user1, t -> t.setTokenHash(tokenHash).setExpirationDate(expirationTimestamp));
assertThatThrownBy(() -> underTest.authenticate(request))
.hasMessageContaining("The token expired on " + formatDateTime(expirationTimestamp))
.isInstanceOf(AuthenticationException.class);
verify(userLastConnectionDatesUpdater, never()).updateLastConnectionDateIfNeeded(any(UserTokenDto.class));
verifyNoInteractions(authenticationEvent);
}
@Test
public void authenticate_givenGlobalToken_resultContainsUuid() {
UserDto user = db.users().insertUser();
String tokenName = db.users().insertToken(user, t -> t.setTokenHash(GLOBAL_ANALYSIS_TOKEN_HASH).setType(GLOBAL_ANALYSIS_TOKEN.name())).getName();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(EXAMPLE_GLOBAL_ANALYSIS_TOKEN + ":"));
var result = underTest.authenticate(request);
assertThat(result).isPresent();
assertThat(result.get().getTokenDto().getUuid()).isNotNull();
assertThat(result.get().getTokenDto().getType()).isEqualTo(GLOBAL_ANALYSIS_TOKEN.name());
verify(authenticationEvent).loginSuccess(request, user.getLogin(), AuthenticationEvent.Source.local(SONARQUBE_TOKEN));
verify(request).setAttribute("TOKEN_NAME", tokenName);
}
@Test
public void authenticate_givenNewUserToken_resultContainsUuid() {
UserDto user = db.users().insertUser();
String tokenName = db.users().insertToken(user, t -> t.setTokenHash(NEW_USER_TOKEN_HASH).setType(USER_TOKEN.name())).getName();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(EXAMPLE_NEW_USER_TOKEN + ":"));
var result = underTest.authenticate(request);
assertThat(result).isPresent();
assertThat(result.get().getTokenDto().getUuid()).isNotNull();
assertThat(result.get().getTokenDto().getType()).isEqualTo(USER_TOKEN.name());
verify(authenticationEvent).loginSuccess(request, user.getLogin(), AuthenticationEvent.Source.local(SONARQUBE_TOKEN));
verify(request).setAttribute("TOKEN_NAME", tokenName);
}
@Test
public void authenticate_givenProjectToken_resultContainsUuid() {
UserDto user = db.users().insertUser();
String tokenName = db.users().insertToken(user, t -> t.setTokenHash(PROJECT_ANALYSIS_TOKEN_HASH)
.setProjectUuid("project-uuid")
.setType(PROJECT_ANALYSIS_TOKEN.name())).getName();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(EXAMPLE_PROJECT_ANALYSIS_TOKEN + ":"));
var result = underTest.authenticate(request);
assertThat(result).isPresent();
assertThat(result.get().getTokenDto().getUuid()).isNotNull();
assertThat(result.get().getTokenDto().getType()).isEqualTo(PROJECT_ANALYSIS_TOKEN.name());
assertThat(result.get().getTokenDto().getProjectUuid()).isEqualTo("project-uuid");
verify(authenticationEvent).loginSuccess(request, user.getLogin(), AuthenticationEvent.Source.local(SONARQUBE_TOKEN));
verify(request).setAttribute("TOKEN_NAME", tokenName);
}
@Test
public void does_not_authenticate_from_user_token_when_token_does_not_match_active_user() {
UserDto user = db.users().insertDisabledUser();
String tokenName = db.users().insertToken(user, t -> t.setTokenHash(NEW_USER_TOKEN_HASH).setType(USER_TOKEN.name())).getName();
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(EXAMPLE_NEW_USER_TOKEN + ":"));
assertThatThrownBy(() -> underTest.authenticate(request))
.hasMessageContaining("User doesn't exist")
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.local(SONARQUBE_TOKEN));
verifyNoInteractions(authenticationEvent);
}
@Test
public void return_token_from_db() {
String token = "known-token";
String tokenHash = "123456789";
when(tokenGenerator.hash(token)).thenReturn(tokenHash);
UserDto user1 = db.users().insertUser();
UserTokenDto userTokenDto = db.users().insertToken(user1, t -> t.setTokenHash(tokenHash));
UserTokenDto result = underTest.getUserToken(token);
assertThat(result.getUuid()).isEqualTo(userTokenDto.getUuid());
}
@Test
public void return_login_when_token_hash_found_in_db2() {
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64("login:password"));
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isEmpty();
}
@Test
public void return_login_when_token_hash_found_in_db3() {
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn(null);
Optional<UserAuthResult> result = underTest.authenticate(request);
assertThat(result).isEmpty();
}
private static String toBase64(String text) {
return new String(BASE64_ENCODER.encode(text.getBytes(UTF_8)));
}
}
| 14,625 | 44.70625 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/AuthenticationError.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.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.authentication.event.AuthenticationException;
import static org.sonar.server.authentication.AuthenticationRedirection.encodeMessage;
import static org.sonar.server.authentication.AuthenticationRedirection.redirectTo;
import static org.sonar.server.authentication.Cookies.newCookieBuilder;
public final class AuthenticationError {
private static final String UNAUTHORIZED_PATH = "/sessions/unauthorized";
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationError.class);
private static final String AUTHENTICATION_ERROR_COOKIE = "AUTHENTICATION-ERROR";
private static final int FIVE_MINUTES_IN_SECONDS = 5 * 60;
private AuthenticationError() {
// Utility class
}
static void handleError(Exception e, HttpRequest request, HttpResponse response, String message) {
LOGGER.warn(message, e);
redirectToUnauthorized(request, response);
}
public static void handleError(HttpRequest request, HttpResponse response, String message) {
LOGGER.warn(message);
redirectToUnauthorized(request, response);
}
static void handleAuthenticationError(AuthenticationException e, HttpRequest request, HttpResponse response) {
String publicMessage = e.getPublicMessage();
if (publicMessage != null && !publicMessage.isEmpty()) {
addErrorCookie(request, response, publicMessage);
}
redirectToUnauthorized(request, response);
}
public static void addErrorCookie(HttpRequest request, HttpResponse response, String value) {
response.addCookie(newCookieBuilder(request)
.setName(AUTHENTICATION_ERROR_COOKIE)
.setValue(encodeMessage(value))
.setHttpOnly(false)
.setExpiry(FIVE_MINUTES_IN_SECONDS)
.build());
}
private static void redirectToUnauthorized(HttpRequest request, HttpResponse response) {
redirectTo(response, request.getContextPath() + UNAUTHORIZED_PATH);
}
}
| 2,944 | 38.266667 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/AuthenticationFilter.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.CheckForNull;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.web.HttpFilter;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static org.sonar.server.authentication.AuthenticationError.handleError;
public abstract class AuthenticationFilter extends HttpFilter {
static final String CALLBACK_PATH = "/oauth2/callback/";
private final IdentityProviderRepository identityProviderRepository;
protected AuthenticationFilter(IdentityProviderRepository identityProviderRepository) {
this.identityProviderRepository = identityProviderRepository;
}
/**
* @return the {@link IdentityProvider} for the key extracted in the request if is exists, or {@code null}, in which
* case the request is fully handled and caller should not handle it
*/
@CheckForNull
IdentityProvider resolveProviderOrHandleResponse(HttpRequest request, HttpResponse response, String path) {
String requestUri = request.getRequestURI();
String providerKey = extractKeyProvider(requestUri, request.getContextPath() + path);
if (providerKey == null) {
handleError(request, response, "No provider key found in URI");
return null;
}
try {
return identityProviderRepository.getEnabledByKey(providerKey);
} catch (Exception e) {
handleError(e, request, response, format("Failed to retrieve IdentityProvider for key '%s'", providerKey));
return null;
}
}
@CheckForNull
private static String extractKeyProvider(String requestUri, String context) {
if (requestUri.contains(context)) {
String key = requestUri.replace(context, "");
if (!isNullOrEmpty(key)) {
return key;
}
}
return null;
}
}
| 2,782 | 37.652778 | 118 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/AuthenticationModule.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.core.platform.Module;
import org.sonar.server.authentication.event.AuthenticationEventImpl;
import org.sonar.server.authentication.purge.ExpiredSessionsCleaner;
import org.sonar.server.authentication.purge.ExpiredSessionsCleanerExecutorServiceImpl;
public class AuthenticationModule extends Module {
@Override
protected void configureModule() {
add(
AuthenticationEventImpl.class,
BaseContextFactory.class,
BasicAuthentication.class,
CredentialsAuthentication.class,
CredentialsExternalAuthentication.class,
LdapCredentialsAuthentication.class,
CredentialsLocalAuthentication.class,
DefaultAdminCredentialsVerifierFilter.class,
GithubWebhookAuthentication.class,
HttpHeadersAuthentication.class,
IdentityProviderRepository.class,
InitFilter.class,
JwtCsrfVerifier.class,
JwtHttpHandler.class,
JwtSerializer.class,
OAuth2AuthenticationParametersImpl.class,
SamlValidationRedirectionFilter.class,
OAuth2CallbackFilter.class,
OAuth2ContextFactory.class,
OAuthCsrfVerifier.class,
RequestAuthenticatorImpl.class,
ResetPasswordFilter.class,
ExpiredSessionsCleaner.class,
ExpiredSessionsCleanerExecutorServiceImpl.class,
UserLastConnectionDatesUpdaterImpl.class,
UserRegistrarImpl.class,
UserSessionInitializer.class);
}
}
| 2,291 | 37.2 | 87 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/AuthenticationRedirection.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.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.sonar.api.server.http.HttpResponse;
import static java.lang.String.format;
import static java.net.URLEncoder.encode;
import static java.nio.charset.StandardCharsets.UTF_8;
public class AuthenticationRedirection {
private AuthenticationRedirection() {
// Only static methods
}
public static String encodeMessage(String message) {
try {
return encode(message, UTF_8.name())
// In order for Javascript to be able to decode this message, + must be replaced by %20
.replace("+", "%20");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(format("Fail to encode %s", message), e);
}
}
public static void redirectTo(HttpResponse response, String url) {
try {
response.sendRedirect(url);
} catch (IOException e) {
throw new IllegalStateException(format("Fail to redirect to %s", url), e);
}
}
static void redirectTo(HttpServletResponse response, String url) {
try {
response.sendRedirect(url);
} catch (IOException e) {
throw new IllegalStateException(format("Fail to redirect to %s", url), e);
}
}
}
| 2,147 | 33.095238 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/BaseContextFactory.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.sonar.api.platform.Server;
import org.sonar.api.server.authentication.BaseIdentityProvider;
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.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.http.JavaxHttpRequest;
import org.sonar.server.http.JavaxHttpResponse;
import org.sonar.server.user.ThreadLocalUserSession;
import org.sonar.server.user.UserSessionFactory;
public class BaseContextFactory {
private final ThreadLocalUserSession threadLocalUserSession;
private final UserRegistrar userRegistrar;
private final Server server;
private final JwtHttpHandler jwtHttpHandler;
private final UserSessionFactory userSessionFactory;
public BaseContextFactory(UserRegistrar userRegistrar, Server server, JwtHttpHandler jwtHttpHandler,
ThreadLocalUserSession threadLocalUserSession, UserSessionFactory userSessionFactory) {
this.userSessionFactory = userSessionFactory;
this.userRegistrar = userRegistrar;
this.server = server;
this.jwtHttpHandler = jwtHttpHandler;
this.threadLocalUserSession = threadLocalUserSession;
}
public BaseIdentityProvider.Context newContext(HttpRequest request, HttpResponse response, BaseIdentityProvider identityProvider) {
return new ContextImpl(request, response, identityProvider);
}
private class ContextImpl implements BaseIdentityProvider.Context {
private final HttpRequest request;
private final HttpResponse response;
private final BaseIdentityProvider identityProvider;
public ContextImpl(HttpRequest request, HttpResponse response, BaseIdentityProvider identityProvider) {
this.request = request;
this.response = response;
this.identityProvider = identityProvider;
}
@Override
public HttpRequest getHttpRequest() {
return request;
}
@Override
public HttpResponse getHttpResponse() {
return response;
}
@Override
public HttpServletRequest getRequest() {
return ((JavaxHttpRequest) request).getDelegate();
}
@Override
public HttpServletResponse getResponse() {
return ((JavaxHttpResponse) response).getDelegate();
}
@Override
public String getServerBaseURL() {
return server.getPublicRootUrl();
}
@Override
public void authenticate(UserIdentity userIdentity) {
UserDto userDto = userRegistrar.register(
UserRegistration.builder()
.setUserIdentity(userIdentity)
.setProvider(identityProvider)
.setSource(Source.external(identityProvider))
.build());
jwtHttpHandler.generateToken(userDto, request, response);
threadLocalUserSession.set(userSessionFactory.create(userDto));
}
}
}
| 3,873 | 35.54717 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/BasicAuthentication.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.sonar.api.server.http.HttpRequest;
import org.sonar.db.user.UserDto;
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.apache.commons.lang.StringUtils.startsWithIgnoreCase;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
/**
* HTTP BASIC authentication relying on tuple {login, password}.
* Login can represent a user access token.
*
* @see CredentialsAuthentication for standard login/password authentication
* @see UserTokenAuthentication for user access token
*/
public class BasicAuthentication {
private final CredentialsAuthentication credentialsAuthentication;
private final UserTokenAuthentication userTokenAuthentication;
public BasicAuthentication(CredentialsAuthentication credentialsAuthentication, UserTokenAuthentication userTokenAuthentication) {
this.credentialsAuthentication = credentialsAuthentication;
this.userTokenAuthentication = userTokenAuthentication;
}
public Optional<UserDto> authenticate(HttpRequest request) {
return extractCredentialsFromHeader(request)
.flatMap(credentials -> Optional.ofNullable(authenticate(credentials, request)));
}
public static Optional<Credentials> extractCredentialsFromHeader(HttpRequest request) {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || !startsWithIgnoreCase(authorizationHeader, "BASIC")) {
return Optional.empty();
}
String basicAuthEncoded = authorizationHeader.substring(6);
String basicAuthDecoded = getDecodedBasicAuth(basicAuthEncoded);
int semiColonPos = basicAuthDecoded.indexOf(':');
if (semiColonPos <= 0) {
throw AuthenticationException.newBuilder()
.setSource(Source.local(Method.BASIC))
.setMessage("Decoded basic auth does not contain ':'")
.build();
}
String login = basicAuthDecoded.substring(0, semiColonPos);
String password = basicAuthDecoded.substring(semiColonPos + 1);
return Optional.of(new Credentials(login, password));
}
private static String getDecodedBasicAuth(String basicAuthEncoded) {
try {
return new String(Base64.getDecoder().decode(basicAuthEncoded.getBytes(UTF_8)), UTF_8);
} catch (Exception e) {
throw AuthenticationException.newBuilder()
.setSource(Source.local(Method.BASIC))
.setMessage("Invalid basic header")
.build();
}
}
private UserDto authenticate(Credentials credentials, HttpRequest request) {
if (credentials.getPassword().isEmpty()) {
Optional<UserAuthResult> userAuthResult = userTokenAuthentication.authenticate(request);
if (userAuthResult.isPresent()) {
return userAuthResult.get().getUserDto();
} else {
throw AuthenticationException.newBuilder()
.setSource(AuthenticationEvent.Source.local(AuthenticationEvent.Method.SONARQUBE_TOKEN))
.setMessage("User doesn't exist")
.build();
}
}
return credentialsAuthentication.authenticate(credentials, request, Method.BASIC);
}
}
| 4,296 | 39.92381 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/Cookies.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.Arrays;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.server.http.Cookie;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.server.http.JavaxHttpRequest.JavaxCookie;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Helper class to create a {@link javax.servlet.http.Cookie}.
*
* The {@link javax.servlet.http.Cookie#setSecure(boolean)} will automatically be set to true.
*/
public class Cookies {
public static final String SET_COOKIE = "Set-Cookie";
public static final String SAMESITE_LAX = "Lax";
private static final String HTTPS_HEADER = "X-Forwarded-Proto";
private static final String HTTPS_VALUE = "https";
private Cookies() {
// Only static methods
}
public static Optional<Cookie> findCookie(String cookieName, HttpRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return Optional.empty();
}
return Arrays.stream(cookies)
.filter(cookie -> cookieName.equals(cookie.getName()))
.findFirst();
}
public static CookieBuilder newCookieBuilder(HttpRequest request) {
return new CookieBuilder(request);
}
public static class CookieBuilder {
private final HttpRequest request;
private String name;
private String value;
private boolean httpOnly;
private int expiry;
private String sameSite;
CookieBuilder(HttpRequest request) {
this.request = request;
}
/**
* Name of the cookie
*/
public CookieBuilder setName(String name) {
this.name = requireNonNull(name);
return this;
}
/**
* Name of the cookie
*/
public CookieBuilder setValue(@Nullable String value) {
this.value = value;
return this;
}
/**
* SameSite attribute, only work for toString()
*/
public CookieBuilder setSameSite(@Nullable String sameSite) {
this.sameSite = sameSite;
return this;
}
/**
* Sets the flag that controls if this cookie will be hidden from scripts on the client side.
*/
public CookieBuilder setHttpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
return this;
}
/**
* Sets the maximum age of the cookie in seconds.
*/
public CookieBuilder setExpiry(int expiry) {
this.expiry = expiry;
return this;
}
public Cookie build() {
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(requireNonNull(name), value);
cookie.setPath(getContextPath(request));
cookie.setSecure(isHttps(request));
cookie.setHttpOnly(httpOnly);
cookie.setMaxAge(expiry);
return new JavaxCookie(cookie);
}
public String toValueString() {
String output = String.format("%s=%s; Path=%s; SameSite=%s; Max-Age=%d", name, value, getContextPath(request), sameSite, expiry);
if (httpOnly) {
output += "; HttpOnly";
}
if (isHttps(request)) {
output += "; Secure";
}
return output;
}
private static boolean isHttps(HttpRequest request) {
return HTTPS_VALUE.equalsIgnoreCase(request.getHeader(HTTPS_HEADER));
}
private static String getContextPath(HttpRequest request) {
String path = request.getContextPath();
return isNullOrEmpty(path) ? "/" : path;
}
}
}
| 4,298 | 28.244898 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/Credentials.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.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
@Immutable
public class Credentials {
private final String login;
private final String password;
public Credentials(String login, @Nullable String password) {
checkArgument(login != null && !login.isEmpty(), "login must not be null nor empty");
this.login = login;
this.password = defaultIfEmpty(password, null);
}
/**
* Non-empty login
*/
public String getLogin() {
return login;
}
/**
* Non-empty password. {@code Optional.empty()} is returned if the password is not set
* or initially empty. {@code Optional.of("")} is never returned.
*/
public Optional<String> getPassword() {
return Optional.ofNullable(password);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Credentials that = (Credentials) o;
return login.equals(that.login) && password.equals(that.password);
}
@Override
public int hashCode() {
return Objects.hash(login, password);
}
}
| 2,206 | 28.824324 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsAuthentication.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.sonar.api.server.http.HttpRequest;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
/**
* Authentication based on the tuple {login, password}. Validation can be
* delegated to an external system, e.g. LDAP.
*/
public class CredentialsAuthentication {
static final String ERROR_PASSWORD_CANNOT_BE_NULL = "Password cannot be null";
private final DbClient dbClient;
private final AuthenticationEvent authenticationEvent;
private final CredentialsExternalAuthentication externalAuthentication;
private final CredentialsLocalAuthentication localAuthentication;
private final LdapCredentialsAuthentication ldapCredentialsAuthentication;
public CredentialsAuthentication(DbClient dbClient, AuthenticationEvent authenticationEvent,
CredentialsExternalAuthentication externalAuthentication, CredentialsLocalAuthentication localAuthentication,
LdapCredentialsAuthentication ldapCredentialsAuthentication) {
this.dbClient = dbClient;
this.authenticationEvent = authenticationEvent;
this.externalAuthentication = externalAuthentication;
this.localAuthentication = localAuthentication;
this.ldapCredentialsAuthentication = ldapCredentialsAuthentication;
}
public UserDto authenticate(Credentials credentials, HttpRequest request, Method method) {
try (DbSession dbSession = dbClient.openSession(false)) {
return authenticate(dbSession, credentials, request, method);
}
}
private UserDto authenticate(DbSession dbSession, Credentials credentials, HttpRequest request, Method method) {
UserDto localUser = dbClient.userDao().selectActiveUserByLogin(dbSession, credentials.getLogin());
if (localUser != null && localUser.isLocal()) {
String password = getNonNullPassword(credentials);
localAuthentication.authenticate(dbSession, localUser, password, method);
dbSession.commit();
authenticationEvent.loginSuccess(request, localUser.getLogin(), Source.local(method));
return localUser;
}
Optional<UserDto> externalUser = externalAuthentication.authenticate(credentials, request, method)
.or(() -> ldapCredentialsAuthentication.authenticate(credentials, request, method));
if (externalUser.isPresent()) {
return externalUser.get();
}
localAuthentication.generateHashToAvoidEnumerationAttack();
throw AuthenticationException.newBuilder()
.setSource(Source.local(method))
.setLogin(credentials.getLogin())
.setMessage(localUser != null && !localUser.isLocal() ? "User is not local" : "No active user for login")
.build();
}
private static String getNonNullPassword(Credentials credentials) {
return credentials.getPassword().orElseThrow(() -> new IllegalArgumentException(ERROR_PASSWORD_CANNOT_BE_NULL));
}
}
| 4,035 | 44.863636 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsExternalAuthentication.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.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
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.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.db.user.UserDto;
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.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.trimToNull;
import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY;
/**
* Delegates the validation of credentials to an external system, e.g. LDAP.
*/
public class CredentialsExternalAuthentication implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(CredentialsExternalAuthentication.class);
private final Configuration config;
private final SecurityRealmFactory securityRealmFactory;
private final UserRegistrar userRegistrar;
private final AuthenticationEvent authenticationEvent;
private SecurityRealm realm;
private Authenticator authenticator;
private ExternalUsersProvider externalUsersProvider;
private ExternalGroupsProvider externalGroupsProvider;
public CredentialsExternalAuthentication(Configuration config, SecurityRealmFactory securityRealmFactory,
UserRegistrar userRegistrar, AuthenticationEvent authenticationEvent) {
this.config = config;
this.securityRealmFactory = securityRealmFactory;
this.userRegistrar = userRegistrar;
this.authenticationEvent = authenticationEvent;
}
@Override
public void start() {
realm = securityRealmFactory.getRealm();
if (realm != null) {
authenticator = requireNonNull(realm.doGetAuthenticator(), "No authenticator available");
externalUsersProvider = requireNonNull(realm.getUsersProvider(), "No users provider available");
externalGroupsProvider = realm.getGroupsProvider();
}
}
public Optional<UserDto> authenticate(Credentials credentials, HttpRequest request, AuthenticationEvent.Method method) {
if (realm == null) {
return Optional.empty();
}
return Optional.of(doAuthenticate(fixCase(credentials), request, method));
}
private UserDto doAuthenticate(Credentials credentials, HttpRequest request, AuthenticationEvent.Method method) {
try {
HttpServletRequest httpServletRequest = ((JavaxHttpRequest) request).getDelegate();
ExternalUsersProvider.Context externalUsersProviderContext = new ExternalUsersProvider.Context(credentials.getLogin(), request, httpServletRequest);
UserDetails details = externalUsersProvider.doGetUserDetails(externalUsersProviderContext);
if (details == null) {
throw AuthenticationException.newBuilder()
.setSource(realmEventSource(method))
.setLogin(credentials.getLogin())
.setMessage("No user details")
.build();
}
Authenticator.Context authenticatorContext = new Authenticator.Context(credentials.getLogin(), credentials.getPassword().orElse(null), request, httpServletRequest);
boolean status = authenticator.doAuthenticate(authenticatorContext);
if (!status) {
throw AuthenticationException.newBuilder()
.setSource(realmEventSource(method))
.setLogin(credentials.getLogin())
.setMessage("Realm returned authenticate=false")
.build();
}
UserDto userDto = synchronize(credentials.getLogin(), details, request, method);
authenticationEvent.loginSuccess(request, credentials.getLogin(), realmEventSource(method));
return userDto;
} catch (AuthenticationException e) {
throw e;
} catch (Exception e) {
// It seems that with Realm API it's expected to log the error and to not authenticate the user
LOG.error("Error during authentication", e);
throw AuthenticationException.newBuilder()
.setSource(realmEventSource(method))
.setLogin(credentials.getLogin())
.setMessage(e.getMessage())
.build();
}
}
private Source realmEventSource(AuthenticationEvent.Method method) {
return Source.realm(method, realm.getName());
}
private UserDto synchronize(String userLogin, UserDetails details, HttpRequest request, AuthenticationEvent.Method method) {
String name = details.getName();
UserIdentity.Builder userIdentityBuilder = UserIdentity.builder()
.setName(isEmpty(name) ? userLogin : name)
.setEmail(trimToNull(details.getEmail()))
.setProviderLogin(userLogin);
if (externalGroupsProvider != null) {
HttpServletRequest httpServletRequest = ((JavaxHttpRequest) request).getDelegate();
ExternalGroupsProvider.Context context = new ExternalGroupsProvider.Context(userLogin, request, httpServletRequest);
Collection<String> groups = externalGroupsProvider.doGetGroups(context);
userIdentityBuilder.setGroups(new HashSet<>(groups));
}
return userRegistrar.register(
UserRegistration.builder()
.setUserIdentity(userIdentityBuilder.build())
.setProvider(new ExternalIdentityProvider())
.setSource(realmEventSource(method))
.build());
}
private Credentials fixCase(Credentials credentials) {
if (config.getBoolean("sonar.authenticator.downcase").orElse(false)) {
return new Credentials(credentials.getLogin().toLowerCase(Locale.ENGLISH), credentials.getPassword().orElse(null));
}
return credentials;
}
private static class ExternalIdentityProvider implements IdentityProvider {
@Override
public String getKey() {
return SQ_AUTHORITY;
}
@Override
public String getName() {
return SQ_AUTHORITY;
}
@Override
public Display getDisplay() {
return null;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean allowsUsersToSignUp() {
return true;
}
}
@Override
public void stop() {
// Nothing to do
}
}
| 7,659 | 38.282051 | 170 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsLocalAuthentication.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.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.EnumMap;
import javax.annotation.Nullable;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.apache.commons.lang.RandomStringUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.sonar.api.config.Configuration;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent.Method;
import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
/**
* Validates the password of a "local" user (password is stored in
* database).
*/
public class CredentialsLocalAuthentication {
public static final String ERROR_NULL_HASH_METHOD = "null hash method";
public static final String ERROR_NULL_PASSWORD_IN_DB = "null password in DB";
public static final String ERROR_NULL_SALT = "null salt";
public static final String ERROR_WRONG_PASSWORD = "wrong password";
public static final String ERROR_UNKNOWN_HASH_METHOD = "Unknown hash method [%s]";
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final String PBKDF2_ITERATIONS_PROP = "sonar.internal.pbkdf2.iterations";
private static final HashMethod DEFAULT = HashMethod.PBKDF2;
private static final int DUMMY_PASSWORD_AND_SALT_SIZE = 100;
private final DbClient dbClient;
private final EnumMap<HashMethod, HashFunction> hashFunctions = new EnumMap<>(HashMethod.class);
public enum HashMethod {
BCRYPT, PBKDF2
}
public CredentialsLocalAuthentication(DbClient dbClient, Configuration configuration) {
this.dbClient = dbClient;
hashFunctions.put(HashMethod.BCRYPT, new BcryptFunction());
hashFunctions.put(HashMethod.PBKDF2, new PBKDF2Function(configuration.getInt(PBKDF2_ITERATIONS_PROP).orElse(null)));
}
void generateHashToAvoidEnumerationAttack(){
String randomSalt = RandomStringUtils.randomAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE);
String randomPassword = RandomStringUtils.randomAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE);
hashFunctions.get(HashMethod.PBKDF2).encryptPassword(randomSalt, randomPassword);
}
/**
* This method authenticate a user with his password against the value stored in user.
* If authentication failed an AuthenticationException will be thrown containing the failure message.
* If the password must be updated because an old algorithm is used, the UserDto is updated but the session
* is not committed
*/
public void authenticate(DbSession session, UserDto user, String password, Method method) {
HashMethod hashMethod = getHashMethod(user, method);
HashFunction hashFunction = hashFunctions.get(hashMethod);
AuthenticationResult result = authenticate(user, password, method, hashFunction);
// Upgrade the password if it's an old hashMethod
if (hashMethod != DEFAULT || result.needsUpdate) {
hashFunctions.get(DEFAULT).storeHashPassword(user, password);
dbClient.userDao().update(session, user);
}
}
private HashMethod getHashMethod(UserDto user, Method method) {
if (user.getHashMethod() == null) {
throw AuthenticationException.newBuilder()
.setSource(Source.local(method))
.setLogin(user.getLogin())
.setMessage(ERROR_NULL_HASH_METHOD)
.build();
}
try {
return HashMethod.valueOf(user.getHashMethod());
} catch (IllegalArgumentException ex) {
generateHashToAvoidEnumerationAttack();
throw AuthenticationException.newBuilder()
.setSource(Source.local(method))
.setLogin(user.getLogin())
.setMessage(format(ERROR_UNKNOWN_HASH_METHOD, user.getHashMethod()))
.build();
}
}
private static AuthenticationResult authenticate(UserDto user, String password, Method method, HashFunction hashFunction) {
AuthenticationResult result = hashFunction.checkCredentials(user, password);
if (!result.isSuccessful()) {
throw AuthenticationException.newBuilder()
.setSource(Source.local(method))
.setLogin(user.getLogin())
.setMessage(result.getFailureMessage())
.build();
}
return result;
}
/**
* Method used to store the password as a hash in database.
* The crypted_password, salt and hash_method are set
*/
public void storeHashPassword(UserDto user, String password) {
hashFunctions.get(DEFAULT).storeHashPassword(user, password);
}
private static class AuthenticationResult {
private final boolean successful;
private final String failureMessage;
private final boolean needsUpdate;
private AuthenticationResult(boolean successful, String failureMessage) {
this(successful, failureMessage, false);
}
private AuthenticationResult(boolean successful, String failureMessage, boolean needsUpdate) {
checkArgument((successful && failureMessage.isEmpty()) || (!successful && !failureMessage.isEmpty()), "Incorrect parameters");
this.successful = successful;
this.failureMessage = failureMessage;
this.needsUpdate = needsUpdate;
}
public boolean isSuccessful() {
return successful;
}
public String getFailureMessage() {
return failureMessage;
}
public boolean isNeedsUpdate() {
return needsUpdate;
}
}
public interface HashFunction {
AuthenticationResult checkCredentials(UserDto user, String password);
void storeHashPassword(UserDto user, String password);
default String encryptPassword(String salt, String password) {
throw new IllegalStateException("This method is not supported for this hash function");
}
}
static final class PBKDF2Function implements HashFunction {
private static final char ITERATIONS_HASH_SEPARATOR = '$';
private static final int DEFAULT_ITERATIONS = 100_000;
private static final String ALGORITHM = "PBKDF2WithHmacSHA512";
private static final int KEY_LEN = 512;
private static final String ERROR_INVALID_HASH_STORED = "invalid hash stored";
private final int generationIterations;
public PBKDF2Function(@Nullable Integer generationIterations) {
this.generationIterations = generationIterations != null ? generationIterations : DEFAULT_ITERATIONS;
}
@Override
public AuthenticationResult checkCredentials(UserDto user, String password) {
if (user.getCryptedPassword() == null) {
return new AuthenticationResult(false, ERROR_NULL_PASSWORD_IN_DB);
}
if (user.getSalt() == null) {
return new AuthenticationResult(false, ERROR_NULL_SALT);
}
int pos = user.getCryptedPassword().indexOf(ITERATIONS_HASH_SEPARATOR);
if (pos < 1) {
return new AuthenticationResult(false, ERROR_INVALID_HASH_STORED);
}
int iterations;
try {
iterations = Integer.parseInt(user.getCryptedPassword().substring(0, pos));
} catch (NumberFormatException e) {
return new AuthenticationResult(false, ERROR_INVALID_HASH_STORED);
}
String hash = user.getCryptedPassword().substring(pos + 1);
byte[] salt = Base64.getDecoder().decode(user.getSalt());
if (!hash.equals(hash(salt, password, iterations))) {
return new AuthenticationResult(false, ERROR_WRONG_PASSWORD);
}
boolean needsUpdate = iterations != generationIterations;
return new AuthenticationResult(true, "", needsUpdate);
}
@Override
public void storeHashPassword(UserDto user, String password) {
byte[] salt = new byte[20];
SECURE_RANDOM.nextBytes(salt);
String hashStr = hash(salt, password, generationIterations);
String saltStr = Base64.getEncoder().encodeToString(salt);
user.setHashMethod(HashMethod.PBKDF2.name())
.setCryptedPassword(composeEncryptedPassword(hashStr))
.setSalt(saltStr);
}
@Override
public String encryptPassword(String saltStr, String password) {
byte[] salt = Base64.getDecoder().decode(saltStr);
return composeEncryptedPassword(hash(salt, password, generationIterations));
}
private String composeEncryptedPassword(String hashStr) {
return format("%d%c%s", generationIterations, ITERATIONS_HASH_SEPARATOR, hashStr);
}
private static String hash(byte[] salt, String password, int iterations) {
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, KEY_LEN);
byte[] hash = skf.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(hash);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
}
}
}
/**
* Implementation of deprecated bcrypt hash function
*/
private static final class BcryptFunction implements HashFunction {
@Override
public AuthenticationResult checkCredentials(UserDto user, String password) {
if (user.getCryptedPassword() == null) {
return new AuthenticationResult(false, ERROR_NULL_PASSWORD_IN_DB);
}
// This behavior is overridden in most of integration tests for performance reasons, any changes to BCrypt calls should be propagated to
// Byteman classes
if (!BCrypt.checkpw(password, user.getCryptedPassword())) {
return new AuthenticationResult(false, ERROR_WRONG_PASSWORD);
}
return new AuthenticationResult(true, "");
}
@Override
public void storeHashPassword(UserDto user, String password) {
user.setHashMethod(HashMethod.BCRYPT.name())
.setCryptedPassword(BCrypt.hashpw(password, BCrypt.gensalt(12)))
.setSalt(null);
}
}
}
| 10,901 | 38.934066 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifier.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;
public interface DefaultAdminCredentialsVerifier {
boolean hasDefaultCredentialUser();
}
| 978 | 35.259259 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierFilter.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.io.IOException;
import java.util.Set;
import org.sonar.api.config.Configuration;
import org.sonar.api.impl.ws.StaticResources;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.web.FilterChain;
import org.sonar.api.web.HttpFilter;
import org.sonar.api.web.UrlPattern;
import org.sonar.server.user.ThreadLocalUserSession;
import static org.sonar.server.authentication.AuthenticationRedirection.redirectTo;
public class DefaultAdminCredentialsVerifierFilter extends HttpFilter {
private static final String RESET_PASSWORD_PATH = "/account/reset_password";
private static final String CHANGE_ADMIN_PASSWORD_PATH = "/admin/change_admin_password";
// This property is used by Orchestrator to disable this force redirect. It should never be used in production, which
// is why this is not defined in org.sonar.process.ProcessProperties.
private static final String SONAR_FORCE_REDIRECT_DEFAULT_ADMIN_CREDENTIALS = "sonar.forceRedirectOnDefaultAdminCredentials";
private static final Set<String> SKIPPED_URLS = Set.of(
RESET_PASSWORD_PATH,
CHANGE_ADMIN_PASSWORD_PATH,
"/batch/*", "/api/*", "/api/v2/*");
private final Configuration config;
private final DefaultAdminCredentialsVerifier defaultAdminCredentialsVerifier;
private final ThreadLocalUserSession userSession;
public DefaultAdminCredentialsVerifierFilter(Configuration config, DefaultAdminCredentialsVerifier defaultAdminCredentialsVerifier, ThreadLocalUserSession userSession) {
this.config = config;
this.defaultAdminCredentialsVerifier = defaultAdminCredentialsVerifier;
this.userSession = userSession;
}
@Override
public UrlPattern doGetPattern() {
return UrlPattern.builder()
.includes("/*")
.excludes(StaticResources.patterns())
.excludes(SKIPPED_URLS)
.build();
}
@Override
public void init() {
// nothing to do
}
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
boolean forceRedirect = config
.getBoolean(SONAR_FORCE_REDIRECT_DEFAULT_ADMIN_CREDENTIALS)
.orElse(true);
if (forceRedirect && userSession.hasSession() && userSession.isLoggedIn()
&& userSession.isSystemAdministrator() && !"admin".equals(userSession.getLogin())
&& defaultAdminCredentialsVerifier.hasDefaultCredentialUser()) {
redirectTo(response, request.getContextPath() + CHANGE_ADMIN_PASSWORD_PATH);
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
// nothing to do
}
}
| 3,510 | 37.582418 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierImpl.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.notification.NotificationManager;
import static org.sonar.server.log.ServerProcessLogging.STARTUP_LOGGER_NAME;
import static org.sonar.server.property.InternalProperties.DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL;
/**
* Detect usage of an active admin account with default credential in order to ask this account to reset its password during authentication.
*/
public class DefaultAdminCredentialsVerifierImpl implements DefaultAdminCredentialsVerifier {
private static final Logger LOGGER = LoggerFactory.getLogger(STARTUP_LOGGER_NAME);
private final DbClient dbClient;
private final CredentialsLocalAuthentication localAuthentication;
private final NotificationManager notificationManager;
public DefaultAdminCredentialsVerifierImpl(DbClient dbClient, CredentialsLocalAuthentication localAuthentication, NotificationManager notificationManager) {
this.dbClient = dbClient;
this.localAuthentication = localAuthentication;
this.notificationManager = notificationManager;
}
public void runAtStart() {
try (DbSession session = dbClient.openSession(false)) {
UserDto admin = getAdminUser(session);
if (admin == null || !isDefaultCredentialUser(session, admin)) {
return;
}
addWarningInSonarDotLog();
dbClient.userDao().update(session, admin.setResetPassword(true));
sendEmailToAdmins(session);
session.commit();
}
}
@Override
public boolean hasDefaultCredentialUser() {
try (DbSession session = dbClient.openSession(false)) {
UserDto admin = getAdminUser(session);
if (admin == null) {
return false;
} else {
return isDefaultCredentialUser(session, admin);
}
}
}
private UserDto getAdminUser(DbSession session) {
return dbClient.userDao().selectActiveUserByLogin(session, "admin");
}
private static void addWarningInSonarDotLog() {
String highlighter = "####################################################################################################################";
String msg = "Default Administrator credentials are still being used. Make sure to change the password or deactivate the account.";
LOGGER.warn(highlighter);
LOGGER.warn(msg);
LOGGER.warn(highlighter);
}
private boolean isDefaultCredentialUser(DbSession dbSession, UserDto user) {
try {
localAuthentication.authenticate(dbSession, user, "admin", AuthenticationEvent.Method.BASIC);
return true;
} catch (AuthenticationException ex) {
return false;
}
}
private void sendEmailToAdmins(DbSession session) {
if (dbClient.internalPropertiesDao().selectByKey(session, DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL)
.map(Boolean::parseBoolean)
.orElse(false)) {
return;
}
notificationManager.scheduleForSending(new DefaultAdminCredentialsVerifierNotification());
dbClient.internalPropertiesDao().save(session, DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL, Boolean.TRUE.toString());
}
}
| 4,180 | 37.712963 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierNotification.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.notifications.Notification;
public class DefaultAdminCredentialsVerifierNotification extends Notification {
static final String TYPE = "default-admin-credential-verifier";
public DefaultAdminCredentialsVerifierNotification() {
super(TYPE);
}
}
| 1,163 | 35.375 | 79 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierNotificationHandler.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.Collection;
import java.util.Optional;
import java.util.Set;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.notification.EmailNotificationHandler;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static java.util.stream.Collectors.toSet;
public class DefaultAdminCredentialsVerifierNotificationHandler extends EmailNotificationHandler<DefaultAdminCredentialsVerifierNotification> {
private final DbClient dbClient;
public DefaultAdminCredentialsVerifierNotificationHandler(DbClient dbClient, EmailNotificationChannel emailNotificationChannel) {
super(emailNotificationChannel);
this.dbClient = dbClient;
}
@Override
public Optional<NotificationDispatcherMetadata> getMetadata() {
return Optional.empty();
}
@Override
public Class<DefaultAdminCredentialsVerifierNotification> getNotificationClass() {
return DefaultAdminCredentialsVerifierNotification.class;
}
@Override
public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<DefaultAdminCredentialsVerifierNotification> notifications) {
try (DbSession session = dbClient.openSession(false)) {
return dbClient.authorizationDao().selectGlobalAdministerEmailSubscribers(session)
.stream()
.flatMap(t -> notifications.stream().map(notification -> new EmailDeliveryRequest(t.getEmail(), notification)))
.collect(toSet());
}
}
}
| 2,497 | 38.650794 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierNotificationTemplate.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.CheckForNull;
import org.sonar.api.notifications.Notification;
import org.sonar.server.issue.notification.EmailMessage;
import org.sonar.server.issue.notification.EmailTemplate;
public class DefaultAdminCredentialsVerifierNotificationTemplate implements EmailTemplate {
static final String SUBJECT = "Default Administrator credentials are still used";
static final String BODY_FORMAT = """
Hello,
Your SonarQube instance is still using default administrator credentials.
Make sure to change the password for the 'admin' account or deactivate this account.""";
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!DefaultAdminCredentialsVerifierNotification.TYPE.equals(notification.getType())) {
return null;
}
return new EmailMessage()
.setMessageId(DefaultAdminCredentialsVerifierNotification.TYPE)
.setSubject(SUBJECT)
.setPlainTextMessage(BODY_FORMAT);
}
}
| 1,868 | 36.38 | 92 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/GithubWebhookAuthentication.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.annotations.VisibleForTesting;
import java.security.MessageDigest;
import java.util.Optional;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.server.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.alm.setting.ALM;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.sonar.server.user.GithubWebhookUserSession.GITHUB_WEBHOOK_USER_NAME;
public class GithubWebhookAuthentication {
private static final Logger LOG = LoggerFactory.getLogger(GithubWebhookAuthentication.class);
@VisibleForTesting
static final String GITHUB_SIGNATURE_HEADER = "x-hub-signature-256";
@VisibleForTesting
static final String GITHUB_APP_ID_HEADER = "x-github-hook-installation-target-id";
@VisibleForTesting
static final String MSG_AUTHENTICATION_FAILED = "Failed to authenticate payload from Github webhook. Either the webhook was called by unexpected clients"
+ " or the webhook secret set in SonarQube does not match the one from Github.";
@VisibleForTesting
static final String MSG_UNAUTHENTICATED_GITHUB_CALLS_DENIED = "Unauthenticated calls from GitHub are forbidden. A webhook secret must be defined in the GitHub App with Id %s.";
@VisibleForTesting
static final String MSG_NO_WEBHOOK_SECRET_FOUND = "Webhook secret for your GitHub app with Id %s must be set in SonarQube.";
@VisibleForTesting
static final String MSG_NO_BODY_FOUND = "No body found in GitHub Webhook event.";
private static final String SHA_256_PREFIX = "sha256=";
private final AuthenticationEvent authenticationEvent;
private final DbClient dbClient;
private final Encryption encryption;
public GithubWebhookAuthentication(AuthenticationEvent authenticationEvent, DbClient dbClient, Settings settings) {
this.authenticationEvent = authenticationEvent;
this.dbClient = dbClient;
this.encryption = settings.getEncryption();
}
public Optional<UserAuthResult> authenticate(HttpRequest request) {
String githubAppId = request.getHeader(GITHUB_APP_ID_HEADER);
if (isEmpty(githubAppId)) {
return Optional.empty();
}
String githubSignature = getGithubSignature(request, githubAppId);
String body = getBody(request);
String webhookSecret = getWebhookSecret(githubAppId);
String computedSignature = computeSignature(body, webhookSecret);
if (!checkEqualityTimingAttacksSafe(githubSignature, computedSignature)) {
logAuthenticationProblemAndThrow(MSG_AUTHENTICATION_FAILED);
}
return createAuthResult(request);
}
private static String getGithubSignature(HttpRequest request, String githubAppId) {
String githubSignature = request.getHeader(GITHUB_SIGNATURE_HEADER);
if (isEmpty(githubSignature)) {
logAuthenticationProblemAndThrow(format(MSG_UNAUTHENTICATED_GITHUB_CALLS_DENIED, githubAppId));
}
return githubSignature;
}
private static String getBody(HttpRequest request) {
try {
return request.getReader().lines().collect(joining(System.lineSeparator()));
} catch (Exception e) {
logAuthenticationProblemAndThrow(MSG_NO_BODY_FOUND);
return "";
}
}
private String getWebhookSecret(String githubAppId) {
String webhookSecret = fetchWebhookSecret(githubAppId);
if (isEmpty(webhookSecret)) {
logAuthenticationProblemAndThrow(format(MSG_NO_WEBHOOK_SECRET_FOUND, githubAppId));
}
return webhookSecret;
}
private String fetchWebhookSecret(String appId) {
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.almSettingDao().selectByAlmAndAppId(dbSession, ALM.GITHUB, appId)
.map(almSettingDto -> almSettingDto.getDecryptedWebhookSecret(encryption))
.orElse(null);
}
}
private static void logAuthenticationProblemAndThrow(String message) {
LOG.warn(message);
throw AuthenticationException.newBuilder()
.setSource(AuthenticationEvent.Source.githubWebhook())
.setMessage(message)
.build();
}
private static String computeSignature(String body, String webhookSecret) {
HmacUtils hmacUtils = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, webhookSecret);
return SHA_256_PREFIX + hmacUtils.hmacHex(body);
}
private static boolean checkEqualityTimingAttacksSafe(String githubSignature, String computedSignature) {
return MessageDigest.isEqual(githubSignature.getBytes(UTF_8), computedSignature.getBytes(UTF_8));
}
private Optional<UserAuthResult> createAuthResult(HttpRequest request) {
UserAuthResult userAuthResult = UserAuthResult.withGithubWebhook();
authenticationEvent.loginSuccess(request, GITHUB_WEBHOOK_USER_NAME, AuthenticationEvent.Source.githubWebhook());
return Optional.of(userAuthResult);
}
}
| 6,170 | 39.333333 | 178 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/HttpHeadersAuthentication.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.base.Splitter;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.utils.System2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.user.UserDto;
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 org.sonar.server.exceptions.BadRequestException;
import static org.apache.commons.lang.time.DateUtils.addMinutes;
import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_EMAIL_HEADER;
import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_ENABLE;
import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_GROUPS_HEADER;
import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_LOGIN_HEADER;
import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_NAME_HEADER;
import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES;
import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY;
/**
* Authentication based on the HTTP request headers. The front proxy
* is responsible for validating user identity.
*/
public class HttpHeadersAuthentication implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(HttpHeadersAuthentication.class);
private static final Splitter COMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
private static final String LAST_REFRESH_TIME_TOKEN_PARAM = "ssoLastRefreshTime";
private static final EnumSet<ProcessProperties.Property> PROPERTIES = EnumSet.of(
SONAR_WEB_SSO_LOGIN_HEADER,
SONAR_WEB_SSO_NAME_HEADER,
SONAR_WEB_SSO_EMAIL_HEADER,
SONAR_WEB_SSO_GROUPS_HEADER,
SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES);
private final System2 system2;
private final Configuration config;
private final UserRegistrar userRegistrar;
private final JwtHttpHandler jwtHttpHandler;
private final AuthenticationEvent authenticationEvent;
private final Map<String, String> settingsByKey = new HashMap<>();
private boolean enabled = false;
public HttpHeadersAuthentication(System2 system2, Configuration config, UserRegistrar userRegistrar,
JwtHttpHandler jwtHttpHandler, AuthenticationEvent authenticationEvent) {
this.system2 = system2;
this.config = config;
this.userRegistrar = userRegistrar;
this.jwtHttpHandler = jwtHttpHandler;
this.authenticationEvent = authenticationEvent;
}
@Override
public void start() {
if (config.getBoolean(SONAR_WEB_SSO_ENABLE.getKey()).orElse(false)) {
LOG.info("HTTP headers authentication enabled");
enabled = true;
PROPERTIES.forEach(entry -> settingsByKey.put(entry.getKey(), config.get(entry.getKey()).orElse(entry.getDefaultValue())));
}
}
@Override
public void stop() {
// Nothing to do
}
public Optional<UserDto> authenticate(HttpRequest request, HttpResponse response) {
try {
return doAuthenticate(request, response);
} catch (BadRequestException e) {
throw AuthenticationException.newBuilder()
.setSource(Source.sso())
.setMessage(e.getMessage())
.build();
}
}
private Optional<UserDto> doAuthenticate(HttpRequest request, HttpResponse response) {
if (!enabled) {
return Optional.empty();
}
Map<String, String> headerValuesByNames = getHeaders(request);
String login = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_LOGIN_HEADER.getKey());
if (login == null) {
return Optional.empty();
}
Optional<UserDto> user = getUserFromToken(request, response);
if (user.isPresent() && login.equals(user.get().getLogin())) {
return user;
}
UserDto userDto = doAuthenticate(headerValuesByNames, login);
jwtHttpHandler.generateToken(userDto, Map.of(LAST_REFRESH_TIME_TOKEN_PARAM, system2.now()), request, response);
authenticationEvent.loginSuccess(request, userDto.getLogin(), Source.sso());
return Optional.of(userDto);
}
private Optional<UserDto> getUserFromToken(HttpRequest request, HttpResponse response) {
Optional<JwtHttpHandler.Token> token = jwtHttpHandler.getToken(request, response);
if (token.isEmpty()) {
return Optional.empty();
}
Date now = new Date(system2.now());
int refreshIntervalInMinutes = Integer.parseInt(settingsByKey.get(SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES.getKey()));
Long lastFreshTime = (Long) token.get().getProperties().get(LAST_REFRESH_TIME_TOKEN_PARAM);
if (lastFreshTime == null || now.after(addMinutes(new Date(lastFreshTime), refreshIntervalInMinutes))) {
return Optional.empty();
}
return Optional.of(token.get().getUserDto());
}
private UserDto doAuthenticate(Map<String, String> headerValuesByNames, String login) {
String name = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_NAME_HEADER.getKey());
String email = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_EMAIL_HEADER.getKey());
UserIdentity.Builder userIdentityBuilder = UserIdentity.builder()
.setName(name == null ? login : name)
.setEmail(email)
.setProviderLogin(login);
if (hasHeader(headerValuesByNames, SONAR_WEB_SSO_GROUPS_HEADER.getKey())) {
String groupsValue = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_GROUPS_HEADER.getKey());
userIdentityBuilder.setGroups(groupsValue == null ? Collections.emptySet() : new HashSet<>(COMA_SPLITTER.splitToList(groupsValue)));
}
return userRegistrar.register(
UserRegistration.builder()
.setUserIdentity(userIdentityBuilder.build())
.setProvider(new SsoIdentityProvider())
.setSource(Source.sso())
.build());
}
@CheckForNull
private String getHeaderValue(Map<String, String> headerValuesByNames, String settingKey) {
return headerValuesByNames.get(settingsByKey.get(settingKey).toLowerCase(Locale.ENGLISH));
}
private static Map<String, String> getHeaders(HttpRequest request) {
Map<String, String> headers = new HashMap<>();
Collections.list(request.getHeaderNames()).forEach(header -> headers.put(header.toLowerCase(Locale.ENGLISH), request.getHeader(header)));
return headers;
}
private boolean hasHeader(Map<String, String> headerValuesByNames, String settingKey) {
return headerValuesByNames.containsKey(settingsByKey.get(settingKey).toLowerCase(Locale.ENGLISH));
}
private static class SsoIdentityProvider implements IdentityProvider {
@Override
public String getKey() {
return SQ_AUTHORITY;
}
@Override
public String getName() {
return getKey();
}
@Override
public Display getDisplay() {
return null;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean allowsUsersToSignUp() {
return true;
}
}
}
| 8,438 | 38.251163 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/IdentityProviderRepository.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.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.sonar.api.server.authentication.IdentityProvider;
public class IdentityProviderRepository {
private static final Predicate<IdentityProvider> IS_ENABLED_FILTER = IdentityProvider::isEnabled;
private static final Function<IdentityProvider, String> TO_NAME = IdentityProvider::getName;
protected final Map<String, IdentityProvider> providersByKey = new HashMap<>();
public IdentityProviderRepository(@Nullable List<IdentityProvider> identityProviders) {
Optional.ofNullable(identityProviders)
.ifPresent(list -> list.forEach(i -> providersByKey.put(i.getKey(), i)));
}
public IdentityProvider getEnabledByKey(String key) {
IdentityProvider identityProvider = providersByKey.get(key);
if (identityProvider != null && IS_ENABLED_FILTER.test(identityProvider)) {
return identityProvider;
}
throw new IllegalArgumentException(String.format("Identity provider %s does not exist or is not enabled", key));
}
public List<IdentityProvider> getAllEnabledAndSorted() {
return providersByKey.values().stream()
.filter(IS_ENABLED_FILTER)
.sorted(Comparator.comparing(TO_NAME))
.toList();
}
}
| 2,285 | 37.745763 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/InitFilter.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;
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.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.web.FilterChain;
import org.sonar.api.web.UrlPattern;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import static java.lang.String.format;
import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
import static org.sonar.server.authentication.AuthenticationError.handleError;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
public class InitFilter extends AuthenticationFilter {
private static final String INIT_CONTEXT = "/sessions/init/";
private final BaseContextFactory baseContextFactory;
private final OAuth2ContextFactory oAuth2ContextFactory;
private final AuthenticationEvent authenticationEvent;
private final OAuth2AuthenticationParameters oAuthOAuth2AuthenticationParameters;
public InitFilter(IdentityProviderRepository identityProviderRepository, BaseContextFactory baseContextFactory,
OAuth2ContextFactory oAuth2ContextFactory, AuthenticationEvent authenticationEvent, OAuth2AuthenticationParameters oAuthOAuth2AuthenticationParameters) {
super(identityProviderRepository);
this.baseContextFactory = baseContextFactory;
this.oAuth2ContextFactory = oAuth2ContextFactory;
this.authenticationEvent = authenticationEvent;
this.oAuthOAuth2AuthenticationParameters = oAuthOAuth2AuthenticationParameters;
}
@Override
public UrlPattern doGetPattern() {
return UrlPattern.create(INIT_CONTEXT + "*");
}
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, INIT_CONTEXT);
if (provider != null) {
handleProvider(request, response, provider);
}
}
private void handleProvider(HttpRequest request, HttpResponse response, IdentityProvider provider) {
try {
if (provider instanceof BaseIdentityProvider baseIdentityProvider) {
handleBaseIdentityProvider(request, response, baseIdentityProvider);
} else if (provider instanceof OAuth2IdentityProvider oAuth2IdentityProvider) {
oAuthOAuth2AuthenticationParameters.init(request, response);
handleOAuth2IdentityProvider(request, response, oAuth2IdentityProvider);
} else {
handleError(request, response, format("Unsupported IdentityProvider class: %s", provider.getClass()));
}
} catch (AuthenticationException e) {
oAuthOAuth2AuthenticationParameters.delete(request, response);
authenticationEvent.loginFailure(request, e);
handleAuthenticationError(e, request, response);
} catch (Exception e) {
oAuthOAuth2AuthenticationParameters.delete(request, response);
handleError(e, request, response, format("Fail to initialize authentication with provider '%s'", provider.getKey()));
}
}
private void handleBaseIdentityProvider(HttpRequest request, HttpResponse response, BaseIdentityProvider provider) {
try {
provider.init(baseContextFactory.newContext(request, response, provider));
} catch (UnauthorizedException e) {
throw AuthenticationException.newBuilder()
.setSource(Source.external(provider))
.setMessage(e.getMessage())
.setPublicMessage(e.getMessage())
.build();
}
}
private void handleOAuth2IdentityProvider(HttpRequest request, HttpResponse response, OAuth2IdentityProvider provider) {
try {
provider.init(oAuth2ContextFactory.newContext(request, response, provider));
} catch (UnauthorizedException e) {
throw AuthenticationException.newBuilder()
.setSource(Source.oauth2(provider))
.setMessage(e.getMessage())
.setPublicMessage(e.getMessage())
.build();
}
}
@Override
public void init() {
// Nothing to do
}
@Override
public void destroy() {
// Nothing to do
}
}
| 5,185 | 41.162602 | 157 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/JwtCsrfVerifier.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.math.BigInteger;
import java.security.SecureRandom;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.server.authentication.event.AuthenticationException;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.sonar.server.authentication.Cookies.SAMESITE_LAX;
import static org.sonar.server.authentication.Cookies.SET_COOKIE;
import static org.sonar.server.authentication.Cookies.newCookieBuilder;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
public class JwtCsrfVerifier {
private static final String CSRF_STATE_COOKIE = "XSRF-TOKEN";
private static final String CSRF_HEADER = "X-XSRF-TOKEN";
private static final Set<String> UPDATE_METHODS = Set.of("POST", "PUT", "DELETE");
private static final String API_URL = "/api";
public String generateState(HttpRequest request, HttpResponse response, int timeoutInSeconds) {
// Create a state token to prevent request forgery.
// Store it in the cookie for later validation.
String state = new BigInteger(130, new SecureRandom()).toString(32);
response.addHeader(SET_COOKIE, newCookieBuilder(request)
.setName(CSRF_STATE_COOKIE)
.setValue(state)
.setHttpOnly(false)
.setExpiry(timeoutInSeconds)
.setSameSite(SAMESITE_LAX)
.toValueString());
return state;
}
public void verifyState(HttpRequest request, @Nullable String csrfState, @Nullable String login) {
if (!shouldRequestBeChecked(request)) {
return;
}
String failureCause = checkCsrf(csrfState, request.getHeader(CSRF_HEADER));
if (failureCause != null) {
throw AuthenticationException.newBuilder()
.setSource(Source.local(Method.JWT))
.setLogin(login)
.setMessage(failureCause)
.build();
}
}
@CheckForNull
private static String checkCsrf(@Nullable String csrfState, @Nullable String stateInHeader) {
if (isBlank(csrfState)) {
return "Missing reference CSRF value";
}
if (!StringUtils.equals(csrfState, stateInHeader)) {
return "Wrong CSFR in request";
}
return null;
}
public void refreshState(HttpRequest request, HttpResponse response, String csrfState, int timeoutInSeconds) {
response.addHeader(SET_COOKIE,
newCookieBuilder(request)
.setName(CSRF_STATE_COOKIE)
.setValue(csrfState)
.setHttpOnly(false)
.setExpiry(timeoutInSeconds)
.setSameSite(SAMESITE_LAX)
.toValueString());
}
public void removeState(HttpRequest request, HttpResponse response) {
response.addCookie(newCookieBuilder(request).setName(CSRF_STATE_COOKIE).setValue(null).setHttpOnly(false).setExpiry(0).build());
}
private static boolean shouldRequestBeChecked(HttpRequest request) {
if (UPDATE_METHODS.contains(request.getMethod())) {
String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");
return path.startsWith(API_URL);
}
return false;
}
}
| 4,155 | 36.441441 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/JwtHttpHandler.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 java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
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.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.SessionTokenDto;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.time.DateUtils.addSeconds;
import static org.sonar.process.ProcessProperties.Property.WEB_SESSION_TIMEOUT_IN_MIN;
import static org.sonar.server.authentication.Cookies.SAMESITE_LAX;
import static org.sonar.server.authentication.Cookies.SET_COOKIE;
import static org.sonar.server.authentication.Cookies.findCookie;
import static org.sonar.server.authentication.Cookies.newCookieBuilder;
import static org.sonar.server.authentication.JwtSerializer.LAST_REFRESH_TIME_PARAM;
@ServerSide
public class JwtHttpHandler {
private static final int SESSION_TIMEOUT_DEFAULT_VALUE_IN_MINUTES = 3 * 24 * 60;
private static final int MAX_SESSION_TIMEOUT_IN_MINUTES = 3 * 30 * 24 * 60;
private static final String JWT_COOKIE = "JWT-SESSION";
private static final String CSRF_JWT_PARAM = "xsrfToken";
// Time after which a user will be disconnected
private static final int SESSION_DISCONNECT_IN_SECONDS = 3 * 30 * 24 * 60 * 60;
// This refresh time is used to refresh the session
// The value must be lower than sessionTimeoutInSeconds
private static final int SESSION_REFRESH_IN_SECONDS = 5 * 60;
private final System2 system2;
private final DbClient dbClient;
private final JwtSerializer jwtSerializer;
// This timeout is used to disconnect the user we he has not browse any page for a while
private final int sessionTimeoutInSeconds;
private final JwtCsrfVerifier jwtCsrfVerifier;
public JwtHttpHandler(System2 system2, DbClient dbClient, Configuration config, JwtSerializer jwtSerializer, JwtCsrfVerifier jwtCsrfVerifier) {
this.jwtSerializer = jwtSerializer;
this.dbClient = dbClient;
this.system2 = system2;
this.sessionTimeoutInSeconds = getSessionTimeoutInSeconds(config);
this.jwtCsrfVerifier = jwtCsrfVerifier;
}
public void generateToken(UserDto user, Map<String, Object> properties, HttpRequest request, HttpResponse response) {
String csrfState = jwtCsrfVerifier.generateState(request, response, sessionTimeoutInSeconds);
long expirationTime = system2.now() + sessionTimeoutInSeconds * 1000L;
SessionTokenDto sessionToken = createSessionToken(user, expirationTime);
String token = jwtSerializer.encode(new JwtSerializer.JwtSession(
user.getUuid(),
sessionToken.getUuid(),
expirationTime,
ImmutableMap.<String, Object>builder()
.putAll(properties)
.put(LAST_REFRESH_TIME_PARAM, system2.now())
.put(CSRF_JWT_PARAM, csrfState)
.build()));
response.addHeader(SET_COOKIE, createJwtSession(request, JWT_COOKIE, token, sessionTimeoutInSeconds));
}
private SessionTokenDto createSessionToken(UserDto user, long expirationTime) {
try (DbSession dbSession = dbClient.openSession(false)) {
SessionTokenDto sessionToken = new SessionTokenDto()
.setUserUuid(user.getUuid())
.setExpirationDate(expirationTime);
dbClient.sessionTokensDao().insert(dbSession, sessionToken);
dbSession.commit();
return sessionToken;
}
}
public void generateToken(UserDto user, HttpRequest request, HttpResponse response) {
generateToken(user, Collections.emptyMap(), request, response);
}
public Optional<UserDto> validateToken(HttpRequest request, HttpResponse response) {
Optional<Token> token = getToken(request, response);
return token.map(Token::getUserDto);
}
public Optional<Token> getToken(HttpRequest request, HttpResponse response) {
Optional<String> encodedToken = getTokenFromCookie(request);
if (!encodedToken.isPresent()) {
return Optional.empty();
}
try (DbSession dbSession = dbClient.openSession(false)) {
return validateToken(dbSession, encodedToken.get(), request, response);
}
}
private static Optional<String> getTokenFromCookie(HttpRequest request) {
Optional<Cookie> jwtCookie = findCookie(JWT_COOKIE, request);
if (jwtCookie.isEmpty()) {
return Optional.empty();
}
Cookie cookie = jwtCookie.get();
String token = cookie.getValue();
if (isEmpty(token)) {
return Optional.empty();
}
return Optional.of(token);
}
private Optional<Token> validateToken(DbSession dbSession, String tokenEncoded, HttpRequest request, HttpResponse response) {
Optional<Claims> claims = jwtSerializer.decode(tokenEncoded);
if (claims.isEmpty()) {
return Optional.empty();
}
Claims token = claims.get();
Optional<SessionTokenDto> sessionToken = dbClient.sessionTokensDao().selectByUuid(dbSession, token.getId());
if (sessionToken.isEmpty()) {
return Optional.empty();
}
// Check on expiration is already done when decoding the JWT token, but here is done a double check with the expiration date from DB.
Date now = new Date(system2.now());
if (now.getTime() > sessionToken.get().getExpirationDate()) {
return Optional.empty();
}
if (now.after(addSeconds(token.getIssuedAt(), SESSION_DISCONNECT_IN_SECONDS))) {
return Optional.empty();
}
jwtCsrfVerifier.verifyState(request, (String) token.get(CSRF_JWT_PARAM), token.getSubject());
if (now.after(addSeconds(getLastRefreshDate(token), SESSION_REFRESH_IN_SECONDS))) {
refreshToken(dbSession, sessionToken.get(), token, request, response);
}
Optional<UserDto> user = selectUserFromUuid(dbSession, token.getSubject());
return user.map(userDto -> new Token(userDto, claims.get()));
}
private static Date getLastRefreshDate(Claims token) {
Long lastFreshTime = (Long) token.get(LAST_REFRESH_TIME_PARAM);
requireNonNull(lastFreshTime, "last refresh time is missing in token");
return new Date(lastFreshTime);
}
private void refreshToken(DbSession dbSession, SessionTokenDto tokenFromDb, Claims tokenFromCookie, HttpRequest request, HttpResponse response) {
long expirationTime = system2.now() + sessionTimeoutInSeconds * 1000L;
String refreshToken = jwtSerializer.refresh(tokenFromCookie, expirationTime);
response.addHeader(SET_COOKIE, createJwtSession(request, JWT_COOKIE, refreshToken, sessionTimeoutInSeconds));
jwtCsrfVerifier.refreshState(request, response, (String) tokenFromCookie.get(CSRF_JWT_PARAM), sessionTimeoutInSeconds);
dbClient.sessionTokensDao().update(dbSession, tokenFromDb.setExpirationDate(expirationTime));
dbSession.commit();
}
public void removeToken(HttpRequest request, HttpResponse response) {
removeSessionToken(request);
response.addCookie(createCookie(request, JWT_COOKIE, null, 0));
jwtCsrfVerifier.removeState(request, response);
}
private void removeSessionToken(HttpRequest request) {
Optional<Cookie> jwtCookie = findCookie(JWT_COOKIE, request);
if (!jwtCookie.isPresent()) {
return;
}
Optional<Claims> claims = jwtSerializer.decode(jwtCookie.get().getValue());
if (!claims.isPresent()) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.sessionTokensDao().deleteByUuid(dbSession, claims.get().getId());
dbSession.commit();
}
}
private static Cookie createCookie(HttpRequest request, String name, @Nullable String value, int expirationInSeconds) {
return newCookieBuilder(request).setName(name).setValue(value).setHttpOnly(true).setExpiry(expirationInSeconds).build();
}
private static String createJwtSession(HttpRequest request, String name, @Nullable String value, int expirationInSeconds) {
return newCookieBuilder(request).setName(name).setValue(value).setHttpOnly(true).setExpiry(expirationInSeconds).setSameSite(SAMESITE_LAX).toValueString();
}
private Optional<UserDto> selectUserFromUuid(DbSession dbSession, String userUuid) {
UserDto user = dbClient.userDao().selectByUuid(dbSession, userUuid);
return Optional.ofNullable(user != null && user.isActive() ? user : null);
}
private static int getSessionTimeoutInSeconds(Configuration config) {
int minutes = config.getInt(WEB_SESSION_TIMEOUT_IN_MIN.getKey()).orElse(SESSION_TIMEOUT_DEFAULT_VALUE_IN_MINUTES);
checkArgument(minutes > SESSION_REFRESH_IN_SECONDS / 60 && minutes <= MAX_SESSION_TIMEOUT_IN_MINUTES,
"Property %s must be higher than 5 minutes and must not be greater than 3 months. Got %s minutes", WEB_SESSION_TIMEOUT_IN_MIN.getKey(),
minutes);
return minutes * 60;
}
public static class Token {
private final UserDto userDto;
private final Map<String, Object> properties;
public Token(UserDto userDto, Map<String, Object> properties) {
this.userDto = userDto;
this.properties = properties;
}
public UserDto getUserDto() {
return userDto;
}
public Map<String, Object> getProperties() {
return properties;
}
}
}
| 10,414 | 40.995968 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/JwtSerializer.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.annotations.VisibleForTesting;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SignatureException;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import javax.annotation.concurrent.Immutable;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.jsonwebtoken.impl.crypto.MacProvider.generateKey;
import static java.util.Objects.requireNonNull;
import static org.sonar.process.ProcessProperties.Property.AUTH_JWT_SECRET;
/**
* This class can be used to encode or decode a JWT token
*/
@ServerSide
public class JwtSerializer implements Startable {
private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
static final String LAST_REFRESH_TIME_PARAM = "lastRefreshTime";
private final Configuration config;
private final System2 system2;
private SecretKey secretKey;
public JwtSerializer(Configuration config, System2 system2) {
this.config = config;
this.system2 = system2;
}
@VisibleForTesting
SecretKey getSecretKey() {
return secretKey;
}
@Override
public void start() {
Optional<String> encodedKey = config.get(AUTH_JWT_SECRET.getKey());
this.secretKey = encodedKey
.map(JwtSerializer::decodeSecretKeyProperty)
.orElseGet(JwtSerializer::generateSecretKey);
}
String encode(JwtSession jwtSession) {
checkIsStarted();
return Jwts.builder()
.addClaims(jwtSession.getProperties())
.claim(LAST_REFRESH_TIME_PARAM, system2.now())
.setId(jwtSession.getSessionTokenUuid())
.setSubject(jwtSession.getUserLogin())
.setIssuedAt(new Date(system2.now()))
.setExpiration(new Date(jwtSession.getExpirationTime()))
.signWith(secretKey, SIGNATURE_ALGORITHM)
.compact();
}
Optional<Claims> decode(String token) {
checkIsStarted();
Claims claims = null;
try {
claims = Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody();
requireNonNull(claims.getId(), "Token id hasn't been found");
requireNonNull(claims.getSubject(), "Token subject hasn't been found");
requireNonNull(claims.getExpiration(), "Token expiration date hasn't been found");
requireNonNull(claims.getIssuedAt(), "Token creation date hasn't been found");
return Optional.of(claims);
} catch (UnsupportedJwtException | ExpiredJwtException | SignatureException e) {
return Optional.empty();
} catch (Exception e) {
throw AuthenticationException.newBuilder()
.setSource(Source.jwt())
.setLogin(claims == null ? null : claims.getSubject())
.setMessage(e.getMessage())
.build();
}
}
String refresh(Claims token, long expirationTime) {
checkIsStarted();
return Jwts.builder()
.setClaims(token)
.claim(LAST_REFRESH_TIME_PARAM, system2.now())
.setExpiration(new Date(expirationTime))
.signWith(secretKey, SIGNATURE_ALGORITHM)
.compact();
}
private static SecretKey generateSecretKey() {
return generateKey(SIGNATURE_ALGORITHM);
}
private static SecretKey decodeSecretKeyProperty(String base64SecretKey) {
byte[] decodedKey = Base64.getDecoder().decode(base64SecretKey);
return new SecretKeySpec(decodedKey, 0, decodedKey.length, SIGNATURE_ALGORITHM.getJcaName());
}
private void checkIsStarted() {
checkNotNull(secretKey, "%s not started", getClass().getName());
}
@Override
public void stop() {
secretKey = null;
}
@Immutable
static class JwtSession {
private final String userLogin;
private final String sessionTokenUuid;
private final long expirationTime;
private final Map<String, Object> properties;
JwtSession(String userLogin, String sessionTokenUuid, long expirationTime) {
this(userLogin, sessionTokenUuid, expirationTime, Collections.emptyMap());
}
JwtSession(String userLogin, String sessionTokenUuid, long expirationTime, Map<String, Object> properties) {
this.userLogin = requireNonNull(userLogin, "User login cannot be null");
this.sessionTokenUuid = requireNonNull(sessionTokenUuid, "Session token UUID cannot be null");
this.expirationTime = expirationTime;
this.properties = properties;
}
String getUserLogin() {
return userLogin;
}
String getSessionTokenUuid() {
return sessionTokenUuid;
}
long getExpirationTime() {
return expirationTime;
}
Map<String, Object> getProperties() {
return properties;
}
}
}
| 6,080 | 32.048913 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/LdapCredentialsAuthentication.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.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Optional;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.auth.ldap.LdapAuthenticationResult;
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.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.trimToNull;
public class LdapCredentialsAuthentication {
private static final Logger LOG = LoggerFactory.getLogger(LdapCredentialsAuthentication.class);
private final Configuration configuration;
private final UserRegistrar userRegistrar;
private final AuthenticationEvent authenticationEvent;
private final LdapAuthenticator ldapAuthenticator;
private final LdapUsersProvider ldapUsersProvider;
private final LdapGroupsProvider ldapGroupsProvider;
private final boolean isLdapAuthActivated;
public LdapCredentialsAuthentication(Configuration configuration,
UserRegistrar userRegistrar, AuthenticationEvent authenticationEvent, LdapRealm ldapRealm) {
this.configuration = configuration;
this.userRegistrar = userRegistrar;
this.authenticationEvent = authenticationEvent;
this.isLdapAuthActivated = ldapRealm.isLdapAuthActivated();
this.ldapAuthenticator = ldapRealm.getAuthenticator();
this.ldapUsersProvider = ldapRealm.getUsersProvider();
this.ldapGroupsProvider = ldapRealm.getGroupsProvider();
}
public Optional<UserDto> authenticate(Credentials credentials, HttpRequest request, AuthenticationEvent.Method method) {
if (isLdapAuthActivated) {
return Optional.of(doAuthenticate(fixCase(credentials), request, method));
}
return Optional.empty();
}
private UserDto doAuthenticate(Credentials credentials, HttpRequest request, AuthenticationEvent.Method method) {
try {
LdapAuthenticator.Context ldapAuthenticatorContext = new LdapAuthenticator.Context(credentials.getLogin(), credentials.getPassword().orElse(null), request);
LdapAuthenticationResult authenticationResult = ldapAuthenticator.doAuthenticate(ldapAuthenticatorContext);
if (!authenticationResult.isSuccess()) {
throw AuthenticationException.newBuilder()
.setSource(realmEventSource(method))
.setLogin(credentials.getLogin())
.setMessage("Realm returned authenticate=false")
.build();
}
LdapUsersProvider.Context ldapUsersProviderContext = new LdapUsersProvider.Context(authenticationResult.getServerKey(), credentials.getLogin(), request);
LdapUserDetails ldapUserDetails = ldapUsersProvider.doGetUserDetails(ldapUsersProviderContext);
if (ldapUserDetails == null) {
throw AuthenticationException.newBuilder()
.setSource(realmEventSource(method))
.setLogin(credentials.getLogin())
.setMessage("No user details")
.build();
}
UserDto userDto = synchronize(credentials.getLogin(), authenticationResult.getServerKey(), ldapUserDetails, request, method);
authenticationEvent.loginSuccess(request, credentials.getLogin(), realmEventSource(method));
return userDto;
} catch (AuthenticationException e) {
throw e;
} catch (Exception e) {
// It seems that with Realm API it's expected to log the error and to not authenticate the user
LOG.error("Error during authentication", e);
throw AuthenticationException.newBuilder()
.setSource(realmEventSource(method))
.setLogin(credentials.getLogin())
.setMessage(e.getMessage())
.build();
}
}
private static Source realmEventSource(AuthenticationEvent.Method method) {
return Source.realm(method, "ldap");
}
private UserDto synchronize(String userLogin, String serverKey, LdapUserDetails userDetails, HttpRequest request, AuthenticationEvent.Method method) {
String name = userDetails.getName();
UserIdentity.Builder userIdentityBuilder = UserIdentity.builder()
.setName(isEmpty(name) ? userLogin : name)
.setEmail(trimToNull(userDetails.getEmail()))
.setProviderLogin(userLogin);
if (ldapGroupsProvider != null) {
LdapGroupsProvider.Context context = new LdapGroupsProvider.Context(serverKey, userLogin, request);
Collection<String> groups = ldapGroupsProvider.doGetGroups(context);
userIdentityBuilder.setGroups(new HashSet<>(groups));
}
return userRegistrar.register(
UserRegistration.builder()
.setUserIdentity(userIdentityBuilder.build())
.setProvider(new LdapIdentityProvider(serverKey))
.setSource(realmEventSource(method))
.build());
}
private Credentials fixCase(Credentials credentials) {
if (configuration.getBoolean("sonar.authenticator.downcase").orElse(false)) {
return new Credentials(credentials.getLogin().toLowerCase(Locale.ENGLISH), credentials.getPassword().orElse(null));
}
return credentials;
}
private static class LdapIdentityProvider implements IdentityProvider {
private final String key;
private LdapIdentityProvider(String ldapServerKey) {
this.key = LdapRealm.LDAP_SECURITY_REALM + "_" + ldapServerKey;
}
@Override
public String getKey() {
return key;
}
@Override
public String getName() {
return getKey();
}
@Override
public Display getDisplay() {
return null;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean allowsUsersToSignUp() {
return true;
}
}
}
| 7,124 | 38.364641 | 162 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/LogOAuthWarning.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.apache.commons.lang.StringUtils;
import org.sonar.api.Startable;
import org.sonar.api.platform.Server;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class LogOAuthWarning implements Startable {
private final Server server;
private final OAuth2IdentityProvider[] providers;
@Autowired(required = false)
public LogOAuthWarning(Server server, OAuth2IdentityProvider[] providers) {
this.server = server;
this.providers = providers;
}
/**
* Used by default by the ioc container when no OAuth2IdentityProvider are present
*/
@Autowired(required = false)
public LogOAuthWarning(Server server) {
this(server, new OAuth2IdentityProvider[0]);
}
@Override
public void start() {
if (providers.length == 0) {
return;
}
String publicRootUrl = server.getPublicRootUrl();
if (StringUtils.startsWithIgnoreCase(publicRootUrl, "http:")) {
LoggerFactory.getLogger(getClass()).warn(
"For security reasons, OAuth authentication should use HTTPS. You should set the property 'Administration > Configuration > Server base URL' to a HTTPS URL.");
}
}
@Override
public void stop() {
// nothing to do
}
}
| 2,195 | 32.784615 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/OAuth2AuthenticationParameters.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.FilterConfig;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
/**
* This class is used to store some parameters during the OAuth2 authentication process, by using a cookie.
*
* Parameters are read from the request during {@link InitFilter#init(FilterConfig)}
* and reset when {@link OAuth2IdentityProvider.CallbackContext#redirectToRequestedPage()} is called.
*/
public interface OAuth2AuthenticationParameters {
void init(HttpRequest request, HttpResponse response);
Optional<String> getReturnTo(HttpRequest request);
void delete(HttpRequest request, HttpResponse response);
}
| 1,639 | 37.139535 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/OAuth2AuthenticationParametersImpl.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.base.Strings;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.sonar.api.server.http.Cookie;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import static java.net.URLDecoder.decode;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Optional.empty;
import static org.sonar.server.authentication.AuthenticationRedirection.encodeMessage;
import static org.sonar.server.authentication.Cookies.findCookie;
import static org.sonar.server.authentication.Cookies.newCookieBuilder;
public class OAuth2AuthenticationParametersImpl implements OAuth2AuthenticationParameters {
private static final String AUTHENTICATION_COOKIE_NAME = "AUTH-PARAMS";
private static final int FIVE_MINUTES_IN_SECONDS = 5 * 60;
private static final Pattern VALID_RETURN_TO = Pattern.compile("^/\\w.*");
/**
* The HTTP parameter that contains the path where the user should be redirect to.
* Please note that the web context is included.
*/
private static final String RETURN_TO_PARAMETER = "return_to";
private static final Type JSON_MAP_TYPE = new TypeToken<HashMap<String, String>>() {
}.getType();
@Override
public void init(HttpRequest request, HttpResponse response) {
String returnTo = request.getParameter(RETURN_TO_PARAMETER);
Map<String, String> parameters = new HashMap<>();
Optional<String> sanitizeRedirectUrl = sanitizeRedirectUrl(returnTo);
sanitizeRedirectUrl.ifPresent(s -> parameters.put(RETURN_TO_PARAMETER, s));
if (parameters.isEmpty()) {
return;
}
response.addCookie(newCookieBuilder(request)
.setName(AUTHENTICATION_COOKIE_NAME)
.setValue(toJson(parameters))
.setHttpOnly(true)
.setExpiry(FIVE_MINUTES_IN_SECONDS)
.build());
}
@Override
public Optional<String> getReturnTo(HttpRequest request) {
return getParameter(request, RETURN_TO_PARAMETER)
.flatMap(OAuth2AuthenticationParametersImpl::sanitizeRedirectUrl);
}
private static Optional<String> getParameter(HttpRequest request, String parameterKey) {
Optional<Cookie> cookie = findCookie(AUTHENTICATION_COOKIE_NAME, request);
if (cookie.isEmpty()) {
return empty();
}
Map<String, String> parameters = fromJson(cookie.get().getValue());
if (parameters.isEmpty()) {
return empty();
}
return Optional.ofNullable(parameters.get(parameterKey));
}
@Override
public void delete(HttpRequest request, HttpResponse response) {
response.addCookie(newCookieBuilder(request)
.setName(AUTHENTICATION_COOKIE_NAME)
.setValue(null)
.setHttpOnly(true)
.setExpiry(0)
.build());
}
private static String toJson(Map<String, String> map) {
Gson gson = new GsonBuilder().create();
return encodeMessage(gson.toJson(map));
}
private static Map<String, String> fromJson(String json) {
Gson gson = new GsonBuilder().create();
try {
return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
/**
* This sanitization has been inspired by 'IsUrlLocalToHost()' method in
* https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/preventing-open-redirection-attacks
*/
private static Optional<String> sanitizeRedirectUrl(@Nullable String url) {
if (Strings.isNullOrEmpty(url)) {
return empty();
}
String sanitizedUrl = url.trim();
boolean isValidUrl = VALID_RETURN_TO.matcher(sanitizedUrl).matches();
if (!isValidUrl) {
return empty();
}
return Optional.of(sanitizedUrl);
}
}
| 4,861 | 34.489051 | 102 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/OAuth2CallbackFilter.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.IdentityProvider;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.web.FilterChain;
import org.sonar.api.web.UrlPattern;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.user.ThreadLocalUserSession;
import static java.lang.String.format;
import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
import static org.sonar.server.authentication.AuthenticationError.handleError;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
public class OAuth2CallbackFilter extends AuthenticationFilter {
private final OAuth2ContextFactory oAuth2ContextFactory;
private final AuthenticationEvent authenticationEvent;
private final OAuth2AuthenticationParameters oauth2Parameters;
private final ThreadLocalUserSession threadLocalUserSession;
public OAuth2CallbackFilter(IdentityProviderRepository identityProviderRepository, OAuth2ContextFactory oAuth2ContextFactory,
AuthenticationEvent authenticationEvent, OAuth2AuthenticationParameters oauth2Parameters, ThreadLocalUserSession threadLocalUserSession) {
super(identityProviderRepository);
this.oAuth2ContextFactory = oAuth2ContextFactory;
this.authenticationEvent = authenticationEvent;
this.oauth2Parameters = oauth2Parameters;
this.threadLocalUserSession = threadLocalUserSession;
}
@Override
public UrlPattern doGetPattern() {
return UrlPattern.create(CALLBACK_PATH + "*");
}
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, CALLBACK_PATH);
if (provider != null) {
handleProvider(request, response, provider);
}
}
private void handleProvider(HttpRequest request, HttpResponse response, IdentityProvider provider) {
try {
if (provider instanceof OAuth2IdentityProvider oAuth2IdentityProvider) {
handleOAuth2Provider(request, response, oAuth2IdentityProvider);
} else {
handleError(request, response, format("Not an OAuth2IdentityProvider: %s", provider.getClass()));
}
} catch (AuthenticationException e) {
oauth2Parameters.delete(request, response);
authenticationEvent.loginFailure(request, e);
handleAuthenticationError(e, request, response);
} catch (Exception e) {
oauth2Parameters.delete(request, response);
handleError(e, request, response, format("Fail to callback authentication with '%s'", provider.getKey()));
}
}
private void handleOAuth2Provider(HttpRequest request, HttpResponse response, OAuth2IdentityProvider oAuth2Provider) {
OAuth2IdentityProvider.CallbackContext context = oAuth2ContextFactory.newCallback(request, response, oAuth2Provider);
try {
oAuth2Provider.callback(context);
} catch (UnauthorizedException e) {
throw AuthenticationException.newBuilder()
.setSource(Source.oauth2(oAuth2Provider))
.setMessage(e.getMessage())
.setPublicMessage(e.getMessage())
.build();
}
if (threadLocalUserSession.hasSession()) {
authenticationEvent.loginSuccess(request, threadLocalUserSession.getLogin(), Source.oauth2(oAuth2Provider));
} else {
throw AuthenticationException.newBuilder()
.setSource(Source.oauth2(oAuth2Provider))
.setMessage("Plugin did not call authenticate")
.build();
}
}
@Override
public void init() {
// Nothing to do
}
@Override
public void destroy() {
// Nothing to do
}
}
| 4,774 | 40.163793 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/OAuth2ContextFactory.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.io.IOException;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.sonar.api.platform.Server;
import org.sonar.api.server.ServerSide;
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.authentication.event.AuthenticationEvent;
import org.sonar.server.http.JavaxHttpRequest;
import org.sonar.server.http.JavaxHttpResponse;
import org.sonar.server.user.ThreadLocalUserSession;
import org.sonar.server.user.UserSessionFactory;
import static java.lang.String.format;
import static org.sonar.server.authentication.OAuth2CallbackFilter.CALLBACK_PATH;
@ServerSide
public class OAuth2ContextFactory {
private final ThreadLocalUserSession threadLocalUserSession;
private final UserRegistrar userRegistrar;
private final Server server;
private final OAuthCsrfVerifier csrfVerifier;
private final JwtHttpHandler jwtHttpHandler;
private final UserSessionFactory userSessionFactory;
private final OAuth2AuthenticationParameters oAuthParameters;
public OAuth2ContextFactory(ThreadLocalUserSession threadLocalUserSession, UserRegistrar userRegistrar, Server server,
OAuthCsrfVerifier csrfVerifier, JwtHttpHandler jwtHttpHandler, UserSessionFactory userSessionFactory, OAuth2AuthenticationParameters oAuthParameters) {
this.threadLocalUserSession = threadLocalUserSession;
this.userRegistrar = userRegistrar;
this.server = server;
this.csrfVerifier = csrfVerifier;
this.jwtHttpHandler = jwtHttpHandler;
this.userSessionFactory = userSessionFactory;
this.oAuthParameters = oAuthParameters;
}
public OAuth2IdentityProvider.InitContext newContext(HttpRequest request, HttpResponse response, OAuth2IdentityProvider identityProvider) {
return new OAuthContextImpl(request, response, identityProvider);
}
public OAuth2IdentityProvider.CallbackContext newCallback(HttpRequest request, HttpResponse response, OAuth2IdentityProvider identityProvider) {
return new OAuthContextImpl(request, response, identityProvider);
}
@NotNull
public String generateCallbackUrl(String identityProviderKey) {
return server.getPublicRootUrl() + CALLBACK_PATH + identityProviderKey;
}
public class OAuthContextImpl implements OAuth2IdentityProvider.InitContext, OAuth2IdentityProvider.CallbackContext {
private final HttpRequest request;
private final HttpResponse response;
private final OAuth2IdentityProvider identityProvider;
public OAuthContextImpl(HttpRequest request, HttpResponse response, OAuth2IdentityProvider identityProvider) {
this.request = request;
this.response = response;
this.identityProvider = identityProvider;
}
@Override
public String getCallbackUrl() {
return generateCallbackUrl(identityProvider.getKey());
}
@Override
public String generateCsrfState() {
return csrfVerifier.generateState(request, response);
}
@Override
public HttpRequest getHttpRequest() {
return request;
}
@Override
public HttpResponse getHttpResponse() {
return response;
}
@Override
public HttpServletRequest getRequest() {
return ((JavaxHttpRequest) request).getDelegate();
}
@Override
public HttpServletResponse getResponse() {
return ((JavaxHttpResponse) response).getDelegate();
}
@Override
public void redirectTo(String url) {
try {
response.sendRedirect(url);
} catch (IOException e) {
throw new IllegalStateException(format("Fail to redirect to %s", url), e);
}
}
@Override
public void verifyCsrfState() {
csrfVerifier.verifyState(request, response, identityProvider);
}
@Override
public void verifyCsrfState(String parameterName) {
csrfVerifier.verifyState(request, response, identityProvider, parameterName);
}
@Override
public void redirectToRequestedPage() {
try {
Optional<String> redirectTo = oAuthParameters.getReturnTo(request);
oAuthParameters.delete(request, response);
getHttpResponse().sendRedirect(redirectTo.orElse(server.getContextPath() + "/"));
} catch (IOException e) {
throw new IllegalStateException("Fail to redirect to requested page", e);
}
}
@Override
public void authenticate(UserIdentity userIdentity) {
UserDto userDto = userRegistrar.register(
UserRegistration.builder()
.setUserIdentity(userIdentity)
.setProvider(identityProvider)
.setSource(AuthenticationEvent.Source.oauth2(identityProvider))
.build());
jwtHttpHandler.generateToken(userDto, request, response);
threadLocalUserSession.set(userSessionFactory.create(userDto));
}
}
}
| 5,940 | 35.447853 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/OAuthCsrfVerifier.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.math.BigInteger;
import java.security.SecureRandom;
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.AuthenticationException;
import static java.lang.String.format;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.sonar.server.authentication.Cookies.findCookie;
import static org.sonar.server.authentication.Cookies.newCookieBuilder;
import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
public class OAuthCsrfVerifier {
private static final String CSRF_STATE_COOKIE = "OAUTHSTATE";
private static final String DEFAULT_STATE_PARAMETER_NAME = "state";
public String generateState(HttpRequest request, HttpResponse response) {
// Create a state token to prevent request forgery.
// Store it in the session for later validation.
String state = new BigInteger(130, new SecureRandom()).toString(32);
response.addCookie(newCookieBuilder(request).setName(CSRF_STATE_COOKIE).setValue(sha256Hex(state)).setHttpOnly(true).setExpiry(-1).build());
return state;
}
public void verifyState(HttpRequest request, HttpResponse response, OAuth2IdentityProvider provider) {
verifyState(request, response, provider, DEFAULT_STATE_PARAMETER_NAME);
}
public void verifyState(HttpRequest request, HttpResponse response, OAuth2IdentityProvider provider, String parameterName) {
Cookie cookie = findCookie(CSRF_STATE_COOKIE, request)
.orElseThrow(AuthenticationException.newBuilder()
.setSource(Source.oauth2(provider))
.setMessage(format("Cookie '%s' is missing", CSRF_STATE_COOKIE))::build);
String hashInCookie = cookie.getValue();
// remove cookie
response.addCookie(newCookieBuilder(request).setName(CSRF_STATE_COOKIE).setValue(null).setHttpOnly(true).setExpiry(0).build());
String stateInRequest = request.getParameter(parameterName);
if (isBlank(stateInRequest) || !sha256Hex(stateInRequest).equals(hashInCookie)) {
throw AuthenticationException.newBuilder()
.setSource(Source.oauth2(provider))
.setMessage("CSRF state value is invalid")
.build();
}
}
}
| 3,282 | 43.364865 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/RequestAuthenticator.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.ServerSide;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.server.user.UserSession;
@ServerSide
public interface RequestAuthenticator {
/**
* @throws org.sonar.server.authentication.event.AuthenticationException if user is not authenticated
*/
UserSession authenticate(HttpRequest request, HttpResponse response);
}
| 1,305 | 35.277778 | 103 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/RequestAuthenticatorImpl.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.function.Function;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.db.user.UserDto;
import org.sonar.server.user.UserSession;
import org.sonar.server.user.UserSessionFactory;
import org.sonar.server.usertoken.UserTokenAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import static java.util.Objects.nonNull;
import static org.sonar.server.authentication.UserAuthResult.AuthType.BASIC;
import static org.sonar.server.authentication.UserAuthResult.AuthType.GITHUB_WEBHOOK;
import static org.sonar.server.authentication.UserAuthResult.AuthType.JWT;
import static org.sonar.server.authentication.UserAuthResult.AuthType.SSO;
import static org.sonar.server.authentication.UserAuthResult.AuthType.TOKEN;
public class RequestAuthenticatorImpl implements RequestAuthenticator {
private final JwtHttpHandler jwtHttpHandler;
private final BasicAuthentication basicAuthentication;
private final UserTokenAuthentication userTokenAuthentication;
private final HttpHeadersAuthentication httpHeadersAuthentication;
private final GithubWebhookAuthentication githubWebhookAuthentication;
private final UserSessionFactory userSessionFactory;
@Autowired(required = false)
public RequestAuthenticatorImpl(JwtHttpHandler jwtHttpHandler, BasicAuthentication basicAuthentication, UserTokenAuthentication userTokenAuthentication,
HttpHeadersAuthentication httpHeadersAuthentication,
GithubWebhookAuthentication githubWebhookAuthentication, UserSessionFactory userSessionFactory) {
this.jwtHttpHandler = jwtHttpHandler;
this.basicAuthentication = basicAuthentication;
this.userTokenAuthentication = userTokenAuthentication;
this.httpHeadersAuthentication = httpHeadersAuthentication;
this.githubWebhookAuthentication = githubWebhookAuthentication;
this.userSessionFactory = userSessionFactory;
}
@Autowired(required = false)
public RequestAuthenticatorImpl(JwtHttpHandler jwtHttpHandler, BasicAuthentication basicAuthentication, UserTokenAuthentication userTokenAuthentication,
HttpHeadersAuthentication httpHeadersAuthentication,
UserSessionFactory userSessionFactory, GithubWebhookAuthentication githubWebhookAuthentication) {
this(jwtHttpHandler, basicAuthentication, userTokenAuthentication, httpHeadersAuthentication, githubWebhookAuthentication, userSessionFactory);
}
@Override
public UserSession authenticate(HttpRequest request, HttpResponse response) {
UserAuthResult userAuthResult = loadUser(request, response);
if (nonNull(userAuthResult.getUserDto())) {
if (TOKEN.equals(userAuthResult.getAuthType())) {
return userSessionFactory.create(userAuthResult.getUserDto(), userAuthResult.getTokenDto());
}
return userSessionFactory.create(userAuthResult.getUserDto());
} else if (GITHUB_WEBHOOK.equals(userAuthResult.getAuthType())) {
return userSessionFactory.createGithubWebhookUserSession();
}
return userSessionFactory.createAnonymous();
}
private UserAuthResult loadUser(HttpRequest request, HttpResponse response) {
Function<UserAuthResult.AuthType, Function<UserDto, UserAuthResult>> createUserAuthResult = type -> userDto -> new UserAuthResult(userDto, type);
// SSO authentication should come first in order to update JWT if user from header is not the same is user from JWT
return httpHeadersAuthentication.authenticate(request, response).map(createUserAuthResult.apply(SSO))
.orElseGet(() -> jwtHttpHandler.validateToken(request, response).map(createUserAuthResult.apply(JWT))
.orElseGet(() -> userTokenAuthentication.authenticate(request)
.or(() -> githubWebhookAuthentication.authenticate(request))
.or(() -> basicAuthentication.authenticate(request).map(createUserAuthResult.apply(BASIC)))
.orElseGet(UserAuthResult::new)));
}
}
| 4,813 | 51.326087 | 154 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/ResetPasswordFilter.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.io.IOException;
import java.util.Set;
import org.sonar.api.impl.ws.StaticResources;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.web.FilterChain;
import org.sonar.api.web.HttpFilter;
import org.sonar.api.web.UrlPattern;
import org.sonar.server.user.ThreadLocalUserSession;
import static org.sonar.server.authentication.AuthenticationRedirection.redirectTo;
public class ResetPasswordFilter extends HttpFilter {
private static final String RESET_PASSWORD_PATH = "/account/reset_password";
private static final Set<String> SKIPPED_URLS = Set.of(
RESET_PASSWORD_PATH,
"/batch/*", "/api/*", "/api/v2/*");
private final ThreadLocalUserSession userSession;
public ResetPasswordFilter(ThreadLocalUserSession userSession) {
this.userSession = userSession;
}
@Override
public UrlPattern doGetPattern() {
return UrlPattern.builder()
.includes("/*")
.excludes(StaticResources.patterns())
.excludes(SKIPPED_URLS)
.build();
}
@Override
public void init() {
// nothing to do
}
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
if (userSession.hasSession() && userSession.isLoggedIn() && userSession.shouldResetPassword()) {
redirectTo(response, request.getContextPath() + RESET_PASSWORD_PATH);
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
// nothing to do
}
}
| 2,415 | 31.213333 | 106 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/SafeModeUserSession.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.Collection;
import java.util.Collections;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.user.GroupDto;
import org.sonar.server.user.AbstractUserSession;
@Immutable
public class SafeModeUserSession extends AbstractUserSession {
@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;
}
@CheckForNull
@Override
public String getLogin() {
return null;
}
@CheckForNull
@Override
public String getUuid() {
return null;
}
@CheckForNull
@Override
public String getName() {
return null;
}
@Override
public Collection<GroupDto> getGroups() {
return Collections.emptyList();
}
@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 false;
}
@Override
public boolean isSystemAdministrator() {
return false;
}
@Override
public boolean isActive() {
return false;
}
}
| 2,705 | 23.160714 | 98 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/SamlValidationCspHeaders.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.math.BigInteger;
import java.security.SecureRandom;
import java.util.List;
import org.sonar.api.server.http.HttpResponse;
public class SamlValidationCspHeaders {
private SamlValidationCspHeaders() {
throw new IllegalStateException("Utility class, cannot be instantiated");
}
public static String addCspHeadersWithNonceToResponse(HttpResponse httpResponse) {
final String nonce = getNonce();
List<String> cspPolicies = List.of(
"default-src 'self'",
"base-uri 'none'",
"connect-src 'self' http: https:",
"img-src * data: blob:",
"object-src 'none'",
"script-src 'nonce-" + nonce + "'",
"style-src 'self' 'unsafe-inline'",
"worker-src 'none'");
String policies = String.join("; ", cspPolicies).trim();
List<String> cspHeaders = List.of("Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP");
cspHeaders.forEach(header -> httpResponse.setHeader(header, policies));
return nonce;
}
private static String getNonce() {
// this code is the same as in org.sonar.server.authentication.JwtCsrfVerifier.generateState
return new BigInteger(130, new SecureRandom()).toString(32);
}
}
| 2,087 | 35.631579 | 110 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/SamlValidationRedirectionFilter.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.io.Resources;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.internal.apachecommons.lang.StringEscapeUtils;
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 org.sonar.api.web.HttpFilter;
import org.sonar.api.web.UrlPattern;
import static org.sonar.server.authentication.AuthenticationFilter.CALLBACK_PATH;
public class SamlValidationRedirectionFilter extends HttpFilter {
public static final String VALIDATION_RELAY_STATE = "validation-query";
public static final String SAML_VALIDATION_CONTROLLER_CONTEXT = "saml";
public static final String SAML_VALIDATION_KEY = "validation";
private static final String RELAY_STATE_PARAMETER = "RelayState";
private static final String SAML_RESPONSE_PARAMETER = "SAMLResponse";
private String redirectionPageTemplate;
private final Server server;
public SamlValidationRedirectionFilter(Server server) {
this.server = server;
}
@Override
public UrlPattern doGetPattern() {
return UrlPattern.create(CALLBACK_PATH + "saml");
}
@Override
public void init() {
this.redirectionPageTemplate = extractTemplate("validation-redirection.html");
}
String extractTemplate(String templateLocation) {
try {
URL url = Resources.getResource(templateLocation);
return Resources.toString(url, StandardCharsets.UTF_8);
} catch (IOException | IllegalArgumentException e) {
throw new IllegalStateException("Cannot read the template " + templateLocation, e);
}
}
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
String relayState = request.getParameter(RELAY_STATE_PARAMETER);
if (isSamlValidation(relayState)) {
URI redirectionEndpointUrl = URI.create(server.getContextPath() + "/")
.resolve(SAML_VALIDATION_CONTROLLER_CONTEXT + "/")
.resolve(SAML_VALIDATION_KEY);
String samlResponse = StringEscapeUtils.escapeHtml(request.getParameter(SAML_RESPONSE_PARAMETER));
String csrfToken = getCsrfTokenFromRelayState(relayState);
String nonce = SamlValidationCspHeaders.addCspHeadersWithNonceToResponse(response);
String template = StringUtils.replaceEachRepeatedly(redirectionPageTemplate,
new String[]{"%NONCE%", "%WEB_CONTEXT%", "%VALIDATION_URL%", "%SAML_RESPONSE%", "%CSRF_TOKEN%"},
new String[]{nonce, server.getContextPath(), redirectionEndpointUrl.toString(), samlResponse, csrfToken});
response.setContentType("text/html");
response.getWriter().print(template);
return;
}
chain.doFilter(request, response);
}
private static boolean isSamlValidation(@Nullable String relayState) {
if (relayState != null) {
return VALIDATION_RELAY_STATE.equals(relayState.split("/")[0]) && !getCsrfTokenFromRelayState(relayState).isEmpty();
}
return false;
}
private static String getCsrfTokenFromRelayState(@Nullable String relayState) {
if (relayState != null && relayState.contains("/")) {
return StringEscapeUtils.escapeHtml(relayState.split("/")[1]);
}
return "";
}
}
| 4,276 | 37.531532 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserAuthResult.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.UserTokenDto;
public class UserAuthResult {
public enum AuthType {
SSO,
JWT,
TOKEN,
GITHUB_WEBHOOK,
BASIC
}
UserDto userDto;
UserTokenDto tokenDto;
AuthType authType;
public UserAuthResult() {
}
public UserAuthResult(UserDto userDto, AuthType authType) {
this.userDto = userDto;
this.authType = authType;
}
public UserAuthResult(UserDto userDto, UserTokenDto tokenDto, AuthType authType) {
this.userDto = userDto;
this.tokenDto = tokenDto;
this.authType = authType;
}
private UserAuthResult(AuthType authType) {
this.authType = authType;
}
public static UserAuthResult withGithubWebhook() {
return new UserAuthResult(AuthType.GITHUB_WEBHOOK);
}
public UserDto getUserDto() {
return userDto;
}
public AuthType getAuthType() {
return authType;
}
public UserTokenDto getTokenDto() {
return tokenDto;
}
}
| 1,858 | 24.465753 | 84 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserLastConnectionDatesUpdater.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.UserTokenDto;
public interface UserLastConnectionDatesUpdater {
void updateLastConnectionDateIfNeeded(UserDto user);
void updateLastConnectionDateIfNeeded(UserTokenDto userToken);
}
| 1,133 | 35.580645 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserLastConnectionDatesUpdaterImpl.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.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
public class UserLastConnectionDatesUpdaterImpl implements UserLastConnectionDatesUpdater {
private static final long ONE_HOUR_IN_MILLISECONDS = 60 * 60 * 1000L;
private final DbClient dbClient;
private final System2 system2;
public UserLastConnectionDatesUpdaterImpl(DbClient dbClient, System2 system2) {
this.dbClient = dbClient;
this.system2 = system2;
}
@Override
public void updateLastConnectionDateIfNeeded(UserDto user) {
Long lastConnectionDate = user.getLastConnectionDate();
long now = system2.now();
if (doesNotRequireUpdate(lastConnectionDate, now)) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.userDao().update(dbSession, user.setLastConnectionDate(now), false);
dbSession.commit();
}
}
@Override
public void updateLastConnectionDateIfNeeded(UserTokenDto userToken) {
Long lastConnectionDate = userToken.getLastConnectionDate();
long now = system2.now();
if (doesNotRequireUpdate(lastConnectionDate, now)) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.userTokenDao().updateWithoutAudit(dbSession, userToken.setLastConnectionDate(now));
userToken.setLastConnectionDate(now);
dbSession.commit();
}
}
private static boolean doesNotRequireUpdate(@Nullable Long lastConnectionDate, long now) {
// Update date only once per hour in order to decrease pressure on DB
return lastConnectionDate != null && (now - lastConnectionDate) < ONE_HOUR_IN_MILLISECONDS;
}
}
| 2,663 | 35.493151 | 98 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserRegistrar.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;
public interface UserRegistrar {
UserDto register(UserRegistration registration);
}
| 1,008 | 33.793103 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserRegistrarImpl.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.Sets;
import java.util.ArrayList;
import java.util.Collection;
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.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserGroupDto;
import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.user.ExternalIdentity;
import org.sonar.server.user.NewUser;
import org.sonar.server.user.UpdateUser;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static org.sonar.server.user.UserSession.IdentityProvider.SONARQUBE;
public class UserRegistrarImpl implements UserRegistrar {
public static final String SQ_AUTHORITY = "sonarqube";
public static final String LDAP_PROVIDER_PREFIX = "LDAP_";
private static final Logger LOGGER = LoggerFactory.getLogger(UserRegistrarImpl.class);
public static final String GITHUB_PROVIDER = "github";
public static final String GITLAB_PROVIDER = "gitlab";
private final DbClient dbClient;
private final UserUpdater userUpdater;
private final DefaultGroupFinder defaultGroupFinder;
private final ManagedInstanceService managedInstanceService;
public UserRegistrarImpl(DbClient dbClient, UserUpdater userUpdater, DefaultGroupFinder defaultGroupFinder,
ManagedInstanceService managedInstanceService) {
this.dbClient = dbClient;
this.userUpdater = userUpdater;
this.defaultGroupFinder = defaultGroupFinder;
this.managedInstanceService = managedInstanceService;
}
@Override
public UserDto register(UserRegistration registration) {
try (DbSession dbSession = dbClient.openSession(false)) {
UserDto userDto = getUser(dbSession, registration.getUserIdentity(), registration.getProvider(), registration.getSource());
if (userDto == null) {
return registerNewUser(dbSession, null, registration);
}
if (!userDto.isActive()) {
return registerNewUser(dbSession, userDto, registration);
}
return registerExistingUser(dbSession, userDto, registration);
}
}
@CheckForNull
private UserDto getUser(DbSession dbSession, UserIdentity userIdentity, IdentityProvider provider, Source source) {
// First, try to authenticate using the external ID
// Then, try with the external login, for instance when external ID has changed or is not used by the provider
return retrieveUserByExternalIdAndIdentityProvider(dbSession, userIdentity, provider)
.or(() -> retrieveUserByExternalLoginAndIdentityProvider(dbSession, userIdentity, provider, source))
.or(() -> retrieveUserByLogin(dbSession, userIdentity, provider))
.orElse(null);
}
private Optional<UserDto> retrieveUserByExternalIdAndIdentityProvider(DbSession dbSession, UserIdentity userIdentity, IdentityProvider provider) {
return Optional.ofNullable(dbClient.userDao().selectByExternalIdAndIdentityProvider(dbSession, getProviderIdOrProviderLogin(userIdentity), provider.getKey()));
}
private Optional<UserDto> retrieveUserByExternalLoginAndIdentityProvider(DbSession dbSession, UserIdentity userIdentity, IdentityProvider provider, Source source) {
return Optional.ofNullable(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, userIdentity.getProviderLogin(), provider.getKey()))
.filter(user -> validateAlmSpecificData(user, provider.getKey(), userIdentity, source));
}
private Optional<UserDto> retrieveUserByLogin(DbSession dbSession, UserIdentity userIdentity, IdentityProvider provider) {
return Optional.ofNullable(dbClient.userDao().selectByLogin(dbSession, userIdentity.getProviderLogin()))
.filter(user -> shouldPerformLdapIdentityProviderMigration(user, provider));
}
private static boolean shouldPerformLdapIdentityProviderMigration(UserDto user, IdentityProvider identityProvider) {
boolean isLdapIdentityProvider = identityProvider.getKey().startsWith(LDAP_PROVIDER_PREFIX);
boolean hasSonarQubeExternalIdentityProvider = SONARQUBE.getKey().equals(user.getExternalIdentityProvider());
return isLdapIdentityProvider && hasSonarQubeExternalIdentityProvider && !user.isLocal();
}
private static boolean validateAlmSpecificData(UserDto user, String key, UserIdentity userIdentity, Source source) {
// All gitlab users have an external ID, so the other two authentication methods should never be used
if (GITLAB_PROVIDER.equals(key)) {
throw failAuthenticationException(userIdentity, source);
}
if (GITHUB_PROVIDER.equals(key)) {
validateEmailToAvoidLoginRecycling(userIdentity, user, source);
}
return true;
}
private static void validateEmailToAvoidLoginRecycling(UserIdentity userIdentity, UserDto user, Source source) {
String dbEmail = user.getEmail();
if (dbEmail == null) {
return;
}
String externalEmail = userIdentity.getEmail();
if (!dbEmail.equalsIgnoreCase(externalEmail)) {
LOGGER.warn("User with login '{}' tried to login with email '{}' which doesn't match the email on record '{}'", userIdentity.getProviderLogin(), externalEmail, dbEmail);
throw failAuthenticationException(userIdentity, source);
}
}
private static AuthenticationException failAuthenticationException(UserIdentity userIdentity, Source source) {
String message = String.format("Failed to authenticate with login '%s'", userIdentity.getProviderLogin());
return authException(userIdentity, source, message, message);
}
private static AuthenticationException authException(UserIdentity userIdentity, Source source, String message, String publicMessage) {
return AuthenticationException.newBuilder()
.setSource(source)
.setLogin(userIdentity.getProviderLogin())
.setMessage(message)
.setPublicMessage(publicMessage)
.build();
}
private UserDto registerNewUser(DbSession dbSession, @Nullable UserDto disabledUser, UserRegistration authenticatorParameters) {
blockUnmanagedUserCreationOnManagedInstance(authenticatorParameters);
Optional<UserDto> otherUserToIndex = detectEmailUpdate(dbSession, authenticatorParameters, disabledUser != null ? disabledUser.getUuid() : null);
NewUser newUser = createNewUser(authenticatorParameters);
if (disabledUser == null) {
return userUpdater.createAndCommit(dbSession, newUser, beforeCommit(dbSession, authenticatorParameters), toArray(otherUserToIndex));
}
return userUpdater.reactivateAndCommit(dbSession, disabledUser, newUser, beforeCommit(dbSession, authenticatorParameters), toArray(otherUserToIndex));
}
private void blockUnmanagedUserCreationOnManagedInstance(UserRegistration userRegistration) {
if (managedInstanceService.isInstanceExternallyManaged() && !userRegistration.managed()) {
throw AuthenticationException.newBuilder()
.setMessage("No account found for this user. As the instance is managed, make sure to provision the user from your IDP.")
.setPublicMessage("You have no account on SonarQube. Please make sure with your administrator that your account is provisioned.")
.setLogin(userRegistration.getUserIdentity().getProviderLogin())
.setSource(userRegistration.getSource())
.build();
}
}
private UserDto registerExistingUser(DbSession dbSession, UserDto userDto, UserRegistration authenticatorParameters) {
UpdateUser update = new UpdateUser()
.setEmail(authenticatorParameters.getUserIdentity().getEmail())
.setName(authenticatorParameters.getUserIdentity().getName())
.setExternalIdentity(new ExternalIdentity(
authenticatorParameters.getProvider().getKey(),
authenticatorParameters.getUserIdentity().getProviderLogin(),
authenticatorParameters.getUserIdentity().getProviderId()));
Optional<UserDto> otherUserToIndex = detectEmailUpdate(dbSession, authenticatorParameters, userDto.getUuid());
userUpdater.updateAndCommit(dbSession, userDto, update, beforeCommit(dbSession, authenticatorParameters), toArray(otherUserToIndex));
return userDto;
}
private Consumer<UserDto> beforeCommit(DbSession dbSession, UserRegistration authenticatorParameters) {
return user -> syncGroups(dbSession, authenticatorParameters.getUserIdentity(), user);
}
private Optional<UserDto> detectEmailUpdate(DbSession dbSession, UserRegistration authenticatorParameters, @Nullable String authenticatingUserUuid) {
String email = authenticatorParameters.getUserIdentity().getEmail();
if (email == null) {
return Optional.empty();
}
List<UserDto> existingUsers = dbClient.userDao().selectByEmail(dbSession, email);
if (existingUsers.isEmpty()) {
return Optional.empty();
}
if (existingUsers.size() > 1) {
throw generateExistingEmailError(authenticatorParameters, email);
}
UserDto existingUser = existingUsers.get(0);
if (existingUser == null || existingUser.getUuid().equals(authenticatingUserUuid)) {
return Optional.empty();
}
throw generateExistingEmailError(authenticatorParameters, email);
}
private void syncGroups(DbSession dbSession, UserIdentity userIdentity, UserDto userDto) {
if (!userIdentity.shouldSyncGroups()) {
return;
}
String userLogin = userDto.getLogin();
Set<String> userGroups = new HashSet<>(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(userLogin)).get(userLogin));
Set<String> identityGroups = userIdentity.getGroups();
LOGGER.debug("List of groups returned by the identity provider '{}'", identityGroups);
Collection<String> groupsToAdd = Sets.difference(identityGroups, userGroups);
Collection<String> groupsToRemove = Sets.difference(userGroups, identityGroups);
Collection<String> allGroups = new ArrayList<>(groupsToAdd);
allGroups.addAll(groupsToRemove);
Map<String, GroupDto> groupsByName = dbClient.groupDao().selectByNames(dbSession, allGroups)
.stream()
.collect(Collectors.toMap(GroupDto::getName, Function.identity()));
addGroups(dbSession, userDto, groupsToAdd, groupsByName);
removeGroups(dbSession, userDto, groupsToRemove, groupsByName);
}
private void addGroups(DbSession dbSession, UserDto userDto, Collection<String> groupsToAdd, Map<String, GroupDto> groupsByName) {
groupsToAdd.stream().map(groupsByName::get).filter(Objects::nonNull).forEach(
groupDto -> {
LOGGER.debug("Adding user '{}' to group '{}'", userDto.getLogin(), groupDto.getName());
dbClient.userGroupDao().insert(dbSession, new UserGroupDto().setGroupUuid(groupDto.getUuid()).setUserUuid(userDto.getUuid()),
groupDto.getName(), userDto.getLogin());
});
}
private void removeGroups(DbSession dbSession, UserDto userDto, Collection<String> groupsToRemove, Map<String, GroupDto> groupsByName) {
Optional<GroupDto> defaultGroup = getDefaultGroup(dbSession);
groupsToRemove.stream().map(groupsByName::get)
.filter(Objects::nonNull)
// user should be member of default group only when organizations are disabled, as the IdentityProvider API doesn't handle yet
// organizations
.filter(group -> defaultGroup.isEmpty() || !group.getUuid().equals(defaultGroup.get().getUuid()))
.forEach(groupDto -> {
LOGGER.debug("Removing group '{}' from user '{}'", groupDto.getName(), userDto.getLogin());
dbClient.userGroupDao().delete(dbSession, groupDto, userDto);
});
}
private Optional<GroupDto> getDefaultGroup(DbSession dbSession) {
return Optional.of(defaultGroupFinder.findDefaultGroup(dbSession));
}
private static NewUser createNewUser(UserRegistration authenticatorParameters) {
String identityProviderKey = authenticatorParameters.getProvider().getKey();
if (!authenticatorParameters.getProvider().allowsUsersToSignUp()) {
throw AuthenticationException.newBuilder()
.setSource(authenticatorParameters.getSource())
.setLogin(authenticatorParameters.getUserIdentity().getProviderLogin())
.setMessage(format("User signup disabled for provider '%s'", identityProviderKey))
.setPublicMessage(format("'%s' users are not allowed to sign up", identityProviderKey))
.build();
}
String providerLogin = authenticatorParameters.getUserIdentity().getProviderLogin();
return NewUser.builder()
.setLogin(SQ_AUTHORITY.equals(identityProviderKey) ? providerLogin : null)
.setEmail(authenticatorParameters.getUserIdentity().getEmail())
.setName(authenticatorParameters.getUserIdentity().getName())
.setExternalIdentity(
new ExternalIdentity(
identityProviderKey,
providerLogin,
authenticatorParameters.getUserIdentity().getProviderId()))
.build();
}
private static UserDto[] toArray(Optional<UserDto> userDto) {
return userDto.map(u -> new UserDto[]{u}).orElse(new UserDto[]{});
}
private static AuthenticationException generateExistingEmailError(UserRegistration authenticatorParameters, String email) {
return AuthenticationException.newBuilder()
.setSource(authenticatorParameters.getSource())
.setLogin(authenticatorParameters.getUserIdentity().getProviderLogin())
.setMessage(format("Email '%s' is already used", email))
.setPublicMessage(
"This account is already associated with another authentication method. "
+ "Sign in using the current authentication method, "
+ "or contact your administrator to transfer your account to a different authentication method.")
.build();
}
private static String getProviderIdOrProviderLogin(UserIdentity userIdentity) {
String providerId = userIdentity.getProviderId();
return providerId == null ? userIdentity.getProviderLogin() : providerId;
}
}
| 15,455 | 47.911392 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserRegistration.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.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.server.authentication.event.AuthenticationEvent;
import static java.util.Objects.requireNonNull;
public class UserRegistration {
private final UserIdentity userIdentity;
private final IdentityProvider provider;
private final AuthenticationEvent.Source source;
private final boolean managed;
UserRegistration(Builder builder) {
this.userIdentity = builder.userIdentity;
this.provider = builder.provider;
this.source = builder.source;
this.managed = builder.managed;
}
public UserIdentity getUserIdentity() {
return userIdentity;
}
public IdentityProvider getProvider() {
return provider;
}
public AuthenticationEvent.Source getSource() {
return source;
}
public boolean managed() {
return managed;
}
public static UserRegistration.Builder builder() {
return new Builder();
}
public static class Builder {
private UserIdentity userIdentity;
private IdentityProvider provider;
private AuthenticationEvent.Source source;
private boolean managed = false;
public Builder setUserIdentity(UserIdentity userIdentity) {
this.userIdentity = userIdentity;
return this;
}
public Builder setProvider(IdentityProvider provider) {
this.provider = provider;
return this;
}
public Builder setSource(AuthenticationEvent.Source source) {
this.source = source;
return this;
}
public Builder setManaged(boolean managed) {
this.managed = managed;
return this;
}
public UserRegistration build() {
requireNonNull(userIdentity, "userIdentity must be set");
requireNonNull(provider, "identityProvider must be set");
requireNonNull(source, "Source must be set");
return new UserRegistration(this);
}
}
}
| 2,811 | 28.291667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.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 java.util.Set;
import org.sonar.api.config.Configuration;
import org.sonar.api.impl.ws.StaticResources;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.web.UrlPattern;
import org.sonar.db.user.UserTokenDto;
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.user.ThreadLocalUserSession;
import org.sonar.server.user.TokenUserSession;
import org.sonar.server.user.UserSession;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE;
import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
@ServerSide
public class UserSessionInitializer {
/**
* Key of attribute to be used for displaying user login
* in logs/access.log. The pattern to be configured
* in property sonar.web.accessLogs.pattern is "%reqAttribute{LOGIN}"
*/
private static final String ACCESS_LOG_LOGIN = "LOGIN";
private static final String SQ_AUTHENTICATION_TOKEN_EXPIRATION = "SonarQube-Authentication-Token-Expiration";
// SONAR-6546 these urls should be get from WebService
private static final Set<String> SKIPPED_URLS = Set.of(
"/batch/index", "/batch/file",
"/maintenance/*", "/setup/*",
"/sessions/*", "/oauth2/callback/*",
"/api/system/db_migration_status", "/api/system/status", "/api/system/migrate_db",
"/api/server/version",
"/api/users/identity_providers", "/api/l10n/index",
"/api/authentication/login", "/api/authentication/logout", "/api/authentication/validate",
"/api/project_badges/measure", "/api/project_badges/quality_gate",
"/api/settings/login_message");
private static final Set<String> URL_USING_PASSCODE = Set.of(
"/api/ce/info", "/api/ce/pause",
"/api/ce/resume", "/api/system/health",
"/api/system/analytics", "/api/system/migrate_es",
"/api/system/liveness",
"/api/monitoring/metrics");
private static final UrlPattern URL_PATTERN = UrlPattern.builder()
.includes("/*")
.excludes(StaticResources.patterns())
.excludes(SKIPPED_URLS)
.build();
private static final UrlPattern PASSCODE_URLS = UrlPattern.builder()
.includes(URL_USING_PASSCODE)
.build();
private final Configuration config;
private final ThreadLocalUserSession threadLocalSession;
private final AuthenticationEvent authenticationEvent;
private final RequestAuthenticator requestAuthenticator;
public UserSessionInitializer(Configuration config, ThreadLocalUserSession threadLocalSession, AuthenticationEvent authenticationEvent,
RequestAuthenticator requestAuthenticator) {
this.config = config;
this.threadLocalSession = threadLocalSession;
this.authenticationEvent = authenticationEvent;
this.requestAuthenticator = requestAuthenticator;
}
public boolean initUserSession(HttpRequest request, HttpResponse response) {
String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");
try {
// Do not set user session when url is excluded
if (URL_PATTERN.matches(path)) {
loadUserSession(request, response, PASSCODE_URLS.matches(path));
}
return true;
} catch (AuthenticationException e) {
authenticationEvent.loginFailure(request, e);
if (isWsUrl(path)) {
response.setStatus(HTTP_UNAUTHORIZED);
return false;
}
if (isNotLocalOrJwt(e.getSource())) {
// redirect to Unauthorized error page
handleAuthenticationError(e, request, response);
return false;
}
// Web pages should redirect to the index.html file
return true;
}
}
private static boolean isNotLocalOrJwt(Source source) {
AuthenticationEvent.Provider provider = source.getProvider();
return provider != AuthenticationEvent.Provider.LOCAL && provider != AuthenticationEvent.Provider.JWT;
}
private void loadUserSession(HttpRequest request, HttpResponse response, boolean urlSupportsSystemPasscode) {
UserSession session = requestAuthenticator.authenticate(request, response);
if (!session.isLoggedIn() && !urlSupportsSystemPasscode && config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE)) {
// authentication is required
throw AuthenticationException.newBuilder()
.setSource(Source.local(AuthenticationEvent.Method.BASIC))
.setMessage("User must be authenticated")
.build();
}
threadLocalSession.set(session);
checkTokenUserSession(response, session);
request.setAttribute(ACCESS_LOG_LOGIN, defaultString(session.getLogin(), "-"));
}
private static void checkTokenUserSession(HttpResponse response, UserSession session) {
if (session instanceof TokenUserSession tokenUserSession) {
UserTokenDto userTokenDto = tokenUserSession.getUserToken();
Optional.ofNullable(userTokenDto.getExpirationDate()).ifPresent(expirationDate -> response.addHeader(SQ_AUTHENTICATION_TOKEN_EXPIRATION, formatDateTime(expirationDate)));
}
}
public void removeUserSession() {
threadLocalSession.unload();
}
private static boolean isWsUrl(String path) {
return path.startsWith("/batch/") || path.startsWith("/api/");
}
}
| 6,617 | 41.152866 | 176 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/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.authentication;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/event/AuthenticationEvent.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 java.util.Objects;
import javax.annotation.Nullable;
import org.sonar.api.server.authentication.BaseIdentityProvider;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.http.HttpRequest;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public interface AuthenticationEvent {
void loginSuccess(HttpRequest request, @Nullable String login, Source source);
void loginFailure(HttpRequest request, AuthenticationException e);
void logoutSuccess(HttpRequest request, @Nullable String login);
void logoutFailure(HttpRequest request, String errorMessage);
enum Method {
/**
* HTTP basic authentication with a login and password.
*/
BASIC,
/**
* Authentication with SonarQube token passed either as basic credentials or bearer token.
*/
SONARQUBE_TOKEN,
/**
* SQ login form authentication with a login and password.
*/
FORM,
/**
* SSO authentication (ie. with HTTP headers)
*/
SSO,
/**
* OAUTH2 authentication.
*/
OAUTH2,
/**
* JWT authentication (ie. with a session token).
*/
JWT,
/**
* Authentication of the GitHub webhook (with shared Nwebhook_secret)
*/
GITHUB_WEBHOOK,
/**
* External authentication (ie. fully implemented out of SQ's core code, see {@link BaseIdentityProvider}).
*/
EXTERNAL
}
enum Provider {
/**
* User authentication made against data in SQ's User table.
*/
LOCAL,
/**
* User authentication made by SSO provider.
*/
SSO,
/**
* User authentication made by Realm based provider (eg. LDAP).
*/
REALM,
/**
* User authentication made by JWT token information.
*/
JWT,
/**
* User authentication done thanks to the signature hash provided by github in the request headers generated with a common secret.
*/
GITHUB_WEBHOOK,
/**
* User authentication made by external provider (see {@link BaseIdentityProvider}).
*/
EXTERNAL
}
final class Source implements Serializable {
private static final String LOCAL_PROVIDER_NAME = "local";
private static final Source SSO_INSTANCE = new Source(Method.SSO, Provider.SSO, "sso");
private static final Source JWT_INSTANCE = new Source(Method.JWT, Provider.JWT, "jwt");
private static final Source GITHUB_WEBHOOK_INSTANCE = new Source(Method.GITHUB_WEBHOOK, Provider.GITHUB_WEBHOOK, "github");
private final Method method;
private final Provider provider;
private final String providerName;
private Source(Method method, Provider provider, String providerName) {
this.method = requireNonNull(method, "method can't be null");
this.provider = requireNonNull(provider, "provider can't be null");
this.providerName = requireNonNull(providerName, "provider name can't be null");
checkArgument(!providerName.isEmpty(), "provider name can't be empty");
}
public static Source local(Method method) {
return new Source(method, Provider.LOCAL, LOCAL_PROVIDER_NAME);
}
public static Source oauth2(OAuth2IdentityProvider identityProvider) {
return new Source(
Method.OAUTH2, Provider.EXTERNAL,
requireNonNull(identityProvider, "identityProvider can't be null").getName());
}
public static Source realm(Method method, String providerName) {
return new Source(method, Provider.REALM, providerName);
}
public static Source sso() {
return SSO_INSTANCE;
}
public static Source jwt() {
return JWT_INSTANCE;
}
public static Source githubWebhook() {
return GITHUB_WEBHOOK_INSTANCE;
}
public static Source external(IdentityProvider identityProvider) {
return new Source(
Method.EXTERNAL, Provider.EXTERNAL,
requireNonNull(identityProvider, "identityProvider can't be null").getName());
}
public Method getMethod() {
return method;
}
public Provider getProvider() {
return provider;
}
public String getProviderName() {
return providerName;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Source source = (Source) o;
return method == source.method &&
provider == source.provider &&
providerName.equals(source.providerName);
}
@Override
public int hashCode() {
return Objects.hash(method, provider, providerName);
}
@Override
public String toString() {
return "Source{" +
"method=" + method +
", provider=" + provider +
", providerName='" + providerName + '\'' +
'}';
}
}
}
| 5,871 | 28.959184 | 134 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/event/AuthenticationEventImpl.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.util.Collections;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.server.http.HttpRequest;
import static java.util.Objects.requireNonNull;
public class AuthenticationEventImpl implements AuthenticationEvent {
private static final Logger LOGGER = LoggerFactory.getLogger("auth.event");
private static final int FLOOD_THRESHOLD = 128;
private static final Pattern PATTERN_LINE_BREAK = Pattern.compile("[\n\r]");
@Override
public void loginSuccess(HttpRequest request, @Nullable String login, Source source) {
checkRequest(request);
requireNonNull(source, "source can't be null");
LOGGER.atDebug().setMessage("login success [method|{}][provider|{}|{}][IP|{}|{}][login|{}]")
.addArgument(source::getMethod)
.addArgument(source::getProvider)
.addArgument(source::getProviderName)
.addArgument(request::getRemoteAddr)
.addArgument(() -> getAllIps(request))
.addArgument(() -> preventLogFlood(sanitizeLog(emptyIfNull(login))))
.log();
}
private static String getAllIps(HttpRequest request) {
return String.join(",", Collections.list(request.getHeaders("X-Forwarded-For")));
}
@Override
public void loginFailure(HttpRequest request, AuthenticationException e) {
checkRequest(request);
requireNonNull(e, "AuthenticationException can't be null");
if (!LOGGER.isDebugEnabled()) {
return;
}
Source source = e.getSource();
LOGGER.debug("login failure [cause|{}][method|{}][provider|{}|{}][IP|{}|{}][login|{}]",
emptyIfNull(e.getMessage()),
source.getMethod(), source.getProvider(), source.getProviderName(),
request.getRemoteAddr(), getAllIps(request),
preventLogFlood(emptyIfNull(e.getLogin())));
}
@Override
public void logoutSuccess(HttpRequest request, @Nullable String login) {
checkRequest(request);
if (!LOGGER.isDebugEnabled()) {
return;
}
LOGGER.debug("logout success [IP|{}|{}][login|{}]",
request.getRemoteAddr(), getAllIps(request),
preventLogFlood(emptyIfNull(login)));
}
@Override
public void logoutFailure(HttpRequest request, String errorMessage) {
checkRequest(request);
requireNonNull(errorMessage, "error message can't be null");
if (!LOGGER.isDebugEnabled()) {
return;
}
LOGGER.debug("logout failure [error|{}][IP|{}|{}]",
emptyIfNull(errorMessage),
request.getRemoteAddr(), getAllIps(request));
}
private static void checkRequest(HttpRequest request) {
requireNonNull(request, "request can't be null");
}
private static String emptyIfNull(@Nullable String login) {
return login == null ? "" : login;
}
private static String preventLogFlood(String str) {
if (str.length() > FLOOD_THRESHOLD) {
return str.substring(0, FLOOD_THRESHOLD) + "...(" + str.length() + ")";
}
return str;
}
private static String sanitizeLog(String message) {
return PATTERN_LINE_BREAK.matcher(message).replaceAll("_");
}
}
| 3,979 | 34.535714 | 96 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/event/AuthenticationException.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 javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
/**
* Exception thrown in case of authentication failure.
* <p>
* This exception contains the source of authentication and, if present, the login on which the login attempt occurred.
* </p>
* <p>
* Given that {@link #source} and {@link #login} will be logged to file, be very careful <strong>not to set the login
* when the login is a security token</strong>.
* </p>
*/
public class AuthenticationException extends RuntimeException {
private final AuthenticationEvent.Source source;
@CheckForNull
private final String login;
private final String publicMessage;
private AuthenticationException(Builder builder) {
super(builder.message);
this.source = requireNonNull(builder.source, "source can't be null");
this.login = builder.login;
this.publicMessage = builder.publicMessage;
}
public AuthenticationEvent.Source getSource() {
return source;
}
@CheckForNull
public String getLogin() {
return login;
}
@CheckForNull
public String getPublicMessage() {
return publicMessage;
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
@CheckForNull
private AuthenticationEvent.Source source;
@CheckForNull
private String login;
@CheckForNull
private String message;
@CheckForNull
private String publicMessage;
private Builder() {
// use static factory method
}
public Builder setSource(AuthenticationEvent.Source source) {
this.source = source;
return this;
}
public Builder setLogin(@Nullable String login) {
this.login = login;
return this;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public Builder setPublicMessage(String publicMessage) {
this.publicMessage = publicMessage;
return this;
}
public AuthenticationException build() {
return new AuthenticationException(this);
}
}
}
| 2,997 | 27.018692 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/event/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.authentication.event;
import javax.annotation.ParametersAreNonnullByDefault;
| 977 | 39.75 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/purge/ExpiredSessionsCleaner.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.purge;
import java.util.concurrent.TimeUnit;
import org.sonar.api.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.util.GlobalLockManager;
public class ExpiredSessionsCleaner implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(ExpiredSessionsCleaner.class);
private static final long PERIOD_IN_SECONDS = 24 * 60 * 60L;
private static final String LOCK_NAME = "SessionCleaner";
private final ExpiredSessionsCleanerExecutorService executorService;
private final DbClient dbClient;
private final GlobalLockManager lockManager;
public ExpiredSessionsCleaner(ExpiredSessionsCleanerExecutorService executorService, DbClient dbClient, GlobalLockManager lockManager) {
this.executorService = executorService;
this.dbClient = dbClient;
this.lockManager = lockManager;
}
@Override
public void start() {
this.executorService.scheduleAtFixedRate(this::executePurge, 0, PERIOD_IN_SECONDS, TimeUnit.SECONDS);
}
private void executePurge() {
if (!lockManager.tryLock(LOCK_NAME)) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
cleanExpiredSessionTokens(dbSession);
cleanExpiredSamlMessageIds(dbSession);
}
}
private void cleanExpiredSessionTokens(DbSession dbSession) {
LOG.debug("Start of cleaning expired session tokens");
int deletedSessionTokens = dbClient.sessionTokensDao().deleteExpired(dbSession);
dbSession.commit();
LOG.info("Purge of expired session tokens has removed {} elements", deletedSessionTokens);
}
private void cleanExpiredSamlMessageIds(DbSession dbSession) {
LOG.debug("Start of cleaning expired SAML message IDs");
int deleted = dbClient.samlMessageIdDao().deleteExpired(dbSession);
dbSession.commit();
LOG.info("Purge of expired SAML message ids has removed {} elements", deleted);
}
@Override
public void stop() {
// nothing to do
}
}
| 2,922 | 34.646341 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/purge/ExpiredSessionsCleanerExecutorService.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.purge;
import java.util.concurrent.ScheduledExecutorService;
import org.sonar.api.server.ServerSide;
@ServerSide
public interface ExpiredSessionsCleanerExecutorService extends ScheduledExecutorService {
}
| 1,090 | 37.964286 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/purge/ExpiredSessionsCleanerExecutorServiceImpl.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.purge;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl;
import static java.lang.Thread.MIN_PRIORITY;
public class ExpiredSessionsCleanerExecutorServiceImpl
extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService>
implements ExpiredSessionsCleanerExecutorService {
public ExpiredSessionsCleanerExecutorServiceImpl() {
super(
Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = Executors.defaultThreadFactory().newThread(r);
thread.setName("ExpiredSessionsCleaner-%d");
thread.setPriority(MIN_PRIORITY);
thread.setDaemon(false);
return thread;
}));
}
}
| 1,659 | 37.604651 | 81 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/purge/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.authentication.purge;
import javax.annotation.ParametersAreNonnullByDefault;
| 978 | 38.16 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/GroupUuid.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 javax.annotation.concurrent.Immutable;
import org.sonar.db.user.GroupDto;
/**
* Reference to a user group, as used internally by the backend. It does
* not support reference to virtual groups "anyone".
*
* @see GroupUuidOrAnyone
*/
@Immutable
public class GroupUuid {
private final String uuid;
private GroupUuid(String uuid) {
this.uuid = uuid;
}
public String getUuid() {
return uuid;
}
public static GroupUuid from(GroupDto dto) {
return new GroupUuid(dto.getUuid());
}
}
| 1,399 | 28.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/GroupUuidOrAnyone.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 javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.user.GroupDto;
/**
* Reference to a user group, as used internally by the backend. Contrary to
* {@link GroupUuid}, it supports reference to virtual groups "anyone". In these
* cases {@link #getUuid()} returns {@code null}
*
* @see GroupUuid
*/
@Immutable
public class GroupUuidOrAnyone {
private final String uuid;
private GroupUuidOrAnyone(@Nullable String uuid) {
this.uuid = uuid;
}
public boolean isAnyone() {
return uuid == null;
}
@CheckForNull
public String getUuid() {
return uuid;
}
public static GroupUuidOrAnyone from(GroupDto dto) {
return new GroupUuidOrAnyone(dto.getUuid());
}
public static GroupUuidOrAnyone forAnyone() {
return new GroupUuidOrAnyone(null);
}
}
| 1,755 | 28.266667 | 80 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.