Merge with 2.0.0-m3

This commit is contained in:
René Pfeuffer
2019-01-16 07:43:22 +01:00
63 changed files with 1385 additions and 645 deletions

View File

@@ -4,10 +4,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.api.v2.resources.ExceptionWithContextToErrorDtoMapper;
import sonia.scm.web.VndMediaType;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@@ -20,16 +18,9 @@ public class FallbackExceptionMapper implements ExceptionMapper<Exception> {
private static final String ERROR_CODE = "CmR8GCJb31";
private final ExceptionWithContextToErrorDtoMapper mapper;
@Inject
public FallbackExceptionMapper(ExceptionWithContextToErrorDtoMapper mapper) {
this.mapper = mapper;
}
@Override
public Response toResponse(Exception exception) {
logger.debug("map {} to status code 500", exception);
logger.warn("mapping unexpected {} to status code 500", exception.getClass().getName(), exception);
ErrorDto errorDto = new ErrorDto();
errorDto.setMessage("internal server error");
errorDto.setContext(Collections.emptyList());

View File

@@ -0,0 +1,35 @@
package sonia.scm.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.web.VndMediaType;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.Collections;
@Provider
public class JaxNotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {
private static final Logger logger = LoggerFactory.getLogger(JaxNotFoundExceptionMapper.class);
private static final String ERROR_CODE = "92RCCCMHO1";
@Override
public Response toResponse(NotFoundException exception) {
logger.debug(exception.getMessage());
ErrorDto errorDto = new ErrorDto();
errorDto.setMessage("path not found");
errorDto.setContext(Collections.emptyList());
errorDto.setErrorCode(ERROR_CODE);
errorDto.setTransactionId(MDC.get("transaction_id"));
return Response.status(Response.Status.NOT_FOUND)
.entity(errorDto)
.type(VndMediaType.ERROR_TYPE)
.build();
}
}

View File

@@ -0,0 +1,35 @@
package sonia.scm.api;
import com.fasterxml.jackson.core.JsonParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.web.VndMediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.Collections;
@Provider
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {
private static final Logger logger = LoggerFactory.getLogger(JsonParseExceptionMapper.class);
private static final String ERROR_CODE = "2VRCrvpL71";
@Override
public Response toResponse(JsonParseException exception) {
logger.trace("got illegal json: {}", exception.getMessage());
ErrorDto errorDto = new ErrorDto();
errorDto.setMessage("illegal json content: " + exception.getMessage());
errorDto.setContext(Collections.emptyList());
errorDto.setErrorCode(ERROR_CODE);
errorDto.setTransactionId(MDC.get("transaction_id"));
return Response.status(Response.Status.BAD_REQUEST)
.entity(errorDto)
.type(VndMediaType.ERROR_TYPE)
.build();
}
}

View File

@@ -15,7 +15,7 @@ import static de.otto.edison.hal.Link.linkBuilder;
import static de.otto.edison.hal.Links.linkingTo;
@Mapper
public abstract class BranchToBranchDtoMapper {
public abstract class BranchToBranchDtoMapper extends LinkAppenderMapper {
@Inject
private ResourceLinks resourceLinks;
@@ -24,12 +24,15 @@ public abstract class BranchToBranchDtoMapper {
public abstract BranchDto map(Branch branch, @Context NamespaceAndName namespaceAndName);
@AfterMapping
void appendLinks(@MappingTarget BranchDto target, @Context NamespaceAndName namespaceAndName) {
void appendLinks(Branch source, @MappingTarget BranchDto target, @Context NamespaceAndName namespaceAndName) {
Links.Builder linksBuilder = linkingTo()
.self(resourceLinks.branch().self(namespaceAndName, target.getName()))
.single(linkBuilder("history", resourceLinks.branch().history(namespaceAndName, target.getName())).build())
.single(linkBuilder("changeset", resourceLinks.changeset().changeset(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())).build())
.single(linkBuilder("source", resourceLinks.source().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())).build());
appendLinks(new EdisonLinkAppender(linksBuilder), source, namespaceAndName);
target.add(linksBuilder.build());
}
}

View File

@@ -23,7 +23,7 @@ import static de.otto.edison.hal.Link.link;
import static de.otto.edison.hal.Links.linkingTo;
@Mapper
public abstract class ChangesetToChangesetDtoMapper implements InstantAttributeMapper {
public abstract class ChangesetToChangesetDtoMapper extends LinkAppenderMapper implements InstantAttributeMapper {
@Inject
private RepositoryServiceFactory serviceFactory;
@@ -67,6 +67,9 @@ public abstract class ChangesetToChangesetDtoMapper implements InstantAttributeM
.self(resourceLinks.changeset().self(repository.getNamespace(), repository.getName(), target.getId()))
.single(link("diff", resourceLinks.diff().self(namespace, name, target.getId())))
.single(link("modifications", resourceLinks.modifications().self(namespace, name, target.getId())));
appendLinks(new EdisonLinkAppender(linksBuilder), source, repository);
target.add(linksBuilder.build());
}

View File

@@ -0,0 +1,49 @@
package sonia.scm.api.v2.resources;
import de.otto.edison.hal.Link;
import de.otto.edison.hal.Links;
import java.util.ArrayList;
import java.util.List;
class EdisonLinkAppender implements LinkAppender {
private final Links.Builder builder;
EdisonLinkAppender(Links.Builder builder) {
this.builder = builder;
}
@Override
public void appendOne(String rel, String href) {
builder.single(Link.link(rel, href));
}
@Override
public LinkArrayBuilder arrayBuilder(String rel) {
return new EdisonLinkArrayBuilder(builder, rel);
}
private static class EdisonLinkArrayBuilder implements LinkArrayBuilder {
private final Links.Builder builder;
private final String rel;
private final List<Link> linkArray = new ArrayList<>();
private EdisonLinkArrayBuilder(Links.Builder builder, String rel) {
this.builder = builder;
this.rel = rel;
}
@Override
public LinkArrayBuilder append(String name, String href) {
linkArray.add(Link.linkBuilder(rel, href).withName(name).build());
return this;
}
@Override
public void build() {
builder.array(linkArray);
}
}
}

View File

@@ -18,7 +18,7 @@ import java.util.stream.Collectors;
import static de.otto.edison.hal.Link.link;
@Mapper
public abstract class FileObjectToFileObjectDtoMapper implements InstantAttributeMapper {
public abstract class FileObjectToFileObjectDtoMapper extends LinkAppenderMapper implements InstantAttributeMapper {
@Inject
private ResourceLinks resourceLinks;
@@ -39,6 +39,8 @@ public abstract class FileObjectToFileObjectDtoMapper implements InstantAttribut
links.single(link("history", resourceLinks.fileHistory().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), revision, path)));
}
appendLinks(new EdisonLinkAppender(links), fileObject, namespaceAndName, revision);
dto.add(links.build());
}

View File

@@ -31,6 +31,9 @@ public abstract class GroupToGroupDtoMapper extends BaseMapper<Group, GroupDto>
if (GroupPermissions.modify(group).isPermitted()) {
linksBuilder.single(link("update", resourceLinks.group().update(target.getName())));
}
appendLinks(new EdisonLinkAppender(linksBuilder), group);
target.add(linksBuilder.build());
}

View File

@@ -14,7 +14,7 @@ import java.util.List;
import static de.otto.edison.hal.Link.link;
public class IndexDtoGenerator {
public class IndexDtoGenerator extends LinkAppenderMapper {
private final ResourceLinks resourceLinks;
private final SCMContextProvider scmContextProvider;
@@ -56,6 +56,8 @@ public class IndexDtoGenerator {
builder.single(link("login", resourceLinks.authentication().jsonLogin()));
}
appendLinks(new EdisonLinkAppender(builder), new Index());
return new IndexDto(scmContextProvider.getVersion(), builder.build());
}
}

View File

@@ -0,0 +1,45 @@
package sonia.scm.api.v2.resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.plugin.Extension;
import javax.inject.Inject;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Set;
/**
* Registers every {@link LinkEnricher} which is annotated with an {@link Enrich} annotation.
*/
@Extension
public class LinkEnricherAutoRegistration implements ServletContextListener {
private static final Logger LOG = LoggerFactory.getLogger(LinkEnricherAutoRegistration.class);
private final LinkEnricherRegistry registry;
private final Set<LinkEnricher> enrichers;
@Inject
public LinkEnricherAutoRegistration(LinkEnricherRegistry registry, Set<LinkEnricher> enrichers) {
this.registry = registry;
this.enrichers = enrichers;
}
@Override
public void contextInitialized(ServletContextEvent sce) {
for (LinkEnricher enricher : enrichers) {
Enrich annotation = enricher.getClass().getAnnotation(Enrich.class);
if (annotation != null) {
registry.register(annotation.value(), enricher);
} else {
LOG.warn("found LinkEnricher extension {} without Enrich annotation", enricher.getClass());
}
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// nothing todo
}
}

View File

@@ -14,7 +14,7 @@ import static de.otto.edison.hal.Link.link;
import static de.otto.edison.hal.Links.linkingTo;
@Mapper
public abstract class MeToUserDtoMapper extends UserToUserDtoMapper{
public abstract class MeToUserDtoMapper extends UserToUserDtoMapper {
@Inject
private UserManager userManager;
@@ -36,6 +36,9 @@ public abstract class MeToUserDtoMapper extends UserToUserDtoMapper{
if (userManager.isTypeDefault(user)) {
linksBuilder.single(link("password", resourceLinks.me().passwordChange()));
}
appendLinks(new EdisonLinkAppender(linksBuilder), new Me(), user);
target.add(linksBuilder.build());
}

View File

@@ -67,6 +67,9 @@ public abstract class RepositoryToRepositoryDtoMapper extends BaseMapper<Reposit
}
linksBuilder.single(link("changesets", resourceLinks.changeset().all(target.getNamespace(), target.getName())));
linksBuilder.single(link("sources", resourceLinks.source().selfWithoutRevision(target.getNamespace(), target.getName())));
appendLinks(new EdisonLinkAppender(linksBuilder), repository);
target.add(linksBuilder.build());
}

View File

@@ -15,7 +15,7 @@ import static de.otto.edison.hal.Link.link;
import static de.otto.edison.hal.Links.linkingTo;
@Mapper
public abstract class TagToTagDtoMapper {
public abstract class TagToTagDtoMapper extends LinkAppenderMapper {
@Inject
private ResourceLinks resourceLinks;
@@ -24,11 +24,14 @@ public abstract class TagToTagDtoMapper {
public abstract TagDto map(Tag tag, @Context NamespaceAndName namespaceAndName);
@AfterMapping
void appendLinks(@MappingTarget TagDto target, @Context NamespaceAndName namespaceAndName) {
void appendLinks(Tag tag, @MappingTarget TagDto target, @Context NamespaceAndName namespaceAndName) {
Links.Builder linksBuilder = linkingTo()
.self(resourceLinks.tag().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getName()))
.single(link("sources", resourceLinks.source().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())))
.single(link("changeset", resourceLinks.changeset().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())));
appendLinks(new EdisonLinkAppender(linksBuilder), tag, namespaceAndName);
target.add(linksBuilder.build());
}
}

View File

@@ -1,6 +1,5 @@
package sonia.scm.api.v2.resources;
import com.google.common.annotations.VisibleForTesting;
import de.otto.edison.hal.Links;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
@@ -43,6 +42,9 @@ public abstract class UserToUserDtoMapper extends BaseMapper<User, UserDto> {
linksBuilder.single(link("password", resourceLinks.user().passwordChange(target.getName())));
}
}
appendLinks(new EdisonLinkAppender(linksBuilder), user);
target.add(linksBuilder.build());
}

View File

@@ -34,6 +34,8 @@ package sonia.scm.plugin;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.base.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//~--- JDK imports ------------------------------------------------------------
@@ -52,17 +54,18 @@ import java.util.Set;
public final class ExplodedSmp implements Comparable<ExplodedSmp>
{
private static final Logger logger = LoggerFactory.getLogger(ExplodedSmp.class);
/**
* Constructs ...
*
*
* @param path
* @param pluginId
* @param dependencies
* @param plugin
*/
ExplodedSmp(Path path, Plugin plugin)
{
logger.trace("create exploded scm for plugin {} and dependencies {}", plugin.getInformation().getName(), plugin.getDependencies());
this.path = path;
this.plugin = plugin;
}

View File

@@ -175,6 +175,11 @@ public final class PluginNode
this.wrapper = wrapper;
}
@Override
public String toString() {
return plugin.getPath().toString() + " -> " + children;
}
//~--- fields ---------------------------------------------------------------
/** Field description */

View File

@@ -162,34 +162,29 @@ public final class PluginProcessor
Set<Path> archives = collect(pluginDirectory, new PluginArchiveFilter());
if (logger.isDebugEnabled())
{
logger.debug("extract {} archives", archives.size());
}
logger.debug("extract {} archives", archives.size());
extract(archives);
List<Path> dirs = collectPluginDirectories(pluginDirectory);
if (logger.isDebugEnabled())
{
logger.debug("process {} directories", dirs.size());
}
logger.debug("process {} directories: {}", dirs.size(), dirs);
List<ExplodedSmp> smps = Lists.transform(dirs, new PathTransformer());
logger.trace("start building plugin tree");
List<PluginNode> rootNodes = new PluginTree(smps).getRootNodes();
PluginTree pluginTree = new PluginTree(smps);
logger.trace("build plugin tree: {}", pluginTree);
List<PluginNode> rootNodes = pluginTree.getRootNodes();
logger.trace("create plugin wrappers and build classloaders");
Set<PluginWrapper> wrappers = createPluginWrappers(classLoader, rootNodes);
if (logger.isDebugEnabled())
{
logger.debug("collected {} plugins", wrappers.size());
}
logger.debug("collected {} plugins", wrappers.size());
return ImmutableSet.copyOf(wrappers);
}
@@ -208,6 +203,9 @@ public final class PluginProcessor
ClassLoader classLoader, PluginNode node)
throws IOException
{
if (node.getWrapper() != null) {
return;
}
ExplodedSmp smp = node.getPlugin();
List<ClassLoader> parents = Lists.newArrayList();

View File

@@ -112,14 +112,14 @@ public final class PluginTree
}
else
{
appendNode(rootNodes, dependencies, smp);
appendNode(smp);
}
}
else
{
//J-
throw new PluginConditionFailedException(
condition,
condition,
String.format(
"could not load plugin %s, the plugin condition does not match",
plugin.getInformation().getId()
@@ -149,23 +149,20 @@ public final class PluginTree
* Method description
*
*
* @param nodes
* @param dependencies
* @param smp
*/
private void appendNode(List<PluginNode> nodes, Set<String> dependencies,
ExplodedSmp smp)
private void appendNode(ExplodedSmp smp)
{
PluginNode child = new PluginNode(smp);
for (String dependency : dependencies)
for (String dependency : smp.getPlugin().getDependencies())
{
if (!appendNode(nodes, child, dependency))
if (!appendNode(rootNodes, child, dependency))
{
//J-
throw new PluginNotInstalledException(
String.format(
"dependency %s of %s is not installed",
"dependency %s of %s is not installed",
dependency,
child.getId()
)
@@ -188,7 +185,7 @@ public final class PluginTree
private boolean appendNode(List<PluginNode> nodes, PluginNode child,
String dependency)
{
logger.debug("check for {} {}", dependency, child.getId());
logger.debug("check for {} as dependency of {}", dependency, child.getId());
boolean found = false;
@@ -196,29 +193,28 @@ public final class PluginTree
{
if (node.getId().equals(dependency))
{
logger.debug("add plugin {} as child of {}", child.getId(),
node.getId());
logger.debug("add plugin {} as child of {}", child.getId(), node.getId());
node.addChild(child);
found = true;
break;
}
else
else if (appendNode(node.getChildren(), child, dependency))
{
if (appendNode(node.getChildren(), child, dependency))
{
found = true;
break;
}
found = true;
break;
}
}
return found;
}
//~--- fields ---------------------------------------------------------------
@Override
public String toString() {
return "plugin tree: " + rootNodes.toString();
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private final List<PluginNode> rootNodes = Lists.newArrayList();

View File

@@ -73,43 +73,39 @@ public final class UberClassLoader extends ClassLoader
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param name
*
* @return
*
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
Class<?> clazz = getFromCache(name);
if (clazz == null)
{
for (PluginWrapper plugin : plugins)
{
ClassLoader cl = plugin.getClassLoader();
// load class could be slow, perhaps we should call
// find class via reflection ???
clazz = cl.loadClass(name);
if (clazz != null)
{
cache.put(name, new WeakReference<Class<?>>(clazz));
break;
}
}
if (clazz == null) {
clazz = findClassInPlugins(name);
cache.put(name, new WeakReference<>(clazz));
}
return clazz;
}
private Class<?> findClassInPlugins(String name) throws ClassNotFoundException {
for (PluginWrapper plugin : plugins) {
Class<?> clazz = findClass(plugin.getClassLoader(), name);
if (clazz != null) {
return clazz;
}
}
throw new ClassNotFoundException("could not find class " + name + " in any of the installed plugins");
}
private Class<?> findClass(ClassLoader classLoader, String name) {
try {
// load class could be slow, perhaps we should call
// find class via reflection ???
return classLoader.loadClass(name);
} catch (ClassNotFoundException ex) {
return null;
}
}
/**
* Method description
*

View File

@@ -31,35 +31,20 @@
package sonia.scm.security;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.annotations.VisibleForTesting;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
import sonia.scm.group.GroupDAO;
import sonia.scm.plugin.Extension;
import sonia.scm.user.UserDAO;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.List;
import java.util.Set;
//~--- JDK imports ------------------------------------------------------------
import javax.inject.Inject;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Realm for authentication with {@link BearerToken}.
@@ -71,34 +56,29 @@ import org.slf4j.LoggerFactory;
@Extension
public class BearerRealm extends AuthenticatingRealm
{
/**
* the logger for BearerRealm
*/
private static final Logger LOG = LoggerFactory.getLogger(BearerRealm.class);
/** realm name */
@VisibleForTesting
static final String REALM = "BearerRealm";
//~--- constructors ---------------------------------------------------------
/** dao realm helper */
private final DAORealmHelper helper;
/** access token resolver **/
private final AccessTokenResolver tokenResolver;
/**
* Constructs ...
*
* @param helperFactory dao realm helper factory
* @param resolver key resolver
* @param validators token claims validators
* @param tokenResolver resolve access token from bearer
*/
@Inject
public BearerRealm(
DAORealmHelperFactory helperFactory, SecureKeyResolver resolver, Set<TokenClaimsValidator> validators
)
{
public BearerRealm(DAORealmHelperFactory helperFactory, AccessTokenResolver tokenResolver) {
this.helper = helperFactory.create(REALM);
this.resolver = resolver;
this.validators = validators;
this.tokenResolver = tokenResolver;
setCredentialsMatcher(new AllowAllCredentialsMatcher());
setAuthenticationTokenClass(BearerToken.class);
}
@@ -106,71 +86,26 @@ public class BearerRealm extends AuthenticatingRealm
//~--- methods --------------------------------------------------------------
/**
* Validates the given jwt token and retrieves authentication data from
* Validates the given bearer token and retrieves authentication data from
* {@link UserDAO} and {@link GroupDAO}.
*
*
* @param token jwt token
* @param token bearer token
*
* @return authentication data from user and group dao
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token)
{
checkArgument(token instanceof BearerToken, "%s is required",
BearerToken.class);
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
checkArgument(token instanceof BearerToken, "%s is required", BearerToken.class);
BearerToken bt = (BearerToken) token;
Claims c = checkToken(bt);
AccessToken accessToken = tokenResolver.resolve(bt);
return helper.getAuthenticationInfo(c.getSubject(), bt.getCredentials(), Scopes.fromClaims(c));
return helper.getAuthenticationInfo(
accessToken.getSubject(),
bt.getCredentials(),
Scopes.fromClaims(accessToken.getClaims())
);
}
/**
* Validates the jwt token.
*
*
* @param token jwt token
*
* @return claim
*/
private Claims checkToken(BearerToken token)
{
Claims claims;
try
{
//J-
claims = Jwts.parser()
.setSigningKeyResolver(resolver)
.parseClaimsJws(token.getCredentials())
.getBody();
//J+
// check all registered claims validators
validators.forEach((validator) -> {
if (!validator.validate(claims)) {
LOG.warn("token claims is invalid, marked by validator {}", validator.getClass());
throw new AuthenticationException("token claims is invalid");
}
});
}
catch (JwtException ex)
{
throw new AuthenticationException("signature is invalid", ex);
}
return claims;
}
//~--- fields ---------------------------------------------------------------
/** token claims validators **/
private final Set<TokenClaimsValidator> validators;
/** dao realm helper */
private final DAORealmHelper helper;
/** secure key resolver */
private final SecureKeyResolver resolver;
}

View File

@@ -55,37 +55,48 @@ public final class JwtAccessTokenResolver implements AccessTokenResolver {
private static final Logger LOG = LoggerFactory.getLogger(JwtAccessTokenResolver.class);
private final SecureKeyResolver keyResolver;
private final Set<TokenClaimsValidator> validators;
private final Set<AccessTokenValidator> validators;
@Inject
public JwtAccessTokenResolver(SecureKeyResolver keyResolver, Set<TokenClaimsValidator> validators) {
public JwtAccessTokenResolver(SecureKeyResolver keyResolver, Set<AccessTokenValidator> validators) {
this.keyResolver = keyResolver;
this.validators = validators;
}
@Override
public JwtAccessToken resolve(BearerToken bearerToken) {
Claims claims;
try {
// parse and validate
claims = Jwts.parser()
String compact = bearerToken.getCredentials();
Claims claims = Jwts.parser()
.setSigningKeyResolver(keyResolver)
.parseClaimsJws(bearerToken.getCredentials())
.parseClaimsJws(compact)
.getBody();
// check all registered claims validators
validators.forEach((validator) -> {
if (!validator.validate(claims)) {
LOG.warn("token claims is invalid, marked by validator {}", validator.getClass());
throw new AuthenticationException("token claims is invalid");
}
});
JwtAccessToken token = new JwtAccessToken(claims, compact);
validate(token);
return token;
} catch (JwtException ex) {
throw new AuthenticationException("signature is invalid", ex);
}
return new JwtAccessToken(claims, bearerToken.getCredentials());
}
private void validate(AccessToken accessToken) {
validators.forEach(validator -> validate(validator, accessToken));
}
private void validate(AccessTokenValidator validator, AccessToken accessToken) {
if (!validator.validate(accessToken)) {
String msg = createValidationFailedMessage(validator, accessToken);
LOG.debug(msg);
throw new AuthenticationException(msg);
}
}
private String createValidationFailedMessage(AccessTokenValidator validator, AccessToken accessToken) {
return String.format("token %s is invalid, marked by validator %s", accessToken.getId(), validator.getClass());
}
}

View File

@@ -47,7 +47,7 @@ import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.PermissionResolver;
/**
* Utile methods for {@link Scope}.
* Util methods for {@link Scope}.
*
* @author Sebastian Sdorra
* @since 2.0.0

View File

@@ -44,7 +44,7 @@ import sonia.scm.util.HttpUtil;
/**
* Xsrf access token enricher will add an xsrf custom field to the access token. The enricher will only
* add the xsrf field, if the authentication request is issued from the web interface and xsrf protection is
* enabled. The xsrf field will be validated on every request by the {@link XsrfTokenClaimsValidator}. Xsrf protection
* enabled. The xsrf field will be validated on every request by the {@link XsrfAccessTokenValidator}. Xsrf protection
* can be disabled with {@link ScmConfiguration#setEnabledXsrfProtection(boolean)}.
*
* @see <a href="https://goo.gl/s67xO3">Issue 793</a>

View File

@@ -30,30 +30,23 @@
*/
package sonia.scm.security;
import com.google.common.base.Strings;
import java.util.Map;
import sonia.scm.plugin.Extension;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.plugin.Extension;
import java.util.Optional;
/**
* Validates xsrf protected token claims. The validator check if the current request contains an xsrf key which is
* equal to the token in the claims. If the claims does not contain a xsrf key, the check is passed by. The xsrf keys
* are added by the {@link XsrfTokenClaimsEnricher}.
* Validates xsrf protected access tokens. The validator check if the current request contains an xsrf key which is
* equal to the one in the access token. If the token does not contain a xsrf key, the check is passed by. The xsrf keys
* are added by the {@link XsrfAccessTokenEnricher}.
*
* @author Sebastian Sdorra
* @since 2.0.0
*/
@Extension
public class XsrfTokenClaimsValidator implements TokenClaimsValidator {
/**
* the logger for XsrfTokenClaimsEnricher
*/
private static final Logger LOG = LoggerFactory.getLogger(XsrfTokenClaimsValidator.class);
public class XsrfAccessTokenValidator implements AccessTokenValidator {
private final Provider<HttpServletRequest> requestProvider;
@@ -64,16 +57,16 @@ public class XsrfTokenClaimsValidator implements TokenClaimsValidator {
* @param requestProvider http request provider
*/
@Inject
public XsrfTokenClaimsValidator(Provider<HttpServletRequest> requestProvider) {
public XsrfAccessTokenValidator(Provider<HttpServletRequest> requestProvider) {
this.requestProvider = requestProvider;
}
@Override
public boolean validate(Map<String, Object> claims) {
String xsrfClaimValue = (String) claims.get(Xsrf.TOKEN_KEY);
if (!Strings.isNullOrEmpty(xsrfClaimValue)) {
public boolean validate(AccessToken accessToken) {
Optional<String> xsrfClaim = accessToken.getCustom(Xsrf.TOKEN_KEY);
if (xsrfClaim.isPresent()) {
String xsrfHeaderValue = requestProvider.get().getHeader(Xsrf.HEADER_KEY);
return xsrfClaimValue.equals(xsrfHeaderValue);
return xsrfClaim.get().equals(xsrfHeaderValue);
}
return true;
}