Add scope from role for api token realm

This commit is contained in:
René Pfeuffer
2020-10-01 09:39:51 +02:00
parent e3e96f7813
commit 4ec75781b7
9 changed files with 469 additions and 92 deletions

View File

@@ -0,0 +1,105 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.security;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import sonia.scm.repository.RepositoryRole;
import sonia.scm.repository.RepositoryRoleManager;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static sonia.scm.security.BearerToken.valueOf;
@ExtendWith(MockitoExtension.class)
class ApiKeyRealmTest {
@Mock
ApiKeyService apiKeyService;
@Mock
DAORealmHelperFactory helperFactory;
@Mock
DAORealmHelper helper;
@Mock(answer = Answers.RETURNS_SELF)
DAORealmHelper.AuthenticationInfoBuilder authenticationInfoBuilder;
@Mock
RepositoryRoleManager repositoryRoleManager;
ApiKeyRealm realm;
@BeforeEach
void initRealmHelper() {
lenient().when(helperFactory.create("ApiTokenRealm")).thenReturn(helper);
lenient().when(helper.authenticationInfoBuilder(any())).thenReturn(authenticationInfoBuilder);
realm = new ApiKeyRealm(apiKeyService, helperFactory, repositoryRoleManager);
}
@Test
void shouldCreateAuthenticationWithScope() {
when(apiKeyService.check("towel")).thenReturn(new ApiKeyService.CheckResult("ford", "READ"));
when(repositoryRoleManager.get("READ")).thenReturn(new RepositoryRole("guide", singleton("read"), "system"));
realm.doGetAuthenticationInfo(valueOf("towel"));
verify(helper).authenticationInfoBuilder("ford");
verifyScopeSet("repository:read:*");
verify(authenticationInfoBuilder).withSessionId(null);
}
@Test
void shouldFailWithoutBearerToken() {
AuthenticationToken otherToken = mock(AuthenticationToken.class);
assertThrows(IllegalArgumentException.class, () -> realm.doGetAuthenticationInfo(otherToken));
}
@Test
void shouldFailWithUnknownRole() {
when(apiKeyService.check("towel")).thenReturn(new ApiKeyService.CheckResult("ford", "READ"));
when(repositoryRoleManager.get("READ")).thenReturn(null);
BearerToken token = valueOf("towel");
assertThrows(AuthorizationException.class, () -> realm.doGetAuthenticationInfo(token));
}
void verifyScopeSet(String... permissions) {
verify(authenticationInfoBuilder).withScope(argThat(scope -> {
assertThat(scope).containsExactly(permissions);
return true;
}));
}
}

View File

@@ -0,0 +1,106 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.security;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
class ScmWildcardPermissionTest {
@Test
void shouldEliminatePermissionsWithDifferentSubject() {
ScmWildcardPermission permission = new ScmWildcardPermission("user:write:*");
Optional<ScmWildcardPermission> limitedPermissions = permission.limit("repository:write:*");
assertThat(limitedPermissions).isEmpty();
}
@Test
void shouldReturnScopeIfPermissionImpliesScope() {
ScmWildcardPermission permission = new ScmWildcardPermission("*");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:read:42");
assertThat(limitedPermission).get().hasToString("repository:read:42");
}
@Test
void shouldReturnPermissionIfScopeImpliesPermission() {
ScmWildcardPermission permission = new ScmWildcardPermission("repository:read:42");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:*:42");
assertThat(limitedPermission).get().hasToString("repository:read:42");
}
@Test
void shouldLimitExplicitParts() {
ScmWildcardPermission permission = new ScmWildcardPermission("repository:read,write:42,43,44");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:read,write,pull:42");
assertThat(limitedPermission).get().hasToString("repository:read,write:42");
}
@Test
void shouldDetectWildcard() {
ScmWildcardPermission permission = new ScmWildcardPermission("repository:read,write:*");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:*:42");
assertThat(limitedPermission).get().hasToString("repository:read,write:42");
}
@Test
void shouldHandleMissingEntriesAsWildcard() {
ScmWildcardPermission permission = new ScmWildcardPermission("repository:read,write");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:*:42");
assertThat(limitedPermission).get().hasToString("repository:read,write:42");
}
@Test
void shouldEliminateEmptyVerbs() {
ScmWildcardPermission permission = new ScmWildcardPermission("repository:read:42");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:pull:42");
assertThat(limitedPermission).isEmpty();
}
@Test
void shouldEliminateEmptyId() {
ScmWildcardPermission permission = new ScmWildcardPermission("repository:read:42");
Optional<ScmWildcardPermission> limitedPermission = permission.limit("repository:read:23");
assertThat(limitedPermission).isEmpty();
}
}

View File

@@ -21,29 +21,32 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
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.*;
import java.util.Set;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.emptyCollectionOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* Unit tests for {@link Scopes}.
*
*
* @author Sebastian Sdorra
*/
public class ScopesTest {
private final WildcardPermissionResolver resolver = new WildcardPermissionResolver();
private final ScmPermissionResolver resolver = new ScmPermissionResolver();
/**
* Tests that filter keep roles.
@@ -51,11 +54,11 @@ public class ScopesTest {
@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.
*/
@@ -63,10 +66,18 @@ public class ScopesTest {
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");
}
@Test
public void testFilterX() {
Scope scope = Scope.valueOf("repository:read,write:*");
AuthorizationInfo authz = authz("repository:*:123");
assertPermissions(Scopes.filter(resolver, authz, scope), "repository:read,write:123");
}
/**
* Tests filter with a simple deny.
*/
@@ -74,12 +85,12 @@ public class ScopesTest {
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.
*/
@@ -87,10 +98,10 @@ public class ScopesTest {
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");
assertPermissions(Scopes.filter(resolver, authz, scope), "repo:read:1", "repo:read:2", "repo:read:3");
}
/**
* Tests filter with admin permissions.
*/
@@ -98,10 +109,10 @@ public class ScopesTest {
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.
*/
@@ -109,29 +120,27 @@ public class ScopesTest {
public void testFilterRequestAdmin(){
Scope scope = Scope.valueOf("*");
AuthorizationInfo authz = authz("repository:*");
assertThat(
Scopes.filter(resolver, authz, scope).getObjectPermissions(),
is(emptyCollectionOf(Permission.class))
);
assertPermissions(Scopes.filter(resolver, authz, scope),
"repository:*");
}
private void assertPermissions(AuthorizationInfo authz, Object... permissions) {
assertThat(authz.getStringPermissions(), is(nullValue()));
assertThat(
Collections2.transform(authz.getObjectPermissions(), Permission::toString),
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));
permissions.add(new ScmWildcardPermission(value));
}
info.setObjectPermissions(permissions);
return info;
}
}
}