Merge branch 'support/2.6.x' into develop

This commit is contained in:
René Pfeuffer
2020-10-09 12:16:23 +02:00
7 changed files with 103 additions and 8 deletions

View File

@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
### Added
- Users can create API keys with limited permissions ([#1359](https://github.com/scm-manager/scm-manager/pull/1359))
- Introduce api for handling token validation failed exception ([#1362](https://github.com/scm-manager/scm-manager/pull/1362))
### Fixed
- Align actionbar item horizontal and enforce correct margin between them ([#1358](https://github.com/scm-manager/scm-manager/pull/1358))

View File

@@ -0,0 +1,51 @@
/*
* 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.AuthenticationException;
/**
* Thrown by the {@link AccessTokenResolver} when an {@link AccessTokenValidator} fails to validate an access token.
* @since 2.6.2
*/
@SuppressWarnings("squid:MaximumInheritanceDepth") // exceptions have a deep inheritance depth themselves; therefore we accept this here
public class TokenValidationFailedException extends AuthenticationException {
private final AccessTokenValidator validator;
private final AccessToken accessToken;
public TokenValidationFailedException(AccessTokenValidator validator, AccessToken accessToken) {
super(String.format("Token validator %s failed for access token %s", validator.getClass(), accessToken.getId()));
this.validator = validator;
this.accessToken = accessToken;
}
public AccessTokenValidator getValidator() {
return validator;
}
public AccessToken getAccessToken() {
return accessToken;
}
}

View File

@@ -39,6 +39,7 @@ import sonia.scm.config.ScmConfiguration;
import sonia.scm.security.AnonymousMode;
import sonia.scm.security.AnonymousToken;
import sonia.scm.security.TokenExpiredException;
import sonia.scm.security.TokenValidationFailedException;
import sonia.scm.util.HttpUtil;
import sonia.scm.util.Util;
import sonia.scm.web.WebTokenGenerator;
@@ -168,9 +169,15 @@ public class AuthenticationFilter extends HttpFilter {
protected void handleTokenExpiredException(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, TokenExpiredException tokenExpiredException) throws IOException, ServletException {
logger.trace("rethrow token expired exception");
throw tokenExpiredException;
}
protected void handleTokenValidationFailedException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, TokenValidationFailedException tokenValidationFailedException) throws IOException, ServletException {
logger.trace("send unauthorized, because of a failed token validation");
handleUnauthorized(request, response, chain);
}
/**
* Iterates all {@link WebTokenGenerator} and creates an
* {@link AuthenticationToken} from the given request.
@@ -216,7 +223,11 @@ public class AuthenticationFilter extends HttpFilter {
processChain(request, response, chain, subject);
} catch (TokenExpiredException ex) {
// Rethrow to be caught by TokenExpiredFilter
logger.trace("handle token expired exception");
handleTokenExpiredException(request, response, chain, ex);
} catch (TokenValidationFailedException ex) {
logger.trace("handle token validation failed exception");
handleTokenValidationFailedException(request, response, chain, ex);
} catch (AuthenticationException ex) {
logger.warn("authentication failed", ex);
handleUnauthorized(request, response, chain);
@@ -259,7 +270,7 @@ public class AuthenticationFilter extends HttpFilter {
*
* @return {@code true} if anonymous access is enabled
*/
private boolean isAnonymousAccessEnabled() {
protected boolean isAnonymousAccessEnabled() {
return (configuration != null) && configuration.getAnonymousMode() != AnonymousMode.OFF;
}
}

View File

@@ -89,7 +89,7 @@ public final class JwtAccessTokenResolver implements AccessTokenResolver {
if (!validator.validate(accessToken)) {
String msg = createValidationFailedMessage(validator, accessToken);
LOG.debug(msg);
throw new AuthenticationException(msg);
throw new TokenValidationFailedException(validator, accessToken);
}
}

View File

@@ -55,16 +55,16 @@ public class ScmAtLeastOneSuccessfulStrategy extends AbstractAuthenticationStrat
}
@Override
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) {
final List<Throwable> throwables = threadLocal.get();
threadLocal.remove();
if (isAuthenticationSuccessful(aggregate)) {
return aggregate;
}
Optional<TokenExpiredException> tokenExpiredException = findTokenExpiredException(throwables);
Optional<? extends AuthenticationException> specializedException = findSpecializedException(throwables);
if (tokenExpiredException.isPresent()) {
throw tokenExpiredException.get();
if (specializedException.isPresent()) {
throw specializedException.get();
} else {
throw createAuthenticationException(token);
}
@@ -82,6 +82,18 @@ public class ScmAtLeastOneSuccessfulStrategy extends AbstractAuthenticationStrat
return throwables.stream().filter(t -> t instanceof TokenExpiredException).findFirst().map(t -> (TokenExpiredException) t);
}
private static Optional<AuthenticationException> findTokenValidationFailedException(List<Throwable> throwables) {
return throwables.stream().filter(t -> t instanceof TokenValidationFailedException).findFirst().map(t -> (TokenValidationFailedException) t);
}
private static Optional<? extends AuthenticationException> findSpecializedException(List<Throwable> throwables) {
Optional<TokenExpiredException> tokenExpiredException = findTokenExpiredException(throwables);
if (tokenExpiredException.isPresent()) {
return tokenExpiredException;
}
return findTokenValidationFailedException(throwables);
}
private static AuthenticationException createAuthenticationException(AuthenticationToken token) {
return new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
"could not be authenticated by any configured realms. Please ensure that at least one realm can " +

View File

@@ -110,7 +110,7 @@ public class JwtAccessTokenResolverTest {
when(validator.validate(Mockito.any(AccessToken.class))).thenReturn(false);
// expect exception
expectedException.expect(AuthenticationException.class);
expectedException.expect(TokenValidationFailedException.class);
expectedException.expectMessage(Matchers.containsString("token"));
BearerToken bearer = BearerToken.valueOf(compact);

View File

@@ -36,6 +36,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
@@ -59,6 +60,9 @@ public class ScmAtLeastOneSuccessfulStrategyTest {
@Mock
TokenExpiredException tokenExpiredException;
@Mock
TokenValidationFailedException tokenValidationFailedException;
@Mock
AuthenticationException authenticationException;
@@ -77,13 +81,29 @@ public class ScmAtLeastOneSuccessfulStrategyTest {
}
@Test(expected = TokenExpiredException.class)
public void shouldRethrowException() {
public void shouldRethrowTokenExpiredException() {
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
strategy.threadLocal.set(singletonList(tokenExpiredException));
strategy.afterAllAttempts(token, aggregateInfo);
}
@Test(expected = TokenValidationFailedException.class)
public void shouldRethrowTokenValidationFailedException() {
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
strategy.threadLocal.set(singletonList(tokenValidationFailedException));
strategy.afterAllAttempts(token, aggregateInfo);
}
@Test(expected = TokenExpiredException.class)
public void shouldPrioritizeRethrowingTokenExpiredExceptionOverTokenValidationFailedException() {
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
strategy.threadLocal.set(Arrays.asList(tokenValidationFailedException, tokenExpiredException));
strategy.afterAllAttempts(token, aggregateInfo);
}
@Test(expected = AuthenticationException.class)
public void shouldThrowGenericErrorIfNonTokenExpiredExceptionWasCaught() {
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();