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

@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.lifecycle.modules;
//~--- non-JDK imports --------------------------------------------------------
@@ -33,6 +33,7 @@ import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.guice.web.ShiroWebModule;
import org.apache.shiro.realm.Realm;
@@ -48,6 +49,7 @@ import javax.servlet.ServletContext;
import org.apache.shiro.mgt.RememberMeManager;
import sonia.scm.security.DisabledRememberMeManager;
import sonia.scm.security.ScmAtLeastOneSuccessfulStrategy;
import sonia.scm.security.ScmPermissionResolver;
/**
*
@@ -94,7 +96,7 @@ public class ScmSecurityModule extends ShiroWebModule
// expose password service to global injector
expose(PasswordService.class);
// disable remember me cookie generation
bind(RememberMeManager.class).to(DisabledRememberMeManager.class);
@@ -102,6 +104,7 @@ public class ScmSecurityModule extends ShiroWebModule
bind(ModularRealmAuthenticator.class);
bind(Authenticator.class).to(ModularRealmAuthenticator.class);
bind(AuthenticationStrategy.class).to(ScmAtLeastOneSuccessfulStrategy.class);
bind(PermissionResolver.class).to(ScmPermissionResolver.class);
// bind realm
for (Class<? extends Realm> realm : extensionProcessor.byExtensionPoint(Realm.class))
@@ -116,7 +119,7 @@ public class ScmSecurityModule extends ShiroWebModule
// disable access to mustache resources
addFilterChain("/**.mustache", filterConfig(ROLES, "nobody"));
// disable session
addFilterChain("/**", NO_SESSION_CREATION);
}

View File

@@ -24,18 +24,19 @@
package sonia.scm.security;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.realm.AuthenticatingRealm;
import sonia.scm.plugin.Extension;
import sonia.scm.repository.RepositoryRole;
import sonia.scm.repository.RepositoryRoleManager;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
@Singleton
@@ -44,24 +45,36 @@ public class ApiKeyRealm extends AuthenticatingRealm {
private final ApiKeyService apiKeyService;
private final DAORealmHelper helper;
private final RepositoryRoleManager repositoryRoleManager;
@Inject
public ApiKeyRealm(ApiKeyService apiKeyService, DAORealmHelperFactory helperFactory) {
public ApiKeyRealm(ApiKeyService apiKeyService, DAORealmHelperFactory helperFactory, RepositoryRoleManager repositoryRoleManager) {
this.apiKeyService = apiKeyService;
this.helper = helperFactory.create("ApiTokenRealm");
this.repositoryRoleManager = repositoryRoleManager;
setAuthenticationTokenClass(BearerToken.class);
setCredentialsMatcher(new AllowAllCredentialsMatcher());
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken || token instanceof BearerToken;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
checkArgument(token instanceof BearerToken, "%s is required", BearerToken.class);
BearerToken bt = (BearerToken) token;
ApiKeyService.CheckResult check = apiKeyService.check(bt.getCredentials());
RepositoryRole repositoryRole = repositoryRoleManager.get(check.getRole());
if (repositoryRole == null) {
throw new AuthorizationException("api key has unknown role: " + check.getRole());
}
String scope = "repository:" + String.join(",", repositoryRole.getVerbs()) + ":*";
return helper
.authenticationInfoBuilder(check.getUser())
.withSessionId(bt.getPrincipal())
// .withScope()
.withScope(Scope.valueOf(scope))
.build();
}
}

View File

@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.security;
//~--- non-JDK imports --------------------------------------------------------
@@ -57,9 +57,9 @@ import java.util.Set;
@Singleton
public class DefaultRealm extends AuthorizingRealm
{
private static final String SEPARATOR = System.getProperty("line.separator", "\n");
/**
* the logger for DefaultRealm
*/
@@ -68,6 +68,7 @@ public class DefaultRealm extends AuthorizingRealm
/** Field description */
@VisibleForTesting
static final String REALM = "DefaultRealm";
private final ScmPermissionResolver permissionResolver;
//~--- constructors ---------------------------------------------------------
@@ -90,11 +91,18 @@ public class DefaultRealm extends AuthorizingRealm
matcher.setPasswordService(service);
setCredentialsMatcher(helper.wrapCredentialsMatcher(matcher));
setAuthenticationTokenClass(UsernamePasswordToken.class);
permissionResolver = new ScmPermissionResolver();
setPermissionResolver(permissionResolver);
// we cache in the AuthorizationCollector
setCachingEnabled(false);
}
@Override
public ScmPermissionResolver getPermissionResolver() {
return permissionResolver;
}
//~--- methods --------------------------------------------------------------
/**
@@ -168,13 +176,13 @@ public class DefaultRealm extends AuthorizingRealm
private void log( PrincipalCollection collection, AuthorizationInfo original, AuthorizationInfo filtered ) {
StringBuilder buffer = new StringBuilder("authorization summary: ");
buffer.append(SEPARATOR).append("username : ").append(collection.getPrimaryPrincipal());
buffer.append(SEPARATOR).append("roles : ");
append(buffer, original.getRoles());
append(buffer, original.getRoles());
buffer.append(SEPARATOR).append("scope : ");
append(buffer, collection.oneByType(Scope.class));
append(buffer, collection.oneByType(Scope.class));
if ( filtered != null ) {
buffer.append(SEPARATOR).append("permissions (filtered by scope): ");
append(buffer, filtered);
@@ -183,21 +191,21 @@ public class DefaultRealm extends AuthorizingRealm
buffer.append(SEPARATOR).append("permissions: ");
}
append(buffer, original);
LOG.trace(buffer.toString());
}
private void append(StringBuilder buffer, AuthorizationInfo authz) {
append(buffer, authz.getStringPermissions());
append(buffer, authz.getObjectPermissions());
append(buffer, authz.getObjectPermissions());
}
private void append(StringBuilder buffer, Iterable<?> iterable){
if (iterable != null){
for ( Object item : iterable )
{
buffer.append(SEPARATOR).append(" - ").append(item);
}
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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.authz.permission.PermissionResolver;
public class ScmPermissionResolver implements PermissionResolver {
@Override
public ScmWildcardPermission resolvePermission(String permissionString) {
return new ScmWildcardPermission(permissionString);
}
}

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.commons.collections.CollectionUtils;
import org.apache.shiro.authz.permission.WildcardPermission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static java.util.Collections.singleton;
import static java.util.Optional.empty;
import static java.util.Optional.of;
public class ScmWildcardPermission extends WildcardPermission {
public ScmWildcardPermission(String permissionString) {
super(permissionString);
}
Collection<ScmWildcardPermission> limit(Scope scope) {
Collection<ScmWildcardPermission> result = new ArrayList<>();
for (String s : scope) {
limit(s).ifPresent(result::add);
}
return result;
}
Optional<ScmWildcardPermission> limit(String scope) {
return limit(new ScmWildcardPermission(scope));
}
Optional<ScmWildcardPermission> limit(ScmWildcardPermission scope) {
if (this.implies(scope)) {
return of(scope);
}
if (scope.implies(this)) {
return of(this);
}
final List<Set<String>> theseParts = getParts();
final List<Set<String>> scopeParts = scope.getParts();
if (!getEntries(theseParts, 0).equals(getEntries(scopeParts, 0))) {
return empty();
}
String type = getEntries(scopeParts, 0).iterator().next();
Collection<String> verbs = intersect(theseParts, scopeParts, 1);
Collection<String> ids = intersect(theseParts, scopeParts, 2);
if (verbs.isEmpty() || ids.isEmpty()) {
return empty();
}
return of(new ScmWildcardPermission(type + ":" + String.join(",", verbs) + ":" + String.join(",", ids)));
}
private Collection<String> intersect(List<Set<String>> theseParts, List<Set<String>> scopeParts, int position) {
final Set<String> theseEntries = getEntries(theseParts, position);
final Set<String> scopeEntries = getEntries(scopeParts, position);
if (isWildcard(theseEntries)) {
return scopeEntries;
}
if (isWildcard(scopeEntries)) {
return theseEntries;
}
return CollectionUtils.intersection(theseEntries, scopeEntries);
}
private Set<String> getEntries(List<Set<String>> theseParts, int position) {
if (position >= theseParts.size()) {
return singleton(WILDCARD_TOKEN);
}
return theseParts.get(position);
}
private boolean isWildcard(Set<String> entries) {
return entries.size() == 1 && entries.contains(WILDCARD_TOKEN);
}
}

View File

@@ -21,28 +21,26 @@
* 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.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.PermissionResolver;
/**
* Util methods for {@link Scope}.
*
*
* @author Sebastian Sdorra
* @since 2.0.0
*/
@@ -50,16 +48,16 @@ public final class Scopes {
/** Key of scope in the claims of a token **/
public final static String CLAIMS_KEY = "scope";
private Scopes() {
}
/**
* Returns scope from a token claims. If the claims does not contain a scope object, the method will return an empty
* scope.
*
*
* @param claims token claims
*
*
* @return scope of claims
*/
@SuppressWarnings("unchecked")
@@ -70,11 +68,11 @@ public final class Scopes {
}
return scope;
}
/**
* Adds a scope to a token claims. The method will add the scope to the claims, if the scope is non null and not
* Adds a scope to a token claims. The method will add the scope to the claims, if the scope is non null and not
* empty.
*
*
* @param claims token claims
* @param scope scope
*/
@@ -83,55 +81,51 @@ public final class Scopes {
claims.put(CLAIMS_KEY, ImmutableSet.copyOf(scope));
}
}
/**
* Filter permissions from {@link AuthorizationInfo} by scope values. Only permission definitions from the scope will
* be returned and only if a permission from the {@link AuthorizationInfo} implies the requested scope permission.
*
* Limit permissions from {@link AuthorizationInfo} by scope values. Permission definitions from the
* {@link AuthorizationInfo} will be returned, if a permission from the scope implies the original permission.
* If a permission from the {@link AuthorizationInfo} exceeds the permissions defined by the scope, it will
* be reduced. If the latter computation results in an empty permission, it will be omitted.
*
* @param resolver permission resolver
* @param authz authorization info
* @param scope scope
*
* @return filtered {@link AuthorizationInfo}
*
* @return limited {@link AuthorizationInfo}
*/
public static AuthorizationInfo filter(PermissionResolver resolver, AuthorizationInfo authz, Scope scope) {
public static AuthorizationInfo filter(ScmPermissionResolver resolver, AuthorizationInfo authz, Scope scope) {
List<Permission> authzPermissions = authzPermissions(resolver, authz);
Predicate<Permission> predicate = implies(authzPermissions);
Set<Permission> filteredPermissions = resolve(resolver, ImmutableList.copyOf(scope))
Set<Permission> filteredPermissions = authzPermissions
.stream()
.filter(predicate)
.map(p -> asScmWildcardPermission(p))
.map(p -> p.limit(scope))
.flatMap(Collection::stream)
.collect(Collectors.toSet());
Set<String> roles = ImmutableSet.copyOf(nullToEmpty(authz.getRoles()));
SimpleAuthorizationInfo authzFiltered = new SimpleAuthorizationInfo(roles);
authzFiltered.setObjectPermissions(filteredPermissions);
return authzFiltered;
}
public static ScmWildcardPermission asScmWildcardPermission(Permission p) {
return p instanceof ScmWildcardPermission ? (ScmWildcardPermission) p : new ScmWildcardPermission(p.toString());
}
private static <T> Collection<T> nullToEmpty(Collection<T> collection) {
return collection != null ? collection : Collections.emptySet();
}
private static Collection<Permission> resolve(PermissionResolver resolver, Collection<String> permissions) {
private static Collection<ScmWildcardPermission> resolve(ScmPermissionResolver resolver, Collection<String> permissions) {
return Collections2.transform(nullToEmpty(permissions), resolver::resolvePermission);
}
private static Predicate<Permission> implies(Iterable<Permission> authzPermissions){
return (scopePermission) -> {
for ( Permission authzPermission : authzPermissions ) {
if (authzPermission.implies(scopePermission)) {
return true;
}
}
return false;
};
}
private static List<Permission> authzPermissions(PermissionResolver resolver, AuthorizationInfo authz){
private static List<Permission> authzPermissions(ScmPermissionResolver resolver, AuthorizationInfo authz){
List<Permission> authzPermissions = Lists.newArrayList();
authzPermissions.addAll(nullToEmpty(authz.getObjectPermissions()));
authzPermissions.addAll(resolve(resolver, authz.getStringPermissions()));
return authzPermissions;
}
}