mirror of
https://github.com/scm-manager/scm-manager.git
synced 2025-11-17 18:51:10 +01:00
implement token scopes, scopes can be used to issue a token which is only suitable for a single or set explicit actions
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Copyright (c) 2014, Sebastian Sdorra
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of SCM-Manager; nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from this
|
||||
* software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* http://bitbucket.org/sdorra/scm-manager
|
||||
*
|
||||
*/
|
||||
package sonia.scm.it;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.sun.jersey.api.client.Client;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.GenericType;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import java.util.List;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import sonia.scm.ScmState;
|
||||
import static sonia.scm.it.IntegrationTestUtil.*;
|
||||
import static sonia.scm.it.RepositoryITUtil.*;
|
||||
import static sonia.scm.it.RepositoryITUtil.createRepository;
|
||||
import sonia.scm.repository.Repository;
|
||||
import sonia.scm.repository.RepositoryTestData;
|
||||
|
||||
/**
|
||||
* Integration test for authorization with scope.
|
||||
*
|
||||
* @author Sebastian Sdorra
|
||||
*/
|
||||
public class AuthorizationScopeITCase {
|
||||
|
||||
private Repository heartOfGold;
|
||||
private Repository puzzle42;
|
||||
|
||||
/**
|
||||
* Create test repositories.
|
||||
*/
|
||||
@Before
|
||||
public void createTestRepositories(){
|
||||
Client adminClient = createAdminClient();
|
||||
this.heartOfGold = createRepository(adminClient, RepositoryTestData.createHeartOfGold("git"));
|
||||
this.puzzle42 = createRepository(adminClient, RepositoryTestData.create42Puzzle("git"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete test repositories.
|
||||
*/
|
||||
@After
|
||||
public void deleteTestRepositories(){
|
||||
Client adminClient = createAdminClient();
|
||||
deleteRepository(adminClient, heartOfGold.getId());
|
||||
deleteRepository(adminClient, puzzle42.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Read all available repositories without scope.
|
||||
*/
|
||||
@Test
|
||||
public void testAuthenticateWithoutScope() {
|
||||
Assert.assertEquals(2, getRepositories(createAuthenticationToken()).size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Read all available repositories with a scope for only one of them.
|
||||
*/
|
||||
@Test
|
||||
public void testAuthenticateWithScope() {
|
||||
String scope = "repository:read:".concat(heartOfGold.getId());
|
||||
Assert.assertEquals(1, getRepositories(createAuthenticationToken(scope)).size());
|
||||
}
|
||||
|
||||
private List<Repository> getRepositories(String token) {
|
||||
Client client = createClient();
|
||||
WebResource wr = client.resource(createResourceUrl("repositories"));
|
||||
return wr.header("Authorization", "Bearer ".concat(token)).get(new GenericType<List<Repository>>(){});
|
||||
}
|
||||
|
||||
private String createAuthenticationToken() {
|
||||
return createAuthenticationToken("");
|
||||
}
|
||||
|
||||
private String createAuthenticationToken(String scope) {
|
||||
Client client = createClient();
|
||||
String url = createResourceUrl("authentication/login");
|
||||
if (!Strings.isNullOrEmpty(scope)) {
|
||||
url = url.concat("?scope=").concat(scope);
|
||||
}
|
||||
WebResource wr = client.resource(url);
|
||||
MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
|
||||
|
||||
formData.add("username", ADMIN_USERNAME);
|
||||
formData.add("password", ADMIN_PASSWORD);
|
||||
|
||||
ClientResponse response = wr.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);
|
||||
if (response.getStatus() >= 300 ){
|
||||
Assert.fail("authentication failed with status code " + response.getStatus());
|
||||
}
|
||||
|
||||
return response.getEntity(ScmState.class).getToken();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -35,6 +35,7 @@ package sonia.scm.security;
|
||||
|
||||
//~--- non-JDK imports --------------------------------------------------------
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Sets;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwsHeader;
|
||||
@@ -115,6 +116,35 @@ public class BearerRealmTest
|
||||
|
||||
assertEquals(marvin.getName(), principals.getPrimaryPrincipal());
|
||||
assertEquals(marvin, principals.oneByType(User.class));
|
||||
assertNotNull(principals.oneByType(Scope.class));
|
||||
assertTrue(principals.oneByType(Scope.class).isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link BearerRealm#doGetAuthenticationInfo(AuthenticationToken)} with scope.
|
||||
*
|
||||
*/
|
||||
@Test
|
||||
public void testDoGetAuthenticationInfoWithScope()
|
||||
{
|
||||
SecureKey key = createSecureKey();
|
||||
|
||||
User marvin = UserTestData.createMarvin();
|
||||
|
||||
when(userDAO.get(marvin.getName())).thenReturn(marvin);
|
||||
|
||||
resolveKey(key);
|
||||
|
||||
String compact = createCompactToken(
|
||||
marvin.getName(),
|
||||
key,
|
||||
new Date(System.currentTimeMillis() + 60000),
|
||||
Scope.valueOf("repo:*", "user:*")
|
||||
);
|
||||
|
||||
AuthenticationInfo info = realm.doGetAuthenticationInfo(new BearerAuthenticationToken(compact));
|
||||
Scope scope = info.getPrincipals().oneByType(Scope.class);
|
||||
assertThat(scope, Matchers.containsInAnyOrder("repo:*", "user:*"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -159,7 +189,7 @@ public class BearerRealmTest
|
||||
resolveKey(key);
|
||||
|
||||
Date exp = new Date(System.currentTimeMillis() - 600l);
|
||||
String compact = createCompactToken(trillian.getName(), key, exp);
|
||||
String compact = createCompactToken(trillian.getName(), key, exp, Scope.empty());
|
||||
|
||||
realm.doGetAuthenticationInfo(new BearerAuthenticationToken(compact));
|
||||
}
|
||||
@@ -221,66 +251,30 @@ public class BearerRealmTest
|
||||
|
||||
//~--- methods --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
*
|
||||
* @param subject
|
||||
* @param key
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private String createCompactToken(String subject, SecureKey key)
|
||||
{
|
||||
return createCompactToken(subject, key,
|
||||
new Date(System.currentTimeMillis() + 60000));
|
||||
private String createCompactToken(String subject, SecureKey key) {
|
||||
return createCompactToken(subject, key, Scope.empty());
|
||||
}
|
||||
|
||||
private String createCompactToken(String subject, SecureKey key, Scope scope) {
|
||||
return createCompactToken(subject, key, new Date(System.currentTimeMillis() + 60000), scope);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
*
|
||||
* @param subject
|
||||
* @param key
|
||||
* @param exp
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private String createCompactToken(String subject, SecureKey key, Date exp)
|
||||
{
|
||||
//J-
|
||||
private String createCompactToken(String subject, SecureKey key, Date exp, Scope scope) {
|
||||
return Jwts.builder()
|
||||
.claim(Scopes.CLAIMS_KEY, ImmutableList.copyOf(scope))
|
||||
.setSubject(subject)
|
||||
.setExpiration(exp)
|
||||
.signWith(SignatureAlgorithm.HS256, key.getBytes())
|
||||
.compact();
|
||||
//J+
|
||||
}
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private SecureKey createSecureKey()
|
||||
{
|
||||
private SecureKey createSecureKey() {
|
||||
byte[] bytes = new byte[32];
|
||||
|
||||
random.nextBytes(bytes);
|
||||
|
||||
return new SecureKey(bytes, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
*
|
||||
* @param key
|
||||
*/
|
||||
private void resolveKey(SecureKey key)
|
||||
{
|
||||
//J-
|
||||
private void resolveKey(SecureKey key) {
|
||||
when(
|
||||
keyResolver.resolveSigningKey(
|
||||
any(JwsHeader.class),
|
||||
@@ -293,7 +287,6 @@ public class BearerRealmTest
|
||||
SignatureAlgorithm.HS256.getValue()
|
||||
)
|
||||
);
|
||||
//J+
|
||||
}
|
||||
|
||||
//~--- fields ---------------------------------------------------------------
|
||||
|
||||
@@ -61,83 +61,82 @@ import java.security.SecureRandom;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
*
|
||||
* Tests {@link BearerTokenGenerator}.
|
||||
*
|
||||
* @author Sebastian Sdorra
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class BearerTokenGeneratorTest
|
||||
{
|
||||
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
@Mock
|
||||
private KeyGenerator keyGenerator;
|
||||
|
||||
@Mock
|
||||
private SecureKeyResolver keyResolver;
|
||||
|
||||
private BearerTokenGenerator tokenGenerator;
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
*/
|
||||
@Test
|
||||
public void testCreateBearerToken()
|
||||
{
|
||||
User trillian = UserTestData.createTrillian();
|
||||
SecureKey key = createSecureKey();
|
||||
|
||||
when(keyGenerator.createKey()).thenReturn("sid");
|
||||
when(keyResolver.getSecureKey(trillian.getName())).thenReturn(key);
|
||||
|
||||
String token = tokenGenerator.createBearerToken(trillian);
|
||||
|
||||
assertThat(token, not(isEmptyOrNullString()));
|
||||
assertTrue(Jwts.parser().isSigned(token));
|
||||
|
||||
Claims claims = Jwts.parser().setSigningKey(key.getBytes()).parseClaimsJws(
|
||||
token).getBody();
|
||||
|
||||
assertEquals(trillian.getName(), claims.getSubject());
|
||||
assertEquals("sid", claims.getId());
|
||||
assertEquals("123", claims.get("abc"));
|
||||
}
|
||||
|
||||
//~--- set methods ----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
* Set up mocks and object under test.
|
||||
*/
|
||||
@Before
|
||||
public void setUp()
|
||||
{
|
||||
public void setUp() {
|
||||
Set<TokenClaimsEnricher> enrichers = Sets.newHashSet();
|
||||
enrichers.add((claims) -> {claims.put("abc", "123");});
|
||||
tokenGenerator = new BearerTokenGenerator(keyGenerator, keyResolver, enrichers);
|
||||
}
|
||||
|
||||
//~--- methods --------------------------------------------------------------
|
||||
|
||||
|
||||
/**
|
||||
* Method description
|
||||
*
|
||||
*
|
||||
* @return
|
||||
* Tests {@link BearerTokenGenerator#createBearerToken(User, Scope)}.
|
||||
*/
|
||||
private SecureKey createSecureKey()
|
||||
@Test
|
||||
public void testCreateBearerToken()
|
||||
{
|
||||
byte[] bytes = new byte[32];
|
||||
|
||||
random.nextBytes(bytes);
|
||||
|
||||
return new SecureKey(bytes, System.currentTimeMillis());
|
||||
Claims claims = createAssertAndParseToken(UserTestData.createTrillian(), "sid", Scope.empty());
|
||||
|
||||
assertEquals("123", claims.get("abc"));
|
||||
assertNull(claims.get(Scopes.CLAIMS_KEY));
|
||||
}
|
||||
|
||||
//~--- fields ---------------------------------------------------------------
|
||||
/**
|
||||
* Tests {@link BearerTokenGenerator#createBearerToken(User, Scope)} with scope.
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testCreateBearerTokenWithScope(){
|
||||
Claims claims = createAssertAndParseToken(UserTestData.createTrillian(), "sid", Scope.valueOf("repo:*", "user:*"));
|
||||
assertEquals("123", claims.get("abc"));
|
||||
|
||||
Scope scope = Scopes.fromClaims(claims);
|
||||
assertThat(scope, containsInAnyOrder("repo:*", "user:*"));
|
||||
}
|
||||
|
||||
private Claims createAssertAndParseToken(User user, String id, Scope scope){
|
||||
SecureKey key = createSecureKey();
|
||||
|
||||
/** Field description */
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
when(keyGenerator.createKey()).thenReturn(id);
|
||||
when(keyResolver.getSecureKey(user.getName())).thenReturn(key);
|
||||
|
||||
/** Field description */
|
||||
@Mock
|
||||
private KeyGenerator keyGenerator;
|
||||
String token = tokenGenerator.createBearerToken(user, scope);
|
||||
|
||||
/** Field description */
|
||||
@Mock
|
||||
private SecureKeyResolver keyResolver;
|
||||
assertThat(token, not(isEmptyOrNullString()));
|
||||
assertTrue(Jwts.parser().isSigned(token));
|
||||
|
||||
/** Field description */
|
||||
private BearerTokenGenerator tokenGenerator;
|
||||
Claims claims = Jwts.parser().setSigningKey(key.getBytes()).parseClaimsJws(token).getBody();
|
||||
|
||||
assertEquals(user.getName(), claims.getSubject());
|
||||
assertEquals(id, claims.getId());
|
||||
|
||||
return claims;
|
||||
}
|
||||
|
||||
private SecureKey createSecureKey() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return new SecureKey(bytes, System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ package sonia.scm.security;
|
||||
|
||||
//~--- non-JDK imports --------------------------------------------------------
|
||||
|
||||
import com.google.common.collect.Collections2;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import org.apache.shiro.authc.AuthenticationInfo;
|
||||
@@ -71,6 +72,11 @@ import static org.mockito.Mockito.*;
|
||||
//~--- JDK imports ------------------------------------------------------------
|
||||
|
||||
import java.util.List;
|
||||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.Permission;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.mockito.InjectMocks;
|
||||
|
||||
/**
|
||||
@@ -109,6 +115,62 @@ public class DefaultRealmTest
|
||||
realm.doGetAuthorizationInfo(col);
|
||||
verify(collector, times(1)).collect(col);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DefaultRealm#doGetAuthorizationInfo(PrincipalCollection)} without scope.
|
||||
*/
|
||||
@Test
|
||||
public void testGetAuthorizationInfoWithoutScope(){
|
||||
SimplePrincipalCollection col = new SimplePrincipalCollection();
|
||||
|
||||
SimpleAuthorizationInfo collectorsAuthz = new SimpleAuthorizationInfo();
|
||||
collectorsAuthz.addStringPermission("repository:*");
|
||||
when(collector.collect(col)).thenReturn(collectorsAuthz);
|
||||
|
||||
AuthorizationInfo realmsAutz = realm.doGetAuthorizationInfo(col);
|
||||
assertThat(realmsAutz.getObjectPermissions(), is(nullValue()));
|
||||
assertThat(realmsAutz.getStringPermissions(), Matchers.contains("repository:*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DefaultRealm#doGetAuthorizationInfo(PrincipalCollection)} with empty scope.
|
||||
*/
|
||||
@Test
|
||||
public void testGetAuthorizationInfoWithEmptyScope(){
|
||||
SimplePrincipalCollection col = new SimplePrincipalCollection();
|
||||
col.add(Scope.empty(), DefaultRealm.REALM);
|
||||
|
||||
SimpleAuthorizationInfo collectorsAuthz = new SimpleAuthorizationInfo();
|
||||
collectorsAuthz.addStringPermission("repository:*");
|
||||
when(collector.collect(col)).thenReturn(collectorsAuthz);
|
||||
|
||||
AuthorizationInfo realmsAutz = realm.doGetAuthorizationInfo(col);
|
||||
assertThat(realmsAutz.getObjectPermissions(), is(nullValue()));
|
||||
assertThat(realmsAutz.getStringPermissions(), Matchers.contains("repository:*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DefaultRealm#doGetAuthorizationInfo(PrincipalCollection)} with scope.
|
||||
*/
|
||||
@Test
|
||||
public void testGetAuthorizationInfoWithScope(){
|
||||
SimplePrincipalCollection col = new SimplePrincipalCollection();
|
||||
col.add(Scope.valueOf("user:*:me"), DefaultRealm.REALM);
|
||||
|
||||
SimpleAuthorizationInfo collectorsAuthz = new SimpleAuthorizationInfo();
|
||||
collectorsAuthz.addStringPermission("repository:*");
|
||||
collectorsAuthz.addStringPermission("user:*:me");
|
||||
when(collector.collect(col)).thenReturn(collectorsAuthz);
|
||||
|
||||
AuthorizationInfo realmsAutz = realm.doGetAuthorizationInfo(col);
|
||||
assertThat(
|
||||
Collections2.transform(realmsAutz.getObjectPermissions(), Permission::toString),
|
||||
allOf(
|
||||
Matchers.contains("user:*:me"),
|
||||
not(Matchers.contains("repository:*"))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method description
|
||||
@@ -223,6 +285,9 @@ public class DefaultRealmTest
|
||||
hashService.setHashIterations(512);
|
||||
service.setHashService(hashService);
|
||||
realm = new DefaultRealm(service, collector, helperFactory);
|
||||
|
||||
// set permission resolver
|
||||
realm.setPermissionResolver(new WildcardPermissionResolver());
|
||||
}
|
||||
|
||||
//~--- methods --------------------------------------------------------------
|
||||
|
||||
144
scm-webapp/src/test/java/sonia/scm/security/ScopesTest.java
Normal file
144
scm-webapp/src/test/java/sonia/scm/security/ScopesTest.java
Normal file
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Copyright (c) 2014, Sebastian Sdorra
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of SCM-Manager; nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from this
|
||||
* software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* http://bitbucket.org/sdorra/scm-manager
|
||||
*
|
||||
*/
|
||||
|
||||
package sonia.scm.security;
|
||||
|
||||
import com.google.common.collect.Collections2;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.util.Set;
|
||||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.Permission;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.authz.permission.WildcardPermission;
|
||||
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Scopes}.
|
||||
*
|
||||
* @author Sebastian Sdorra
|
||||
*/
|
||||
public class ScopesTest {
|
||||
|
||||
private final WildcardPermissionResolver resolver = new WildcardPermissionResolver();
|
||||
|
||||
/**
|
||||
* Tests that filter keep roles.
|
||||
*/
|
||||
@Test
|
||||
public void testFilterKeepRoles(){
|
||||
AuthorizationInfo authz = authz("repository:read:123");
|
||||
|
||||
AuthorizationInfo filtered = Scopes.filter(resolver, authz, Scope.empty());
|
||||
assertThat(filtered.getRoles(), containsInAnyOrder("unit", "test"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests filter with a simple allow.
|
||||
*/
|
||||
@Test
|
||||
public void testFilterSimpleAllow() {
|
||||
Scope scope = Scope.valueOf("repository:read:123");
|
||||
AuthorizationInfo authz = authz("repository:*", "user:*:me");
|
||||
|
||||
assertPermissions(Scopes.filter(resolver, authz, scope), "repository:read:123");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests filter with a simple deny.
|
||||
*/
|
||||
@Test
|
||||
public void testFilterSimpleDeny() {
|
||||
Scope scope = Scope.valueOf("repository:read:123");
|
||||
AuthorizationInfo authz = authz("user:*:me");
|
||||
|
||||
AuthorizationInfo filtered = Scopes.filter(resolver, authz, scope);
|
||||
assertThat(filtered.getStringPermissions(), is(nullValue()));
|
||||
assertThat(filtered.getObjectPermissions(), is(emptyCollectionOf(Permission.class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests filter with a multiple scope entries.
|
||||
*/
|
||||
@Test
|
||||
public void testFilterMultiple() {
|
||||
Scope scope = Scope.valueOf("repo:read,modify:1", "repo:read:2", "repo:*:3", "repo:modify:4");
|
||||
AuthorizationInfo authz = authz("repo:read:*");
|
||||
|
||||
assertPermissions(Scopes.filter(resolver, authz, scope), "repo:read:2");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests filter with admin permissions.
|
||||
*/
|
||||
@Test
|
||||
public void testFilterAdmin(){
|
||||
Scope scope = Scope.valueOf("repository:*", "user:*:me");
|
||||
AuthorizationInfo authz = authz("*");
|
||||
|
||||
assertPermissions(Scopes.filter(resolver, authz, scope), "repository:*", "user:*:me");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests filter with requested admin permissions from a non admin.
|
||||
*/
|
||||
@Test
|
||||
public void testFilterRequestAdmin(){
|
||||
Scope scope = Scope.valueOf("*");
|
||||
AuthorizationInfo authz = authz("repository:*");
|
||||
|
||||
assertThat(
|
||||
Scopes.filter(resolver, authz, scope).getObjectPermissions(),
|
||||
is(emptyCollectionOf(Permission.class))
|
||||
);
|
||||
}
|
||||
|
||||
private void assertPermissions(AuthorizationInfo authz, Object... permissions) {
|
||||
assertThat(authz.getStringPermissions(), is(nullValue()));
|
||||
assertThat(
|
||||
Collections2.transform(authz.getObjectPermissions(), Permission::toString),
|
||||
containsInAnyOrder(permissions)
|
||||
);
|
||||
}
|
||||
|
||||
private AuthorizationInfo authz( String... values ) {
|
||||
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(Sets.newHashSet("unit", "test"));
|
||||
Set<Permission> permissions = Sets.newLinkedHashSet();
|
||||
for ( String value : values ) {
|
||||
permissions.add(new WildcardPermission(value));
|
||||
}
|
||||
info.setObjectPermissions(permissions);
|
||||
return info;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user