mirror of
https://github.com/scm-manager/scm-manager.git
synced 2025-11-10 07:25:44 +01:00
Merge with 2.0.0-m3
This commit is contained in:
5
Jenkinsfile
vendored
5
Jenkinsfile
vendored
@@ -50,6 +50,11 @@ node('docker') {
|
|||||||
def dockerImageTag = "2.0.0-dev-${commitHash.substring(0,7)}-${BUILD_NUMBER}"
|
def dockerImageTag = "2.0.0-dev-${commitHash.substring(0,7)}-${BUILD_NUMBER}"
|
||||||
|
|
||||||
if (isMainBranch()) {
|
if (isMainBranch()) {
|
||||||
|
stage('Archive') {
|
||||||
|
archiveArtifacts 'scm-webapp/target/scm-webapp.war'
|
||||||
|
archiveArtifacts 'scm-server/target/scm-server-app.*'
|
||||||
|
}
|
||||||
|
|
||||||
stage('Docker') {
|
stage('Docker') {
|
||||||
def image = docker.build('cloudogu/scm-manager')
|
def image = docker.build('cloudogu/scm-manager')
|
||||||
docker.withRegistry('', 'hub.docker.com-cesmarvin') {
|
docker.withRegistry('', 'hub.docker.com-cesmarvin') {
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ package sonia.scm.security;
|
|||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An access token can be used to access scm-manager without providing username and password. An {@link AccessToken} can
|
* An access token can be used to access scm-manager without providing username and password. An {@link AccessToken} can
|
||||||
@@ -103,6 +104,13 @@ public interface AccessToken {
|
|||||||
*/
|
*/
|
||||||
Scope getScope();
|
Scope getScope();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns name of groups, in which the user should be a member.
|
||||||
|
*
|
||||||
|
* @return name of groups
|
||||||
|
*/
|
||||||
|
Set<String> getGroups();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns an optional value of a custom token field.
|
* Returns an optional value of a custom token field.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -89,16 +89,25 @@ public interface AccessTokenBuilder {
|
|||||||
* @return {@code this}
|
* @return {@code this}
|
||||||
*/
|
*/
|
||||||
AccessTokenBuilder refreshableFor(long count, TimeUnit unit);
|
AccessTokenBuilder refreshableFor(long count, TimeUnit unit);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reduces the permissions of the token by providing a scope.
|
* Reduces the permissions of the token by providing a scope.
|
||||||
*
|
*
|
||||||
* @param scope scope of token
|
* @param scope scope of token
|
||||||
*
|
*
|
||||||
* @return {@code this}
|
* @return {@code this}
|
||||||
*/
|
*/
|
||||||
AccessTokenBuilder scope(Scope scope);
|
AccessTokenBuilder scope(Scope scope);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define the logged in user as member of the given groups.
|
||||||
|
*
|
||||||
|
* @param groups group names
|
||||||
|
*
|
||||||
|
* @return {@code this}
|
||||||
|
*/
|
||||||
|
AccessTokenBuilder groups(String... groups);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new {@link AccessToken} with the provided settings.
|
* Creates a new {@link AccessToken} with the provided settings.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ import com.google.common.base.MoreObjects;
|
|||||||
import com.google.common.base.Strings;
|
import com.google.common.base.Strings;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
import com.google.common.collect.ImmutableSet.Builder;
|
import com.google.common.collect.ImmutableSet.Builder;
|
||||||
import org.apache.shiro.authc.AuthenticationException;
|
|
||||||
import org.apache.shiro.authc.AuthenticationInfo;
|
import org.apache.shiro.authc.AuthenticationInfo;
|
||||||
import org.apache.shiro.authc.AuthenticationToken;
|
import org.apache.shiro.authc.AuthenticationToken;
|
||||||
import org.apache.shiro.authc.DisabledAccountException;
|
import org.apache.shiro.authc.DisabledAccountException;
|
||||||
@@ -54,6 +53,8 @@ import sonia.scm.group.GroupNames;
|
|||||||
import sonia.scm.user.User;
|
import sonia.scm.user.User;
|
||||||
import sonia.scm.user.UserDAO;
|
import sonia.scm.user.UserDAO;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
import static com.google.common.base.Preconditions.checkArgument;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -63,8 +64,7 @@ import static com.google.common.base.Preconditions.checkArgument;
|
|||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
*/
|
*/
|
||||||
public final class DAORealmHelper
|
public final class DAORealmHelper {
|
||||||
{
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* the logger for DAORealmHelper
|
* the logger for DAORealmHelper
|
||||||
@@ -109,37 +109,37 @@ public final class DAORealmHelper
|
|||||||
public CredentialsMatcher wrapCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
|
public CredentialsMatcher wrapCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
|
||||||
return new RetryLimitPasswordMatcher(loginAttemptHandler, credentialsMatcher);
|
return new RetryLimitPasswordMatcher(loginAttemptHandler, credentialsMatcher);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method description
|
* Creates {@link AuthenticationInfo} from a {@link UsernamePasswordToken}. The method accepts
|
||||||
|
* {@link AuthenticationInfo} as argument, so that the caller does not need to cast.
|
||||||
*
|
*
|
||||||
|
* @param token authentication token, it must be {@link UsernamePasswordToken}
|
||||||
*
|
*
|
||||||
* @param token
|
* @return authentication info
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*
|
|
||||||
* @throws AuthenticationException
|
|
||||||
*/
|
*/
|
||||||
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
|
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) {
|
||||||
checkArgument(token instanceof UsernamePasswordToken, "%s is required", UsernamePasswordToken.class);
|
checkArgument(token instanceof UsernamePasswordToken, "%s is required", UsernamePasswordToken.class);
|
||||||
|
|
||||||
UsernamePasswordToken upt = (UsernamePasswordToken) token;
|
UsernamePasswordToken upt = (UsernamePasswordToken) token;
|
||||||
String principal = upt.getUsername();
|
String principal = upt.getUsername();
|
||||||
|
|
||||||
return getAuthenticationInfo(principal, null, null);
|
return getAuthenticationInfo(principal, null, null, Collections.emptySet());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method description
|
* Returns a builder for {@link AuthenticationInfo}.
|
||||||
*
|
*
|
||||||
|
* @param principal name of principal (username)
|
||||||
*
|
*
|
||||||
* @param principal
|
* @return authentication info builder
|
||||||
* @param credentials
|
|
||||||
* @param scope
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
*/
|
||||||
public AuthenticationInfo getAuthenticationInfo(String principal, String credentials, Scope scope) {
|
public AuthenticationInfoBuilder authenticationInfoBuilder(String principal) {
|
||||||
|
return new AuthenticationInfoBuilder(principal);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private AuthenticationInfo getAuthenticationInfo(String principal, String credentials, Scope scope, Iterable<String> groups) {
|
||||||
checkArgument(!Strings.isNullOrEmpty(principal), "username is required");
|
checkArgument(!Strings.isNullOrEmpty(principal), "username is required");
|
||||||
|
|
||||||
LOG.debug("try to authenticate {}", principal);
|
LOG.debug("try to authenticate {}", principal);
|
||||||
@@ -157,7 +157,7 @@ public final class DAORealmHelper
|
|||||||
|
|
||||||
collection.add(principal, realm);
|
collection.add(principal, realm);
|
||||||
collection.add(user, realm);
|
collection.add(user, realm);
|
||||||
collection.add(collectGroups(principal), realm);
|
collection.add(collectGroups(principal, groups), realm);
|
||||||
collection.add(MoreObjects.firstNonNull(scope, Scope.empty()), realm);
|
collection.add(MoreObjects.firstNonNull(scope, Scope.empty()), realm);
|
||||||
|
|
||||||
String creds = credentials;
|
String creds = credentials;
|
||||||
@@ -171,11 +171,15 @@ public final class DAORealmHelper
|
|||||||
|
|
||||||
//~--- methods --------------------------------------------------------------
|
//~--- methods --------------------------------------------------------------
|
||||||
|
|
||||||
private GroupNames collectGroups(String principal) {
|
private GroupNames collectGroups(String principal, Iterable<String> groupNames) {
|
||||||
Builder<String> builder = ImmutableSet.builder();
|
Builder<String> builder = ImmutableSet.builder();
|
||||||
|
|
||||||
builder.add(GroupNames.AUTHENTICATED);
|
builder.add(GroupNames.AUTHENTICATED);
|
||||||
|
|
||||||
|
for (String group : groupNames) {
|
||||||
|
builder.add(group);
|
||||||
|
}
|
||||||
|
|
||||||
for (Group group : groupDAO.getAll()) {
|
for (Group group : groupDAO.getAll()) {
|
||||||
if (group.isMember(principal)) {
|
if (group.isMember(principal)) {
|
||||||
builder.add(group.getName());
|
builder.add(group.getName());
|
||||||
@@ -187,6 +191,69 @@ public final class DAORealmHelper
|
|||||||
return groups;
|
return groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builder class for {@link AuthenticationInfo}.
|
||||||
|
*/
|
||||||
|
public class AuthenticationInfoBuilder {
|
||||||
|
|
||||||
|
private final String principal;
|
||||||
|
|
||||||
|
private String credentials;
|
||||||
|
private Scope scope;
|
||||||
|
private Iterable<String> groups = Collections.emptySet();
|
||||||
|
|
||||||
|
private AuthenticationInfoBuilder(String principal) {
|
||||||
|
this.principal = principal;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* With credentials uses the given credentials for the {@link AuthenticationInfo}, this is particularly important
|
||||||
|
* for caching purposes.
|
||||||
|
*
|
||||||
|
* @param credentials credentials such as password
|
||||||
|
*
|
||||||
|
* @return {@code this}
|
||||||
|
*/
|
||||||
|
public AuthenticationInfoBuilder withCredentials(String credentials) {
|
||||||
|
this.credentials = credentials;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* With the scope object it is possible to limit the access permissions to scm-manager.
|
||||||
|
*
|
||||||
|
* @param scope scope object
|
||||||
|
*
|
||||||
|
* @return {@code this}
|
||||||
|
*/
|
||||||
|
public AuthenticationInfoBuilder withScope(Scope scope) {
|
||||||
|
this.scope = scope;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* With groups adds extra groups, besides those which come from the {@link GroupDAO}, to the authentication info.
|
||||||
|
*
|
||||||
|
* @param groups extra groups
|
||||||
|
*
|
||||||
|
* @return {@code this}
|
||||||
|
*/
|
||||||
|
public AuthenticationInfoBuilder withGroups(Iterable<String> groups) {
|
||||||
|
this.groups = groups;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build creates the authentication info from the given information.
|
||||||
|
*
|
||||||
|
* @return authentication info
|
||||||
|
*/
|
||||||
|
public AuthenticationInfo build() {
|
||||||
|
return getAuthenticationInfo(principal, credentials, scope, groups);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
private static class RetryLimitPasswordMatcher implements CredentialsMatcher {
|
private static class RetryLimitPasswordMatcher implements CredentialsMatcher {
|
||||||
|
|
||||||
private final LoginAttemptHandler loginAttemptHandler;
|
private final LoginAttemptHandler loginAttemptHandler;
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package sonia.scm.security;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
|
import com.google.common.collect.ImmutableSet;
|
||||||
|
import org.apache.shiro.authc.AuthenticationInfo;
|
||||||
|
import org.apache.shiro.authc.DisabledAccountException;
|
||||||
|
import org.apache.shiro.authc.UnknownAccountException;
|
||||||
|
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||||
|
import org.apache.shiro.subject.PrincipalCollection;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import sonia.scm.group.Group;
|
||||||
|
import sonia.scm.group.GroupDAO;
|
||||||
|
import sonia.scm.group.GroupNames;
|
||||||
|
import sonia.scm.user.User;
|
||||||
|
import sonia.scm.user.UserDAO;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class DAORealmHelperTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private LoginAttemptHandler loginAttemptHandler;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserDAO userDAO;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private GroupDAO groupDAO;
|
||||||
|
|
||||||
|
private DAORealmHelper helper;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUpObjectUnderTest() {
|
||||||
|
helper = new DAORealmHelper(loginAttemptHandler, userDAO, groupDAO, "hitchhiker");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowExceptionWithoutUsername() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> helper.authenticationInfoBuilder(null).build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowExceptionWithEmptyUsername() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> helper.authenticationInfoBuilder("").build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowExceptionWithUnknownUser() {
|
||||||
|
assertThrows(UnknownAccountException.class, () -> helper.authenticationInfoBuilder("trillian").build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowExceptionOnDisabledAccount() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
user.setActive(false);
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
assertThrows(DisabledAccountException.class, () -> helper.authenticationInfoBuilder("trillian").build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnAuthenticationInfo() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
AuthenticationInfo authenticationInfo = helper.authenticationInfoBuilder("trillian").build();
|
||||||
|
PrincipalCollection principals = authenticationInfo.getPrincipals();
|
||||||
|
assertThat(principals.oneByType(User.class)).isSameAs(user);
|
||||||
|
assertThat(principals.oneByType(GroupNames.class)).containsOnly("_authenticated");
|
||||||
|
assertThat(principals.oneByType(Scope.class)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnAuthenticationInfoWithGroups() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
Group one = new Group("xml", "one", "trillian");
|
||||||
|
Group two = new Group("xml", "two", "trillian");
|
||||||
|
Group six = new Group("xml", "six", "dent");
|
||||||
|
when(groupDAO.getAll()).thenReturn(ImmutableList.of(one, two, six));
|
||||||
|
|
||||||
|
AuthenticationInfo authenticationInfo = helper.authenticationInfoBuilder("trillian")
|
||||||
|
.withGroups(ImmutableList.of("three"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
PrincipalCollection principals = authenticationInfo.getPrincipals();
|
||||||
|
assertThat(principals.oneByType(GroupNames.class)).containsOnly("_authenticated", "one", "two", "three");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnAuthenticationInfoWithScope() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
Scope scope = Scope.valueOf("user:*", "group:*");
|
||||||
|
|
||||||
|
AuthenticationInfo authenticationInfo = helper.authenticationInfoBuilder("trillian")
|
||||||
|
.withScope(scope)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
PrincipalCollection principals = authenticationInfo.getPrincipals();
|
||||||
|
assertThat(principals.oneByType(Scope.class)).isSameAs(scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnAuthenticationInfoWithCredentials() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
AuthenticationInfo authenticationInfo = helper.authenticationInfoBuilder("trillian")
|
||||||
|
.withCredentials("secret")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertThat(authenticationInfo.getCredentials()).isEqualTo("secret");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnAuthenticationInfoWithCredentialsFromUser() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
user.setPassword("secret");
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
AuthenticationInfo authenticationInfo = helper.authenticationInfoBuilder("trillian").build();
|
||||||
|
|
||||||
|
assertThat(authenticationInfo.getCredentials()).isEqualTo("secret");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowExceptionWithWrongTypeOfToken() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> helper.getAuthenticationInfo(BearerToken.valueOf("__bearer__")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldGetAuthenticationInfo() {
|
||||||
|
User user = new User("trillian");
|
||||||
|
when(userDAO.get("trillian")).thenReturn(user);
|
||||||
|
|
||||||
|
AuthenticationInfo authenticationInfo = helper.getAuthenticationInfo(new UsernamePasswordToken("trillian", "secret"));
|
||||||
|
|
||||||
|
PrincipalCollection principals = authenticationInfo.getPrincipals();
|
||||||
|
assertThat(principals.oneByType(User.class)).isSameAs(user);
|
||||||
|
assertThat(principals.oneByType(GroupNames.class)).containsOnly("_authenticated");
|
||||||
|
assertThat(principals.oneByType(Scope.class)).isEmpty();
|
||||||
|
|
||||||
|
assertThat(authenticationInfo.getCredentials()).isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,10 @@
|
|||||||
package sonia.scm.it;
|
package sonia.scm.it;
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import sonia.scm.it.utils.ScmRequests;
|
import sonia.scm.it.utils.ScmRequests;
|
||||||
import sonia.scm.it.utils.TestData;
|
import sonia.scm.it.utils.TestData;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
public class MeITCase {
|
public class MeITCase {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
@@ -23,9 +20,6 @@ public class MeITCase {
|
|||||||
.requestIndexResource(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN)
|
.requestIndexResource(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN)
|
||||||
.requestMe()
|
.requestMe()
|
||||||
.assertStatusCode(200)
|
.assertStatusCode(200)
|
||||||
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))
|
|
||||||
.assertPassword(Assert::assertNull)
|
|
||||||
.assertType(s -> assertThat(s).isEqualTo("xml"))
|
|
||||||
.requestChangePassword(TestData.USER_SCM_ADMIN, newPassword)
|
.requestChangePassword(TestData.USER_SCM_ADMIN, newPassword)
|
||||||
.assertStatusCode(204);
|
.assertStatusCode(204);
|
||||||
// assert password is changed -> login with the new Password than undo changes
|
// assert password is changed -> login with the new Password than undo changes
|
||||||
@@ -33,7 +27,6 @@ public class MeITCase {
|
|||||||
.requestIndexResource(TestData.USER_SCM_ADMIN, newPassword)
|
.requestIndexResource(TestData.USER_SCM_ADMIN, newPassword)
|
||||||
.requestMe()
|
.requestMe()
|
||||||
.assertStatusCode(200)
|
.assertStatusCode(200)
|
||||||
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))// still admin
|
|
||||||
.requestChangePassword(newPassword, TestData.USER_SCM_ADMIN)
|
.requestChangePassword(newPassword, TestData.USER_SCM_ADMIN)
|
||||||
.assertStatusCode(204);
|
.assertStatusCode(204);
|
||||||
}
|
}
|
||||||
@@ -49,9 +42,6 @@ public class MeITCase {
|
|||||||
.requestIndexResource(username, password)
|
.requestIndexResource(username, password)
|
||||||
.requestMe()
|
.requestMe()
|
||||||
.assertStatusCode(200)
|
.assertStatusCode(200)
|
||||||
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.FALSE))
|
|
||||||
.assertPassword(Assert::assertNull)
|
|
||||||
.assertType(s -> assertThat(s).isEqualTo("xml"))
|
|
||||||
.requestChangePassword(password, newPassword)
|
.requestChangePassword(password, newPassword)
|
||||||
.assertStatusCode(204);
|
.assertStatusCode(204);
|
||||||
// assert password is changed -> login with the new Password than undo changes
|
// assert password is changed -> login with the new Password than undo changes
|
||||||
@@ -72,9 +62,6 @@ public class MeITCase {
|
|||||||
.requestIndexResource(newUser, password)
|
.requestIndexResource(newUser, password)
|
||||||
.requestMe()
|
.requestMe()
|
||||||
.assertStatusCode(200)
|
.assertStatusCode(200)
|
||||||
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))
|
|
||||||
.assertPassword(Assert::assertNull)
|
|
||||||
.assertType(s -> assertThat(s).isEqualTo(type))
|
|
||||||
.assertPasswordLinkDoesNotExists();
|
.assertPasswordLinkDoesNotExists();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ public class ScmRequests {
|
|||||||
return new IndexResponse(applyGETRequest(RestUtil.REST_BASE_URL.toString()));
|
return new IndexResponse(applyGETRequest(RestUtil.REST_BASE_URL.toString()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public <SELF extends UserResponse<SELF, T>, T extends ModelResponse> UserResponse<SELF,T> requestUser(String username, String password, String pathParam) {
|
public UserResponse<UserResponse> requestUser(String username, String password, String pathParam) {
|
||||||
setUsername(username);
|
setUsername(username);
|
||||||
setPassword(password);
|
setPassword(password);
|
||||||
return new UserResponse<>(applyGETRequest(RestUtil.REST_BASE_URL.resolve("users/"+pathParam).toString()), null);
|
return new UserResponse<>(applyGETRequest(RestUtil.REST_BASE_URL.resolve("users/"+pathParam).toString()), null);
|
||||||
@@ -195,7 +195,7 @@ public class ScmRequests {
|
|||||||
return new MeResponse<>(applyGETRequestFromLink(response, LINK_ME), this);
|
return new MeResponse<>(applyGETRequestFromLink(response, LINK_ME), this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserResponse<? extends UserResponse, IndexResponse> requestUser(String username) {
|
public UserResponse<IndexResponse> requestUser(String username) {
|
||||||
return new UserResponse<>(applyGETRequestFromLinkWithParams(response, LINK_USERS, username), this);
|
return new UserResponse<>(applyGETRequestFromLinkWithParams(response, LINK_USERS, username), this);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,19 +307,24 @@ public class ScmRequests {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class MeResponse<PREV extends ModelResponse> extends UserResponse<MeResponse<PREV>, PREV> {
|
public class MeResponse<PREV extends ModelResponse> extends ModelResponse<MeResponse<PREV>, PREV> {
|
||||||
|
|
||||||
|
public static final String LINKS_PASSWORD_HREF = "_links.password.href";
|
||||||
|
|
||||||
public MeResponse(Response response, PREV previousResponse) {
|
public MeResponse(Response response, PREV previousResponse) {
|
||||||
super(response, previousResponse);
|
super(response, previousResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ChangePasswordResponse<UserResponse> requestChangePassword(String oldPassword, String newPassword) {
|
public MeResponse<PREV> assertPasswordLinkDoesNotExists() {
|
||||||
|
return assertPropertyPathDoesNotExists(LINKS_PASSWORD_HREF);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChangePasswordResponse<MeResponse> requestChangePassword(String oldPassword, String newPassword) {
|
||||||
return new ChangePasswordResponse<>(applyPUTRequestFromLink(super.response, LINKS_PASSWORD_HREF, VndMediaType.PASSWORD_CHANGE, createPasswordChangeJson(oldPassword, newPassword)), this);
|
return new ChangePasswordResponse<>(applyPUTRequestFromLink(super.response, LINKS_PASSWORD_HREF, VndMediaType.PASSWORD_CHANGE, createPasswordChangeJson(oldPassword, newPassword)), this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class UserResponse<SELF extends UserResponse<SELF, PREV>, PREV extends ModelResponse> extends ModelResponse<SELF, PREV> {
|
public class UserResponse<PREV extends ModelResponse> extends ModelResponse<UserResponse<PREV>, PREV> {
|
||||||
|
|
||||||
public static final String LINKS_PASSWORD_HREF = "_links.password.href";
|
public static final String LINKS_PASSWORD_HREF = "_links.password.href";
|
||||||
|
|
||||||
@@ -327,23 +332,23 @@ public class ScmRequests {
|
|||||||
super(response, previousResponse);
|
super(response, previousResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SELF assertPassword(Consumer<String> assertPassword) {
|
public UserResponse<PREV> assertPassword(Consumer<String> assertPassword) {
|
||||||
return super.assertSingleProperty(assertPassword, "password");
|
return super.assertSingleProperty(assertPassword, "password");
|
||||||
}
|
}
|
||||||
|
|
||||||
public SELF assertType(Consumer<String> assertType) {
|
public UserResponse<PREV> assertType(Consumer<String> assertType) {
|
||||||
return assertSingleProperty(assertType, "type");
|
return assertSingleProperty(assertType, "type");
|
||||||
}
|
}
|
||||||
|
|
||||||
public SELF assertAdmin(Consumer<Boolean> assertAdmin) {
|
public UserResponse<PREV> assertAdmin(Consumer<Boolean> assertAdmin) {
|
||||||
return assertSingleProperty(assertAdmin, "admin");
|
return assertSingleProperty(assertAdmin, "admin");
|
||||||
}
|
}
|
||||||
|
|
||||||
public SELF assertPasswordLinkDoesNotExists() {
|
public UserResponse<PREV> assertPasswordLinkDoesNotExists() {
|
||||||
return assertPropertyPathDoesNotExists(LINKS_PASSWORD_HREF);
|
return assertPropertyPathDoesNotExists(LINKS_PASSWORD_HREF);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SELF assertPasswordLinkExists() {
|
public UserResponse<PREV> assertPasswordLinkExists() {
|
||||||
return assertPropertyPathExists(LINKS_PASSWORD_HREF);
|
return assertPropertyPathExists(LINKS_PASSWORD_HREF);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,5 +6,6 @@ export type Me = {
|
|||||||
name: string,
|
name: string,
|
||||||
displayName: string,
|
displayName: string,
|
||||||
mail: string,
|
mail: string,
|
||||||
|
groups: [],
|
||||||
_links: Links
|
_links: Links
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -48,6 +48,7 @@
|
|||||||
"username": "Username",
|
"username": "Username",
|
||||||
"displayName": "Display Name",
|
"displayName": "Display Name",
|
||||||
"mail": "E-Mail",
|
"mail": "E-Mail",
|
||||||
|
"groups": "Groups",
|
||||||
"information": "Information",
|
"information": "Information",
|
||||||
"change-password": "Change password",
|
"change-password": "Change password",
|
||||||
"error-title": "Error",
|
"error-title": "Error",
|
||||||
|
|||||||
@@ -1,53 +1,63 @@
|
|||||||
// @flow
|
// @flow
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import type { Me } from "@scm-manager/ui-types";
|
import type { Me } from "@scm-manager/ui-types";
|
||||||
import { MailLink, AvatarWrapper, AvatarImage } from "@scm-manager/ui-components";
|
import { MailLink, AvatarWrapper, AvatarImage } from "@scm-manager/ui-components";
|
||||||
import { compose } from "redux";
|
import { compose } from "redux";
|
||||||
import { translate } from "react-i18next";
|
import { translate } from "react-i18next";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
me: Me,
|
me: Me,
|
||||||
|
|
||||||
// Context props
|
// Context props
|
||||||
t: string => string
|
t: string => string
|
||||||
};
|
};
|
||||||
type State = {};
|
type State = {};
|
||||||
|
|
||||||
class ProfileInfo extends React.Component<Props, State> {
|
class ProfileInfo extends React.Component<Props, State> {
|
||||||
render() {
|
render() {
|
||||||
const { me, t } = this.props;
|
const { me, t } = this.props;
|
||||||
return (
|
return (
|
||||||
<div className="media">
|
<div className="media">
|
||||||
<AvatarWrapper>
|
<AvatarWrapper>
|
||||||
<figure className="media-left">
|
<figure className="media-left">
|
||||||
<p className="image is-64x64">
|
<p className="image is-64x64">
|
||||||
<AvatarImage person={ me }/>
|
<AvatarImage person={ me }/>
|
||||||
</p>
|
</p>
|
||||||
</figure>
|
</figure>
|
||||||
</AvatarWrapper>
|
</AvatarWrapper>
|
||||||
<div className="media-content">
|
<div className="media-content">
|
||||||
<table className="table">
|
<table className="table">
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr>
|
<tr>
|
||||||
<td className="has-text-weight-semibold">{t("profile.username")}</td>
|
<td className="has-text-weight-semibold">{t("profile.username")}</td>
|
||||||
<td>{me.name}</td>
|
<td>{me.name}</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td className="has-text-weight-semibold">{t("profile.displayName")}</td>
|
<td className="has-text-weight-semibold">{t("profile.displayName")}</td>
|
||||||
<td>{me.displayName}</td>
|
<td>{me.displayName}</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td className="has-text-weight-semibold">{t("profile.mail")}</td>
|
<td className="has-text-weight-semibold">{t("profile.mail")}</td>
|
||||||
<td>
|
<td>
|
||||||
<MailLink address={me.mail} />
|
<MailLink address={me.mail} />
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
<tr>
|
||||||
</table>
|
<td className="has-text-weight-semibold">{t("profile.groups")}</td>
|
||||||
</div>
|
<td className="content">
|
||||||
</div>
|
<ul>
|
||||||
);
|
{me.groups.map((group) => {
|
||||||
}
|
return <li>{group}</li>;
|
||||||
}
|
})}
|
||||||
|
</ul>
|
||||||
export default compose(translate("commons"))(ProfileInfo);
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default compose(translate("commons"))(ProfileInfo);
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import { translate } from "react-i18next";
|
|||||||
import EditGroup from "./EditGroup";
|
import EditGroup from "./EditGroup";
|
||||||
import { getGroupsLink } from "../../modules/indexResource";
|
import { getGroupsLink } from "../../modules/indexResource";
|
||||||
import SetPermissions from "../../permissions/components/SetPermissions";
|
import SetPermissions from "../../permissions/components/SetPermissions";
|
||||||
|
import {ExtensionPoint} from "@scm-manager/ui-extensions";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
name: string,
|
name: string,
|
||||||
@@ -93,6 +94,11 @@ class SingleGroup extends React.Component<Props> {
|
|||||||
|
|
||||||
const url = this.matchedUrl();
|
const url = this.matchedUrl();
|
||||||
|
|
||||||
|
const extensionProps = {
|
||||||
|
group,
|
||||||
|
url
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Page title={group.name}>
|
<Page title={group.name}>
|
||||||
<div className="columns">
|
<div className="columns">
|
||||||
@@ -107,6 +113,11 @@ class SingleGroup extends React.Component<Props> {
|
|||||||
exact
|
exact
|
||||||
component={() => <EditGroup group={group} />}
|
component={() => <EditGroup group={group} />}
|
||||||
/>
|
/>
|
||||||
|
<ExtensionPoint
|
||||||
|
name="group.route"
|
||||||
|
props={extensionProps}
|
||||||
|
renderAll={true}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path={`${url}/permissions`}
|
path={`${url}/permissions`}
|
||||||
exact
|
exact
|
||||||
@@ -134,6 +145,11 @@ class SingleGroup extends React.Component<Props> {
|
|||||||
/>
|
/>
|
||||||
<EditGroupNavLink group={group} editUrl={`${url}/edit`} />
|
<EditGroupNavLink group={group} editUrl={`${url}/edit`} />
|
||||||
<NavLink to="/groups" label={t("single-group.back-label")} />
|
<NavLink to="/groups" label={t("single-group.back-label")} />
|
||||||
|
<ExtensionPoint
|
||||||
|
name="group.navigation"
|
||||||
|
props={extensionProps}
|
||||||
|
renderAll={true}
|
||||||
|
/>
|
||||||
</Section>
|
</Section>
|
||||||
</Navigation>
|
</Navigation>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -134,15 +134,6 @@ const callFetchMe = (link: string): Promise<Me> => {
|
|||||||
.get(link)
|
.get(link)
|
||||||
.then(response => {
|
.then(response => {
|
||||||
return response.json();
|
return response.json();
|
||||||
})
|
|
||||||
.then(json => {
|
|
||||||
const { name, displayName, mail, _links } = json;
|
|
||||||
return {
|
|
||||||
name,
|
|
||||||
displayName,
|
|
||||||
mail,
|
|
||||||
_links
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ public class MapperModule extends AbstractModule {
|
|||||||
@Override
|
@Override
|
||||||
protected void configure() {
|
protected void configure() {
|
||||||
bind(UserDtoToUserMapper.class).to(Mappers.getMapper(UserDtoToUserMapper.class).getClass());
|
bind(UserDtoToUserMapper.class).to(Mappers.getMapper(UserDtoToUserMapper.class).getClass());
|
||||||
bind(MeToUserDtoMapper.class).to(Mappers.getMapper(MeToUserDtoMapper.class).getClass());
|
|
||||||
bind(UserToUserDtoMapper.class).to(Mappers.getMapper(UserToUserDtoMapper.class).getClass());
|
bind(UserToUserDtoMapper.class).to(Mappers.getMapper(UserToUserDtoMapper.class).getClass());
|
||||||
bind(UserCollectionToDtoMapper.class);
|
bind(UserCollectionToDtoMapper.class);
|
||||||
|
|
||||||
@@ -46,6 +45,7 @@ public class MapperModule extends AbstractModule {
|
|||||||
bind(MergeResultToDtoMapper.class).to(Mappers.getMapper(MergeResultToDtoMapper.class).getClass());
|
bind(MergeResultToDtoMapper.class).to(Mappers.getMapper(MergeResultToDtoMapper.class).getClass());
|
||||||
|
|
||||||
// no mapstruct required
|
// no mapstruct required
|
||||||
|
bind(MeDtoFactory.class);
|
||||||
bind(UIPluginDtoMapper.class);
|
bind(UIPluginDtoMapper.class);
|
||||||
bind(UIPluginDtoCollectionMapper.class);
|
bind(UIPluginDtoCollectionMapper.class);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import de.otto.edison.hal.HalRepresentation;
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class MeDto extends HalRepresentation {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
private String displayName;
|
||||||
|
private String mail;
|
||||||
|
private List<String> groups;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("squid:S1185") // We want to have this method available in this package
|
||||||
|
protected HalRepresentation add(Links links) {
|
||||||
|
return super.add(links);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
import org.apache.shiro.SecurityUtils;
|
||||||
|
import org.apache.shiro.subject.PrincipalCollection;
|
||||||
|
import org.apache.shiro.subject.Subject;
|
||||||
|
import sonia.scm.group.GroupNames;
|
||||||
|
import sonia.scm.user.User;
|
||||||
|
import sonia.scm.user.UserManager;
|
||||||
|
import sonia.scm.user.UserPermissions;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
import static de.otto.edison.hal.Link.link;
|
||||||
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
|
||||||
|
public class MeDtoFactory extends LinkAppenderMapper {
|
||||||
|
|
||||||
|
private final ResourceLinks resourceLinks;
|
||||||
|
private final UserManager userManager;
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
public MeDtoFactory(ResourceLinks resourceLinks, UserManager userManager) {
|
||||||
|
this.resourceLinks = resourceLinks;
|
||||||
|
this.userManager = userManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MeDto create() {
|
||||||
|
PrincipalCollection principals = getPrincipalCollection();
|
||||||
|
|
||||||
|
MeDto dto = new MeDto();
|
||||||
|
|
||||||
|
User user = principals.oneByType(User.class);
|
||||||
|
|
||||||
|
mapUserProperties(user, dto);
|
||||||
|
mapGroups(principals, dto);
|
||||||
|
|
||||||
|
appendLinks(user, dto);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void mapGroups(PrincipalCollection principals, MeDto dto) {
|
||||||
|
Iterable<String> groups = principals.oneByType(GroupNames.class);
|
||||||
|
if (groups == null) {
|
||||||
|
groups = Collections.emptySet();
|
||||||
|
}
|
||||||
|
dto.setGroups(ImmutableList.copyOf(groups));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void mapUserProperties(User user, MeDto dto) {
|
||||||
|
dto.setName(user.getName());
|
||||||
|
dto.setDisplayName(user.getDisplayName());
|
||||||
|
dto.setMail(user.getMail());
|
||||||
|
}
|
||||||
|
|
||||||
|
private PrincipalCollection getPrincipalCollection() {
|
||||||
|
Subject subject = SecurityUtils.getSubject();
|
||||||
|
return subject.getPrincipals();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void appendLinks(User user, MeDto target) {
|
||||||
|
Links.Builder linksBuilder = linkingTo().self(resourceLinks.me().self());
|
||||||
|
if (UserPermissions.delete(user).isPermitted()) {
|
||||||
|
linksBuilder.single(link("delete", resourceLinks.me().delete(target.getName())));
|
||||||
|
}
|
||||||
|
if (UserPermissions.modify(user).isPermitted()) {
|
||||||
|
linksBuilder.single(link("update", resourceLinks.me().update(target.getName())));
|
||||||
|
}
|
||||||
|
if (userManager.isTypeDefault(user) && UserPermissions.changePassword(user).isPermitted()) {
|
||||||
|
linksBuilder.single(link("password", resourceLinks.me().passwordChange()));
|
||||||
|
}
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), new Me(), user);
|
||||||
|
|
||||||
|
target.add(linksBuilder.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -3,14 +3,11 @@ package sonia.scm.api.v2.resources;
|
|||||||
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
|
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
|
||||||
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
|
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
|
||||||
import com.webcohesion.enunciate.metadata.rs.TypeHint;
|
import com.webcohesion.enunciate.metadata.rs.TypeHint;
|
||||||
import org.apache.shiro.SecurityUtils;
|
|
||||||
import org.apache.shiro.authc.credential.PasswordService;
|
import org.apache.shiro.authc.credential.PasswordService;
|
||||||
import sonia.scm.user.User;
|
|
||||||
import sonia.scm.user.UserManager;
|
import sonia.scm.user.UserManager;
|
||||||
import sonia.scm.web.VndMediaType;
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
import javax.inject.Named;
|
|
||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
@@ -28,20 +25,18 @@ import javax.ws.rs.core.UriInfo;
|
|||||||
*/
|
*/
|
||||||
@Path(MeResource.ME_PATH_V2)
|
@Path(MeResource.ME_PATH_V2)
|
||||||
public class MeResource {
|
public class MeResource {
|
||||||
public static final String ME_PATH_V2 = "v2/me/";
|
|
||||||
|
|
||||||
private final MeToUserDtoMapper meToUserDtoMapper;
|
static final String ME_PATH_V2 = "v2/me/";
|
||||||
|
|
||||||
private final IdResourceManagerAdapter<User, UserDto> adapter;
|
private final MeDtoFactory meDtoFactory;
|
||||||
private final PasswordService passwordService;
|
|
||||||
private final UserManager userManager;
|
private final UserManager userManager;
|
||||||
|
private final PasswordService passwordService;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public MeResource(MeToUserDtoMapper meToUserDtoMapper, UserManager manager, PasswordService passwordService) {
|
public MeResource(MeDtoFactory meDtoFactory, UserManager userManager, PasswordService passwordService) {
|
||||||
this.meToUserDtoMapper = meToUserDtoMapper;
|
this.meDtoFactory = meDtoFactory;
|
||||||
this.adapter = new IdResourceManagerAdapter<>(manager, User.class);
|
this.userManager = userManager;
|
||||||
this.passwordService = passwordService;
|
this.passwordService = passwordService;
|
||||||
this.userManager = manager;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -49,17 +44,15 @@ public class MeResource {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("")
|
@Path("")
|
||||||
@Produces(VndMediaType.USER)
|
@Produces(VndMediaType.ME)
|
||||||
@TypeHint(UserDto.class)
|
@TypeHint(MeDto.class)
|
||||||
@StatusCodes({
|
@StatusCodes({
|
||||||
@ResponseCode(code = 200, condition = "success"),
|
@ResponseCode(code = 200, condition = "success"),
|
||||||
@ResponseCode(code = 401, condition = "not authenticated / invalid credentials"),
|
@ResponseCode(code = 401, condition = "not authenticated / invalid credentials"),
|
||||||
@ResponseCode(code = 500, condition = "internal server error")
|
@ResponseCode(code = 500, condition = "internal server error")
|
||||||
})
|
})
|
||||||
public Response get(@Context Request request, @Context UriInfo uriInfo) {
|
public Response get(@Context Request request, @Context UriInfo uriInfo) {
|
||||||
|
return Response.ok(meDtoFactory.create()).build();
|
||||||
String id = (String) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
|
|
||||||
return adapter.get(id, meToUserDtoMapper::map);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -75,7 +68,10 @@ public class MeResource {
|
|||||||
@TypeHint(TypeHint.NO_CONTENT.class)
|
@TypeHint(TypeHint.NO_CONTENT.class)
|
||||||
@Consumes(VndMediaType.PASSWORD_CHANGE)
|
@Consumes(VndMediaType.PASSWORD_CHANGE)
|
||||||
public Response changePassword(@Valid PasswordChangeDto passwordChange) {
|
public Response changePassword(@Valid PasswordChangeDto passwordChange) {
|
||||||
userManager.changePasswordForLoggedInUser(passwordService.encryptPassword(passwordChange.getOldPassword()), passwordService.encryptPassword(passwordChange.getNewPassword()));
|
userManager.changePasswordForLoggedInUser(
|
||||||
|
passwordService.encryptPassword(passwordChange.getOldPassword()),
|
||||||
|
passwordService.encryptPassword(passwordChange.getNewPassword())
|
||||||
|
);
|
||||||
return Response.noContent().build();
|
return Response.noContent().build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
package sonia.scm.api.v2.resources;
|
|
||||||
|
|
||||||
import de.otto.edison.hal.Links;
|
|
||||||
import org.mapstruct.AfterMapping;
|
|
||||||
import org.mapstruct.Mapper;
|
|
||||||
import org.mapstruct.MappingTarget;
|
|
||||||
import sonia.scm.user.User;
|
|
||||||
import sonia.scm.user.UserManager;
|
|
||||||
import sonia.scm.user.UserPermissions;
|
|
||||||
|
|
||||||
import javax.inject.Inject;
|
|
||||||
|
|
||||||
import static de.otto.edison.hal.Link.link;
|
|
||||||
import static de.otto.edison.hal.Links.linkingTo;
|
|
||||||
|
|
||||||
@Mapper
|
|
||||||
public abstract class MeToUserDtoMapper extends UserToUserDtoMapper {
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
private UserManager userManager;
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
private ResourceLinks resourceLinks;
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
@AfterMapping
|
|
||||||
protected void appendLinks(User user, @MappingTarget UserDto target) {
|
|
||||||
Links.Builder linksBuilder = linkingTo().self(resourceLinks.me().self());
|
|
||||||
if (UserPermissions.delete(user).isPermitted()) {
|
|
||||||
linksBuilder.single(link("delete", resourceLinks.me().delete(target.getName())));
|
|
||||||
}
|
|
||||||
if (UserPermissions.modify(user).isPermitted()) {
|
|
||||||
linksBuilder.single(link("update", resourceLinks.me().update(target.getName())));
|
|
||||||
}
|
|
||||||
if (userManager.isTypeDefault(user)) {
|
|
||||||
linksBuilder.single(link("password", resourceLinks.me().passwordChange()));
|
|
||||||
}
|
|
||||||
|
|
||||||
appendLinks(new EdisonLinkAppender(linksBuilder), new Me(), user);
|
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -101,11 +101,11 @@ public class BearerRealm extends AuthenticatingRealm
|
|||||||
BearerToken bt = (BearerToken) token;
|
BearerToken bt = (BearerToken) token;
|
||||||
AccessToken accessToken = tokenResolver.resolve(bt);
|
AccessToken accessToken = tokenResolver.resolve(bt);
|
||||||
|
|
||||||
return helper.getAuthenticationInfo(
|
return helper.authenticationInfoBuilder(accessToken.getSubject())
|
||||||
accessToken.getSubject(),
|
.withCredentials(bt.getCredentials())
|
||||||
bt.getCredentials(),
|
.withScope(Scopes.fromClaims(accessToken.getClaims()))
|
||||||
Scopes.fromClaims(accessToken.getClaims())
|
.withGroups(accessToken.getGroups())
|
||||||
);
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import sonia.scm.cache.Cache;
|
import sonia.scm.cache.Cache;
|
||||||
import sonia.scm.cache.CacheManager;
|
import sonia.scm.cache.CacheManager;
|
||||||
|
import sonia.scm.config.ScmConfiguration;
|
||||||
import sonia.scm.group.GroupNames;
|
import sonia.scm.group.GroupNames;
|
||||||
import sonia.scm.group.GroupPermissions;
|
import sonia.scm.group.GroupPermissions;
|
||||||
import sonia.scm.plugin.Extension;
|
import sonia.scm.plugin.Extension;
|
||||||
@@ -75,9 +76,6 @@ import java.util.Set;
|
|||||||
public class DefaultAuthorizationCollector implements AuthorizationCollector
|
public class DefaultAuthorizationCollector implements AuthorizationCollector
|
||||||
{
|
{
|
||||||
|
|
||||||
// TODO move to util class
|
|
||||||
private static final String SEPARATOR = System.getProperty("line.separator", "\n");
|
|
||||||
|
|
||||||
/** Field description */
|
/** Field description */
|
||||||
private static final String ADMIN_PERMISSION = "*";
|
private static final String ADMIN_PERMISSION = "*";
|
||||||
|
|
||||||
@@ -97,14 +95,16 @@ public class DefaultAuthorizationCollector implements AuthorizationCollector
|
|||||||
*
|
*
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
|
* @param configuration
|
||||||
* @param cacheManager
|
* @param cacheManager
|
||||||
* @param repositoryDAO
|
* @param repositoryDAO
|
||||||
* @param securitySystem
|
* @param securitySystem
|
||||||
*/
|
*/
|
||||||
@Inject
|
@Inject
|
||||||
public DefaultAuthorizationCollector(CacheManager cacheManager,
|
public DefaultAuthorizationCollector(ScmConfiguration configuration, CacheManager cacheManager,
|
||||||
RepositoryDAO repositoryDAO, SecuritySystem securitySystem)
|
RepositoryDAO repositoryDAO, SecuritySystem securitySystem)
|
||||||
{
|
{
|
||||||
|
this.configuration = configuration;
|
||||||
this.cache = cacheManager.getCache(CACHE_NAME);
|
this.cache = cacheManager.getCache(CACHE_NAME);
|
||||||
this.repositoryDAO = repositoryDAO;
|
this.repositoryDAO = repositoryDAO;
|
||||||
this.securitySystem = securitySystem;
|
this.securitySystem = securitySystem;
|
||||||
@@ -238,7 +238,7 @@ public class DefaultAuthorizationCollector implements AuthorizationCollector
|
|||||||
Set<String> roles;
|
Set<String> roles;
|
||||||
Set<String> permissions;
|
Set<String> permissions;
|
||||||
|
|
||||||
if (user.isAdmin())
|
if (isAdmin(user, groups))
|
||||||
{
|
{
|
||||||
if (logger.isDebugEnabled())
|
if (logger.isDebugEnabled())
|
||||||
{
|
{
|
||||||
@@ -269,6 +269,37 @@ public class DefaultAuthorizationCollector implements AuthorizationCollector
|
|||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isAdmin(User user, GroupNames groups) {
|
||||||
|
boolean admin = user.isAdmin();
|
||||||
|
if (admin) {
|
||||||
|
logger.debug("user {} is marked as admin, because of the user flag", user.getName());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (isUserAdminInConfiguration(user)) {
|
||||||
|
logger.debug("user {} is marked as admin, because of the admin user configuration", user.getName());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return isUserAdminInGroupConfiguration(user, groups);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isUserAdminInGroupConfiguration(User user, GroupNames groups) {
|
||||||
|
Set<String> adminGroups = configuration.getAdminGroups();
|
||||||
|
if (adminGroups != null && groups != null) {
|
||||||
|
for (String group : groups) {
|
||||||
|
if (adminGroups.contains(group)) {
|
||||||
|
logger.debug("user {} is marked as admin, because of the admin group configuration for group {}", user.getName(), group);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isUserAdminInConfiguration(User user) {
|
||||||
|
Set<String> adminUsers = configuration.getAdminUsers();
|
||||||
|
return adminUsers != null && adminUsers.contains(user.getName());
|
||||||
|
}
|
||||||
|
|
||||||
private String getGroupAutocompletePermission() {
|
private String getGroupAutocompletePermission() {
|
||||||
return GroupPermissions.autocomplete().asShiroString();
|
return GroupPermissions.autocomplete().asShiroString();
|
||||||
}
|
}
|
||||||
@@ -372,6 +403,8 @@ public class DefaultAuthorizationCollector implements AuthorizationCollector
|
|||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
//~--- fields ---------------------------------------------------------------
|
||||||
|
|
||||||
|
private final ScmConfiguration configuration;
|
||||||
|
|
||||||
/** authorization cache */
|
/** authorization cache */
|
||||||
private final Cache<CacheKey, AuthorizationInfo> cache;
|
private final Cache<CacheKey, AuthorizationInfo> cache;
|
||||||
|
|
||||||
|
|||||||
@@ -30,12 +30,15 @@
|
|||||||
*/
|
*/
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableSet;
|
||||||
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.Claims;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
import static java.util.Optional.ofNullable;
|
import static java.util.Optional.ofNullable;
|
||||||
|
|
||||||
@@ -49,6 +52,8 @@ public final class JwtAccessToken implements AccessToken {
|
|||||||
|
|
||||||
public static final String REFRESHABLE_UNTIL_CLAIM_KEY = "scm-manager.refreshExpiration";
|
public static final String REFRESHABLE_UNTIL_CLAIM_KEY = "scm-manager.refreshExpiration";
|
||||||
public static final String PARENT_TOKEN_ID_CLAIM_KEY = "scm-manager.parentTokenId";
|
public static final String PARENT_TOKEN_ID_CLAIM_KEY = "scm-manager.parentTokenId";
|
||||||
|
public static final String GROUPS_CLAIM_KEY = "scm-manager.groups";
|
||||||
|
|
||||||
private final Claims claims;
|
private final Claims claims;
|
||||||
private final String compact;
|
private final String compact;
|
||||||
|
|
||||||
@@ -103,6 +108,16 @@ public final class JwtAccessToken implements AccessToken {
|
|||||||
return Optional.ofNullable(claims.get(key));
|
return Optional.ofNullable(claims.get(key));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Set<String> getGroups() {
|
||||||
|
Iterable<String> groups = claims.get(GROUPS_CLAIM_KEY, Iterable.class);
|
||||||
|
if (groups != null) {
|
||||||
|
return ImmutableSet.copyOf(groups);
|
||||||
|
}
|
||||||
|
return ImmutableSet.of();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String compact() {
|
public String compact() {
|
||||||
return compact;
|
return compact;
|
||||||
|
|||||||
@@ -39,9 +39,12 @@ import io.jsonwebtoken.SignatureAlgorithm;
|
|||||||
|
|
||||||
import java.time.Clock;
|
import java.time.Clock;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import org.apache.shiro.SecurityUtils;
|
import org.apache.shiro.SecurityUtils;
|
||||||
import org.apache.shiro.subject.Subject;
|
import org.apache.shiro.subject.Subject;
|
||||||
@@ -74,6 +77,7 @@ public final class JwtAccessTokenBuilder implements AccessTokenBuilder {
|
|||||||
private Instant refreshExpiration;
|
private Instant refreshExpiration;
|
||||||
private String parentKeyId;
|
private String parentKeyId;
|
||||||
private Scope scope = Scope.empty();
|
private Scope scope = Scope.empty();
|
||||||
|
private Set<String> groups = new HashSet<>();
|
||||||
|
|
||||||
private final Map<String,Object> custom = Maps.newHashMap();
|
private final Map<String,Object> custom = Maps.newHashMap();
|
||||||
|
|
||||||
@@ -134,6 +138,12 @@ public final class JwtAccessTokenBuilder implements AccessTokenBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public JwtAccessTokenBuilder groups(String... groups) {
|
||||||
|
Collections.addAll(this.groups, groups);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
JwtAccessTokenBuilder refreshExpiration(Instant refreshExpiration) {
|
JwtAccessTokenBuilder refreshExpiration(Instant refreshExpiration) {
|
||||||
this.refreshExpiration = refreshExpiration;
|
this.refreshExpiration = refreshExpiration;
|
||||||
this.refreshableFor = 0;
|
this.refreshableFor = 0;
|
||||||
@@ -195,6 +205,10 @@ public final class JwtAccessTokenBuilder implements AccessTokenBuilder {
|
|||||||
claims.setIssuer(issuer);
|
claims.setIssuer(issuer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!groups.isEmpty()) {
|
||||||
|
claims.put(JwtAccessToken.GROUPS_CLAIM_KEY, groups);
|
||||||
|
}
|
||||||
|
|
||||||
// sign token and create compact version
|
// sign token and create compact version
|
||||||
String compact = Jwts.builder()
|
String compact = Jwts.builder()
|
||||||
.setClaims(claims)
|
.setClaims(claims)
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.apache.shiro.subject.PrincipalCollection;
|
||||||
|
import org.apache.shiro.subject.Subject;
|
||||||
|
import org.apache.shiro.util.ThreadContext;
|
||||||
|
import org.assertj.core.util.Lists;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
|
import sonia.scm.group.GroupNames;
|
||||||
|
import sonia.scm.user.User;
|
||||||
|
import sonia.scm.user.UserManager;
|
||||||
|
import sonia.scm.user.UserPermissions;
|
||||||
|
import sonia.scm.user.UserTestData;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class MeDtoFactoryTest {
|
||||||
|
|
||||||
|
private final URI baseUri = URI.create("https://scm.hitchhiker.com/scm/");
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserManager userManager;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Subject subject;
|
||||||
|
|
||||||
|
private MeDtoFactory meDtoFactory;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUpContext() {
|
||||||
|
ThreadContext.bind(subject);
|
||||||
|
ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri);
|
||||||
|
meDtoFactory = new MeDtoFactory(resourceLinks, userManager);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void unbindSubject() {
|
||||||
|
ThreadContext.unbindSubject();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCreateMeDtoFromUser() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getName()).isEqualTo("trillian");
|
||||||
|
assertThat(dto.getDisplayName()).isEqualTo("Tricia McMillan");
|
||||||
|
assertThat(dto.getMail()).isEqualTo("tricia.mcmillan@hitchhiker.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCreateMeDtoWithEmptyGroups() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getGroups()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCreateMeDtoWithGroups() {
|
||||||
|
prepareSubject(UserTestData.createTrillian(), "HeartOfGold", "Puzzle42");
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getGroups()).containsOnly("HeartOfGold", "Puzzle42");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void prepareSubject(User user, String... groups) {
|
||||||
|
PrincipalCollection collection = mock(PrincipalCollection.class);
|
||||||
|
when(subject.getPrincipals()).thenReturn(collection);
|
||||||
|
when(collection.oneByType(any(Class.class))).then(ic -> {
|
||||||
|
Class<?> type = ic.getArgument(0);
|
||||||
|
if (type.isAssignableFrom(User.class)) {
|
||||||
|
return user;
|
||||||
|
} else if (type.isAssignableFrom(GroupNames.class)) {
|
||||||
|
return new GroupNames(Lists.newArrayList(groups));
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendSelfLink() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("self").get().getHref()).isEqualTo("https://scm.hitchhiker.com/scm/v2/me/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendDeleteLink() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
when(subject.isPermitted("user:delete:trillian")).thenReturn(true);
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("delete").get().getHref()).isEqualTo("https://scm.hitchhiker.com/scm/v2/users/trillian");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldNotAppendDeleteLink() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("delete")).isNotPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendUpdateLink() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
when(subject.isPermitted("user:modify:trillian")).thenReturn(true);
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("update").get().getHref()).isEqualTo("https://scm.hitchhiker.com/scm/v2/users/trillian");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldNotAppendUpdateLink() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("update")).isNotPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldGetPasswordLinkOnlyForDefaultUserType() {
|
||||||
|
User user = UserTestData.createTrillian();
|
||||||
|
prepareSubject(user);
|
||||||
|
|
||||||
|
when(subject.isPermitted("user:changePassword:trillian")).thenReturn(true);
|
||||||
|
when(userManager.isTypeDefault(user)).thenReturn(true);
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("password").get().getHref()).isEqualTo("https://scm.hitchhiker.com/scm/v2/me/password");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldNotGetPasswordLinkWithoutPermision() {
|
||||||
|
User user = UserTestData.createTrillian();
|
||||||
|
prepareSubject(user);
|
||||||
|
|
||||||
|
when(userManager.isTypeDefault(user)).thenReturn(true);
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("password")).isNotPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldNotGetPasswordLinkForNonDefaultUsers() {
|
||||||
|
User user = UserTestData.createTrillian();
|
||||||
|
prepareSubject(user);
|
||||||
|
|
||||||
|
when(subject.isPermitted("user:changePassword:trillian")).thenReturn(true);
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("password")).isNotPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendLinks() {
|
||||||
|
prepareSubject(UserTestData.createTrillian());
|
||||||
|
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
meDtoFactory.setRegistry(registry);
|
||||||
|
|
||||||
|
registry.register(Me.class, (ctx, appender) -> {
|
||||||
|
User user = ctx.oneRequireByType(User.class);
|
||||||
|
appender.appendOne("profile", "http://hitchhiker.com/users/" + user.getName());
|
||||||
|
});
|
||||||
|
|
||||||
|
MeDto dto = meDtoFactory.create();
|
||||||
|
assertThat(dto.getLinks().getLinkBy("profile").get().getHref()).isEqualTo("http://hitchhiker.com/users/trillian");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -2,12 +2,14 @@ package sonia.scm.api.v2.resources;
|
|||||||
|
|
||||||
import com.github.sdorra.shiro.ShiroRule;
|
import com.github.sdorra.shiro.ShiroRule;
|
||||||
import com.github.sdorra.shiro.SubjectAware;
|
import com.github.sdorra.shiro.SubjectAware;
|
||||||
|
import org.apache.shiro.SecurityUtils;
|
||||||
import org.apache.shiro.authc.credential.PasswordService;
|
import org.apache.shiro.authc.credential.PasswordService;
|
||||||
|
import org.apache.shiro.subject.PrincipalCollection;
|
||||||
|
import org.apache.shiro.subject.Subject;
|
||||||
import org.jboss.resteasy.core.Dispatcher;
|
import org.jboss.resteasy.core.Dispatcher;
|
||||||
import org.jboss.resteasy.mock.MockHttpRequest;
|
import org.jboss.resteasy.mock.MockHttpRequest;
|
||||||
import org.jboss.resteasy.mock.MockHttpResponse;
|
import org.jboss.resteasy.mock.MockHttpResponse;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Ignore;
|
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
@@ -19,7 +21,6 @@ import sonia.scm.user.User;
|
|||||||
import sonia.scm.user.UserManager;
|
import sonia.scm.user.UserManager;
|
||||||
import sonia.scm.web.VndMediaType;
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
import javax.lang.model.util.Types;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
@@ -27,11 +28,7 @@ import java.net.URISyntaxException;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.Mockito.*;
|
||||||
import static org.mockito.Mockito.doNothing;
|
|
||||||
import static org.mockito.Mockito.doThrow;
|
|
||||||
import static org.mockito.Mockito.verify;
|
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.mockito.MockitoAnnotations.initMocks;
|
import static org.mockito.MockitoAnnotations.initMocks;
|
||||||
import static sonia.scm.api.v2.resources.DispatcherMock.createDispatcher;
|
import static sonia.scm.api.v2.resources.DispatcherMock.createDispatcher;
|
||||||
|
|
||||||
@@ -57,7 +54,7 @@ public class MeResourceTest {
|
|||||||
private UserManager userManager;
|
private UserManager userManager;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private MeToUserDtoMapperImpl userToDtoMapper;
|
private MeDtoFactory meDtoFactory;
|
||||||
|
|
||||||
private ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
|
private ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
|
||||||
|
|
||||||
@@ -66,7 +63,7 @@ public class MeResourceTest {
|
|||||||
private User originalUser;
|
private User originalUser;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void prepareEnvironment() throws Exception {
|
public void prepareEnvironment() {
|
||||||
initMocks(this);
|
initMocks(this);
|
||||||
originalUser = createDummyUser("trillian");
|
originalUser = createDummyUser("trillian");
|
||||||
when(userManager.create(userCaptor.capture())).thenAnswer(invocation -> invocation.getArguments()[0]);
|
when(userManager.create(userCaptor.capture())).thenAnswer(invocation -> invocation.getArguments()[0]);
|
||||||
@@ -74,17 +71,18 @@ public class MeResourceTest {
|
|||||||
doNothing().when(userManager).delete(userCaptor.capture());
|
doNothing().when(userManager).delete(userCaptor.capture());
|
||||||
when(userManager.isTypeDefault(userCaptor.capture())).thenCallRealMethod();
|
when(userManager.isTypeDefault(userCaptor.capture())).thenCallRealMethod();
|
||||||
when(userManager.getDefaultType()).thenReturn("xml");
|
when(userManager.getDefaultType()).thenReturn("xml");
|
||||||
MeResource meResource = new MeResource(userToDtoMapper, userManager, passwordService);
|
MeResource meResource = new MeResource(meDtoFactory, userManager, passwordService);
|
||||||
when(uriInfo.getApiRestUri()).thenReturn(URI.create("/"));
|
when(uriInfo.getApiRestUri()).thenReturn(URI.create("/"));
|
||||||
when(scmPathInfoStore.get()).thenReturn(uriInfo);
|
when(scmPathInfoStore.get()).thenReturn(uriInfo);
|
||||||
dispatcher = createDispatcher(meResource);
|
dispatcher = createDispatcher(meResource);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@SubjectAware(username = "trillian", password = "secret")
|
|
||||||
public void shouldReturnCurrentlyAuthenticatedUser() throws URISyntaxException {
|
public void shouldReturnCurrentlyAuthenticatedUser() throws URISyntaxException {
|
||||||
|
applyUserToSubject(originalUser);
|
||||||
|
|
||||||
MockHttpRequest request = MockHttpRequest.get("/" + MeResource.ME_PATH_V2);
|
MockHttpRequest request = MockHttpRequest.get("/" + MeResource.ME_PATH_V2);
|
||||||
request.accept(VndMediaType.USER);
|
request.accept(VndMediaType.ME);
|
||||||
MockHttpResponse response = new MockHttpResponse();
|
MockHttpResponse response = new MockHttpResponse();
|
||||||
|
|
||||||
dispatcher.invoke(request, response);
|
dispatcher.invoke(request, response);
|
||||||
@@ -95,8 +93,17 @@ public class MeResourceTest {
|
|||||||
assertTrue(response.getContentAsString().contains("\"delete\":{\"href\":\"/v2/users/trillian\"}"));
|
assertTrue(response.getContentAsString().contains("\"delete\":{\"href\":\"/v2/users/trillian\"}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void applyUserToSubject(User user) {
|
||||||
|
// use spy here to keep applied permissions from ShiroRule
|
||||||
|
Subject subject = spy(SecurityUtils.getSubject());
|
||||||
|
PrincipalCollection collection = mock(PrincipalCollection.class);
|
||||||
|
when(collection.getPrimaryPrincipal()).thenReturn(user.getName());
|
||||||
|
when(subject.getPrincipals()).thenReturn(collection);
|
||||||
|
when(collection.oneByType(User.class)).thenReturn(user);
|
||||||
|
shiro.setSubject(subject);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@SubjectAware(username = "trillian", password = "secret")
|
|
||||||
public void shouldEncryptPasswordBeforeChanging() throws Exception {
|
public void shouldEncryptPasswordBeforeChanging() throws Exception {
|
||||||
String newPassword = "pwd123";
|
String newPassword = "pwd123";
|
||||||
String encryptedNewPassword = "encrypted123";
|
String encryptedNewPassword = "encrypted123";
|
||||||
@@ -124,7 +131,6 @@ public class MeResourceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@SubjectAware(username = "trillian", password = "secret")
|
|
||||||
public void shouldGet400OnMissingOldPassword() throws Exception {
|
public void shouldGet400OnMissingOldPassword() throws Exception {
|
||||||
originalUser.setType("not an xml type");
|
originalUser.setType("not an xml type");
|
||||||
String newPassword = "pwd123";
|
String newPassword = "pwd123";
|
||||||
@@ -141,7 +147,6 @@ public class MeResourceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@SubjectAware(username = "trillian", password = "secret")
|
|
||||||
public void shouldGet400OnMissingEmptyPassword() throws Exception {
|
public void shouldGet400OnMissingEmptyPassword() throws Exception {
|
||||||
String newPassword = "pwd123";
|
String newPassword = "pwd123";
|
||||||
String oldPassword = "";
|
String oldPassword = "";
|
||||||
@@ -158,7 +163,6 @@ public class MeResourceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@SubjectAware(username = "trillian", password = "secret")
|
|
||||||
public void shouldMapExceptionFromManager() throws Exception {
|
public void shouldMapExceptionFromManager() throws Exception {
|
||||||
String newPassword = "pwd123";
|
String newPassword = "pwd123";
|
||||||
String oldPassword = "secret";
|
String oldPassword = "secret";
|
||||||
|
|||||||
@@ -1,151 +0,0 @@
|
|||||||
package sonia.scm.api.v2.resources;
|
|
||||||
|
|
||||||
import org.apache.shiro.subject.Subject;
|
|
||||||
import org.apache.shiro.subject.support.SubjectThreadState;
|
|
||||||
import org.apache.shiro.util.ThreadContext;
|
|
||||||
import org.apache.shiro.util.ThreadState;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.mockito.InjectMocks;
|
|
||||||
import org.mockito.Mock;
|
|
||||||
import sonia.scm.user.User;
|
|
||||||
import sonia.scm.user.UserManager;
|
|
||||||
import sonia.scm.user.UserTestData;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
|
||||||
import static org.mockito.Mockito.mock;
|
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.mockito.MockitoAnnotations.initMocks;
|
|
||||||
|
|
||||||
public class MeToUserDtoMapperTest {
|
|
||||||
|
|
||||||
private final URI baseUri = URI.create("http://example.com/base/");
|
|
||||||
@SuppressWarnings("unused") // Is injected
|
|
||||||
private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri);
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private UserManager userManager;
|
|
||||||
|
|
||||||
@InjectMocks
|
|
||||||
private MeToUserDtoMapperImpl mapper;
|
|
||||||
|
|
||||||
private final Subject subject = mock(Subject.class);
|
|
||||||
private final ThreadState subjectThreadState = new SubjectThreadState(subject);
|
|
||||||
|
|
||||||
private URI expectedBaseUri;
|
|
||||||
private URI expectedUserBaseUri;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void init() {
|
|
||||||
initMocks(this);
|
|
||||||
when(userManager.getDefaultType()).thenReturn("xml");
|
|
||||||
expectedBaseUri = baseUri.resolve(MeResource.ME_PATH_V2 + "/");
|
|
||||||
expectedUserBaseUri = baseUri.resolve(UserRootResource.USERS_PATH_V2 + "/");
|
|
||||||
subjectThreadState.bind();
|
|
||||||
ThreadContext.bind(subject);
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void unbindSubject() {
|
|
||||||
ThreadContext.unbindSubject();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldMapTheUpdateLink() {
|
|
||||||
User user = createDefaultUser();
|
|
||||||
when(subject.isPermitted("user:modify:abc")).thenReturn(true);
|
|
||||||
|
|
||||||
UserDto userDto = mapper.map(user);
|
|
||||||
assertEquals("expected update link", expectedUserBaseUri.resolve("abc").toString(), userDto.getLinks().getLinkBy("update").get().getHref());
|
|
||||||
|
|
||||||
when(subject.isPermitted("user:modify:abc")).thenReturn(false);
|
|
||||||
userDto = mapper.map(user);
|
|
||||||
assertFalse("expected no update link", userDto.getLinks().getLinkBy("update").isPresent());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldMapTheSelfLink() {
|
|
||||||
User user = createDefaultUser();
|
|
||||||
when(subject.isPermitted("user:modify:abc")).thenReturn(true);
|
|
||||||
|
|
||||||
UserDto userDto = mapper.map(user);
|
|
||||||
assertEquals("expected self link", expectedBaseUri.toString(), userDto.getLinks().getLinkBy("self").get().getHref());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldMapTheDeleteLink() {
|
|
||||||
User user = createDefaultUser();
|
|
||||||
when(subject.isPermitted("user:delete:abc")).thenReturn(true);
|
|
||||||
|
|
||||||
UserDto userDto = mapper.map(user);
|
|
||||||
assertEquals("expected update link", expectedUserBaseUri.resolve("abc").toString(), userDto.getLinks().getLinkBy("delete").get().getHref());
|
|
||||||
|
|
||||||
when(subject.isPermitted("user:delete:abc")).thenReturn(false);
|
|
||||||
userDto = mapper.map(user);
|
|
||||||
assertFalse("expected no delete link", userDto.getLinks().getLinkBy("delete").isPresent());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldGetPasswordLinkOnlyForDefaultUserType() {
|
|
||||||
User user = createDefaultUser();
|
|
||||||
when(subject.isPermitted("user:modify:abc")).thenReturn(true);
|
|
||||||
when(userManager.isTypeDefault(eq(user))).thenReturn(true);
|
|
||||||
|
|
||||||
UserDto userDto = mapper.map(user);
|
|
||||||
|
|
||||||
assertEquals("expected password link with modify permission", expectedBaseUri.resolve("password").toString(), userDto.getLinks().getLinkBy("password").get().getHref());
|
|
||||||
|
|
||||||
when(subject.isPermitted("user:modify:abc")).thenReturn(false);
|
|
||||||
userDto = mapper.map(user);
|
|
||||||
assertEquals("expected password link on mission modify permission", expectedBaseUri.resolve("password").toString(), userDto.getLinks().getLinkBy("password").get().getHref());
|
|
||||||
|
|
||||||
when(userManager.isTypeDefault(eq(user))).thenReturn(false);
|
|
||||||
|
|
||||||
userDto = mapper.map(user);
|
|
||||||
|
|
||||||
assertFalse("expected no password link", userDto.getLinks().getLinkBy("password").isPresent());
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldGetEmptyPasswordProperty() {
|
|
||||||
User user = createDefaultUser();
|
|
||||||
user.setPassword("myHighSecurePassword");
|
|
||||||
when(subject.isPermitted("user:modify:abc")).thenReturn(true);
|
|
||||||
|
|
||||||
UserDto userDto = mapper.map(user);
|
|
||||||
|
|
||||||
assertThat(userDto.getPassword()).as("hide password for the me resource").isBlank();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldAppendLinks() {
|
|
||||||
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
|
||||||
registry.register(Me.class, (ctx, appender) -> {
|
|
||||||
User user = ctx.oneRequireByType(User.class);
|
|
||||||
appender.appendOne("profile", "http://hitchhiker.com/users/" + user.getName());
|
|
||||||
});
|
|
||||||
mapper.setRegistry(registry);
|
|
||||||
|
|
||||||
User trillian = UserTestData.createTrillian();
|
|
||||||
UserDto dto = mapper.map(trillian);
|
|
||||||
|
|
||||||
assertEquals("http://hitchhiker.com/users/trillian", dto.getLinks().getLinkBy("profile").get().getHref());
|
|
||||||
}
|
|
||||||
|
|
||||||
private User createDefaultUser() {
|
|
||||||
User user = new User();
|
|
||||||
user.setName("abc");
|
|
||||||
user.setCreationDate(1L);
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -31,11 +31,15 @@
|
|||||||
|
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableSet;
|
||||||
import org.apache.shiro.authc.AuthenticationInfo;
|
import org.apache.shiro.authc.AuthenticationInfo;
|
||||||
|
import org.apache.shiro.authc.SimpleAuthenticationInfo;
|
||||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Answers;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.invocation.InvocationOnMock;
|
import org.mockito.invocation.InvocationOnMock;
|
||||||
@@ -43,6 +47,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
|||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
@@ -65,6 +70,9 @@ class BearerRealmTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private DAORealmHelper realmHelper;
|
private DAORealmHelper realmHelper;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private DAORealmHelper.AuthenticationInfoBuilder builder;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private AccessTokenResolver accessTokenResolver;
|
private AccessTokenResolver accessTokenResolver;
|
||||||
|
|
||||||
@@ -84,15 +92,19 @@ class BearerRealmTest {
|
|||||||
void shouldDoGetAuthentication() {
|
void shouldDoGetAuthentication() {
|
||||||
BearerToken bearerToken = BearerToken.valueOf("__bearer__");
|
BearerToken bearerToken = BearerToken.valueOf("__bearer__");
|
||||||
AccessToken accessToken = mock(AccessToken.class);
|
AccessToken accessToken = mock(AccessToken.class);
|
||||||
when(accessToken.getSubject()).thenReturn("trillian");
|
|
||||||
when(accessToken.getClaims()).thenReturn(new HashMap<>());
|
|
||||||
|
|
||||||
|
Set<String> groups = ImmutableSet.of("HeartOfGold", "Puzzle42");
|
||||||
|
|
||||||
|
when(accessToken.getSubject()).thenReturn("trillian");
|
||||||
|
when(accessToken.getGroups()).thenReturn(groups);
|
||||||
|
when(accessToken.getClaims()).thenReturn(new HashMap<>());
|
||||||
when(accessTokenResolver.resolve(bearerToken)).thenReturn(accessToken);
|
when(accessTokenResolver.resolve(bearerToken)).thenReturn(accessToken);
|
||||||
|
|
||||||
// we have to use answer, because we could not mock the result of Scopes
|
when(realmHelper.authenticationInfoBuilder("trillian")).thenReturn(builder);
|
||||||
when(realmHelper.getAuthenticationInfo(
|
when(builder.withGroups(groups)).thenReturn(builder);
|
||||||
anyString(), anyString(), any(Scope.class)
|
when(builder.withCredentials("__bearer__")).thenReturn(builder);
|
||||||
)).thenAnswer(createAnswer("trillian", "__bearer__", true));
|
when(builder.withScope(any(Scope.class))).thenReturn(builder);
|
||||||
|
when(builder.build()).thenReturn(authenticationInfo);
|
||||||
|
|
||||||
AuthenticationInfo result = realm.doGetAuthenticationInfo(bearerToken);
|
AuthenticationInfo result = realm.doGetAuthenticationInfo(bearerToken);
|
||||||
assertThat(result).isSameAs(authenticationInfo);
|
assertThat(result).isSameAs(authenticationInfo);
|
||||||
@@ -102,25 +114,4 @@ class BearerRealmTest {
|
|||||||
void shouldThrowIllegalArgumentExceptionForWrongTypeOfToken() {
|
void shouldThrowIllegalArgumentExceptionForWrongTypeOfToken() {
|
||||||
assertThrows(IllegalArgumentException.class, () -> realm.doGetAuthenticationInfo(new UsernamePasswordToken()));
|
assertThrows(IllegalArgumentException.class, () -> realm.doGetAuthenticationInfo(new UsernamePasswordToken()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Answer<AuthenticationInfo> createAnswer(String expectedSubject, String expectedCredentials, boolean scopeEmpty) {
|
|
||||||
return (iom) -> {
|
|
||||||
String subject = iom.getArgument(0);
|
|
||||||
assertThat(subject).isEqualTo(expectedSubject);
|
|
||||||
String credentials = iom.getArgument(1);
|
|
||||||
assertThat(credentials).isEqualTo(expectedCredentials);
|
|
||||||
Scope scope = iom.getArgument(2);
|
|
||||||
assertThat(scope.isEmpty()).isEqualTo(scopeEmpty);
|
|
||||||
|
|
||||||
return authenticationInfo;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private class MyAnswer implements Answer<AuthenticationInfo> {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public AuthenticationInfo answer(InvocationOnMock invocationOnMock) throws Throwable {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ package sonia.scm.security;
|
|||||||
|
|
||||||
import com.github.sdorra.shiro.ShiroRule;
|
import com.github.sdorra.shiro.ShiroRule;
|
||||||
import com.github.sdorra.shiro.SubjectAware;
|
import com.github.sdorra.shiro.SubjectAware;
|
||||||
|
import com.google.common.collect.ImmutableSet;
|
||||||
import com.google.common.collect.Lists;
|
import com.google.common.collect.Lists;
|
||||||
import org.apache.shiro.authz.AuthorizationInfo;
|
import org.apache.shiro.authz.AuthorizationInfo;
|
||||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||||
@@ -48,6 +49,7 @@ import org.mockito.Mockito;
|
|||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
import sonia.scm.cache.Cache;
|
import sonia.scm.cache.Cache;
|
||||||
import sonia.scm.cache.CacheManager;
|
import sonia.scm.cache.CacheManager;
|
||||||
|
import sonia.scm.config.ScmConfiguration;
|
||||||
import sonia.scm.group.GroupNames;
|
import sonia.scm.group.GroupNames;
|
||||||
import sonia.scm.repository.PermissionType;
|
import sonia.scm.repository.PermissionType;
|
||||||
import sonia.scm.repository.Repository;
|
import sonia.scm.repository.Repository;
|
||||||
@@ -76,6 +78,8 @@ import static org.mockito.Mockito.when;
|
|||||||
@RunWith(MockitoJUnitRunner.class)
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
public class DefaultAuthorizationCollectorTest {
|
public class DefaultAuthorizationCollectorTest {
|
||||||
|
|
||||||
|
private ScmConfiguration configuration;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private Cache cache;
|
private Cache cache;
|
||||||
|
|
||||||
@@ -99,8 +103,38 @@ public class DefaultAuthorizationCollectorTest {
|
|||||||
@Before
|
@Before
|
||||||
public void setUp(){
|
public void setUp(){
|
||||||
when(cacheManager.getCache(Mockito.any(String.class))).thenReturn(cache);
|
when(cacheManager.getCache(Mockito.any(String.class))).thenReturn(cache);
|
||||||
|
configuration = new ScmConfiguration();
|
||||||
|
collector = new DefaultAuthorizationCollector(configuration, cacheManager, repositoryDAO, securitySystem);
|
||||||
|
}
|
||||||
|
|
||||||
collector = new DefaultAuthorizationCollector(cacheManager, repositoryDAO, securitySystem);
|
@Test
|
||||||
|
@SubjectAware(
|
||||||
|
configuration = "classpath:sonia/scm/shiro-001.ini"
|
||||||
|
)
|
||||||
|
public void shouldGetAdminPrivilegedByConfiguration() {
|
||||||
|
configuration.setAdminUsers(ImmutableSet.of("trillian"));
|
||||||
|
authenticate(UserTestData.createTrillian(), "main");
|
||||||
|
|
||||||
|
AuthorizationInfo authInfo = collector.collect();
|
||||||
|
assertIsAdmin(authInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertIsAdmin(AuthorizationInfo authInfo) {
|
||||||
|
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER, Role.ADMIN));
|
||||||
|
assertThat(authInfo.getObjectPermissions(), nullValue());
|
||||||
|
assertThat(authInfo.getStringPermissions(), Matchers.contains("*"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SubjectAware(
|
||||||
|
configuration = "classpath:sonia/scm/shiro-001.ini"
|
||||||
|
)
|
||||||
|
public void shouldGetAdminPrivilegedByGroupConfiguration() {
|
||||||
|
configuration.setAdminGroups(ImmutableSet.of("heartOfGold"));
|
||||||
|
authenticate(UserTestData.createTrillian(), "heartOfGold");
|
||||||
|
|
||||||
|
AuthorizationInfo authInfo = collector.collect();
|
||||||
|
assertIsAdmin(authInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -142,7 +176,7 @@ public class DefaultAuthorizationCollectorTest {
|
|||||||
public void testCollectWithCache() {
|
public void testCollectWithCache() {
|
||||||
authenticate(UserTestData.createTrillian(), "main");
|
authenticate(UserTestData.createTrillian(), "main");
|
||||||
|
|
||||||
AuthorizationInfo authInfo = collector.collect();
|
collector.collect();
|
||||||
verify(cache).put(any(), any());
|
verify(cache).put(any(), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,9 +210,7 @@ public class DefaultAuthorizationCollectorTest {
|
|||||||
authenticate(trillian, "main");
|
authenticate(trillian, "main");
|
||||||
|
|
||||||
AuthorizationInfo authInfo = collector.collect();
|
AuthorizationInfo authInfo = collector.collect();
|
||||||
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER, Role.ADMIN));
|
assertIsAdmin(authInfo);
|
||||||
assertThat(authInfo.getObjectPermissions(), nullValue());
|
|
||||||
assertThat(authInfo.getStringPermissions(), Matchers.contains("*"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -238,7 +270,7 @@ public class DefaultAuthorizationCollectorTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link AuthorizationCollector#invalidateCache(sonia.scm.security.AuthorizationChangedEvent)}.
|
* Tests {@link DefaultAuthorizationCollector#invalidateCache(sonia.scm.security.AuthorizationChangedEvent)}.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testInvalidateCache() {
|
public void testInvalidateCache() {
|
||||||
|
|||||||
@@ -47,8 +47,7 @@ import org.mockito.junit.MockitoJUnitRunner;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.isEmptyOrNullString;
|
import static org.hamcrest.Matchers.*;
|
||||||
import static org.hamcrest.Matchers.not;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.Assert.assertNotNull;
|
||||||
import static org.junit.Assert.assertThat;
|
import static org.junit.Assert.assertThat;
|
||||||
@@ -135,6 +134,7 @@ public class JwtAccessTokenBuilderTest {
|
|||||||
.issuer("https://www.scm-manager.org")
|
.issuer("https://www.scm-manager.org")
|
||||||
.expiresIn(5, TimeUnit.SECONDS)
|
.expiresIn(5, TimeUnit.SECONDS)
|
||||||
.custom("a", "b")
|
.custom("a", "b")
|
||||||
|
.groups("one", "two", "three")
|
||||||
.scope(Scope.valueOf("repo:*"))
|
.scope(Scope.valueOf("repo:*"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
@@ -161,5 +161,6 @@ public class JwtAccessTokenBuilderTest {
|
|||||||
assertEquals(token.getIssuer().get(), "https://www.scm-manager.org");
|
assertEquals(token.getIssuer().get(), "https://www.scm-manager.org");
|
||||||
assertEquals("b", token.getCustom("a").get());
|
assertEquals("b", token.getCustom("a").get());
|
||||||
assertEquals("[\"repo:*\"]", token.getScope().toString());
|
assertEquals("[\"repo:*\"]", token.getScope().toString());
|
||||||
|
assertThat(token.getGroups(), containsInAnyOrder("one", "two", "three"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user