Handle Plugin Center Authentication failures (#1940)

If the plugin center authentication fails,
the plugins are fetched without authentication
and a warning is displayed on the plugin page.

Co-authored-by: Konstantin Schaper <konstantin.schaper@cloudogu.com>
This commit is contained in:
Sebastian Sdorra
2022-01-31 15:41:12 +01:00
committed by GitHub
parent 67bd96ea81
commit c74e9984f6
22 changed files with 505 additions and 117 deletions

View File

@@ -53,9 +53,16 @@ import sonia.scm.user.UserDisplayManager;
import sonia.scm.util.HttpUtil;
import sonia.scm.web.VndMediaType;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.*;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
@@ -81,6 +88,9 @@ public class PluginCenterAuthResource {
@VisibleForTesting
static final String ERROR_CHALLENGE_DOES_NOT_MATCH = "8ESqFElpI1";
private static final String METHOD_LOGIN = "login";
private static final String METHOD_LOGOUT = "logout";
private final ScmPathInfoStore pathInfoStore;
private final PluginCenterAuthenticator authenticator;
private final ScmConfiguration configuration;
@@ -107,6 +117,7 @@ public class PluginCenterAuthResource {
}
@VisibleForTesting
@SuppressWarnings("java:S107") // parameter count is ok for testing
PluginCenterAuthResource(
ScmPathInfoStore pathInfoStore,
PluginCenterAuthenticator authenticator,
@@ -158,20 +169,21 @@ public class PluginCenterAuthResource {
if (authentication.isPresent()) {
return Response.ok(createAuthenticatedDto(uriInfo, authentication.get())).build();
}
PluginCenterAuthenticationInfoDto dto = new PluginCenterAuthenticationInfoDto(createLinks(uriInfo, false));
PluginCenterAuthenticationInfoDto dto = new PluginCenterAuthenticationInfoDto(createLinks(uriInfo, null));
dto.setDefault(configuration.isDefaultPluginAuthUrl());
return Response.ok(dto).build();
}
private PluginCenterAuthenticationInfoDto createAuthenticatedDto(@Context UriInfo uriInfo, AuthenticationInfo info) {
private PluginCenterAuthenticationInfoDto createAuthenticatedDto(UriInfo uriInfo, AuthenticationInfo info) {
PluginCenterAuthenticationInfoDto dto = new PluginCenterAuthenticationInfoDto(
createLinks(uriInfo, true)
createLinks(uriInfo, info)
);
dto.setPrincipal(getPrincipalDisplayName(info.getPrincipal()));
dto.setPluginCenterSubject(info.getPluginCenterSubject());
dto.setDate(info.getDate());
dto.setDefault(configuration.isDefaultPluginAuthUrl());
dto.setFailed(info.isFailed());
return dto;
}
@@ -197,7 +209,9 @@ public class PluginCenterAuthResource {
schema = @Schema(implementation = ErrorDto.class)
)
)
public Response login(@Context UriInfo uriInfo, @QueryParam("source") String source) throws IOException {
public Response login(
@Context UriInfo uriInfo, @QueryParam("source") String source, @QueryParam("reconnect") boolean reconnect
) throws IOException {
String pluginAuthUrl = configuration.getPluginAuthUrl();
if (Strings.isNullOrEmpty(source)) {
@@ -208,7 +222,7 @@ public class PluginCenterAuthResource {
return error(ERROR_AUTHENTICATION_DISABLED);
}
if (authenticator.isAuthenticated()) {
if (!reconnect && authenticator.isAuthenticated()) {
return error(ERROR_ALREADY_AUTHENTICATED);
}
@@ -235,15 +249,22 @@ public class PluginCenterAuthResource {
return Response.seeOther(authUri).build();
}
private Links createLinks(UriInfo uriInfo, boolean authenticated) {
private Links createLinks(UriInfo uriInfo, @Nullable AuthenticationInfo info) {
String self = uriInfo.getAbsolutePath().toASCIIString();
Links.Builder builder = Links.linkingTo().self(self);
if (PluginPermissions.write().isPermitted()) {
if (authenticated) {
builder.single(Link.link("logout", self));
if (info != null) {
builder.single(Link.link(METHOD_LOGOUT, self));
if (info.isFailed()) {
String reconnectLink = uriInfo.getAbsolutePathBuilder()
.path(METHOD_LOGIN)
.queryParam("reconnect", "true")
.build()
.toASCIIString();
builder.single(Link.link("reconnect", reconnectLink));
}
} else {
URI login = uriInfo.getAbsolutePathBuilder().path("login").build();
builder.single(Link.link("login", login.toASCIIString()));
builder.single(Link.link(METHOD_LOGIN, uriInfo.getAbsolutePathBuilder().path(METHOD_LOGIN).build().toASCIIString()));
}
}
return builder.build();

View File

@@ -46,6 +46,7 @@ public class PluginCenterAuthenticationInfoDto extends HalRepresentation {
@JsonInclude(NON_NULL)
private Instant date;
private boolean isDefault;
private boolean failed;
public PluginCenterAuthenticationInfoDto(Links links) {
super(links);

View File

@@ -49,4 +49,14 @@ public interface AuthenticationInfo {
* @return authentication date
*/
Instant getDate();
/**
* Returns {@code true} if the last authentication has failed.
* @return {@code true} if the last authentication has failed.
* @since 2.31.0
*/
default boolean isFailed() {
return false;
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.plugin;
import lombok.Value;
import sonia.scm.event.Event;
/**
* Event is thrown if the authentication to the plugin center fails.
* @since 2.30.0
*/
@Event
@Value
public class PluginCenterAuthenticationFailedEvent implements PluginCenterAuthenticationEvent {
AuthenticationInfo authenticationInfo;
}

View File

@@ -34,6 +34,8 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Value;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.event.ScmEventBus;
import sonia.scm.net.ahc.AdvancedHttpClient;
@@ -59,6 +61,8 @@ import static sonia.scm.plugin.Tracing.SPAN_KIND;
@Singleton
public class PluginCenterAuthenticator {
private static final Logger LOG = LoggerFactory.getLogger(PluginCenterAuthenticator.class);
@VisibleForTesting
static final String STORE_NAME = "plugin-center-auth";
@@ -86,7 +90,9 @@ public class PluginCenterAuthenticator {
PluginPermissions.write().check();
// check if refresh token is valid
Authentication authentication = new Authentication(principal(), pluginCenterSubject, refreshToken, Instant.now());
Authentication authentication = new Authentication(
principal(), pluginCenterSubject, refreshToken, Instant.now(), false
);
fetchAccessToken(authentication);
eventBus.post(new PluginCenterLoginEvent(authentication));
}
@@ -109,11 +115,16 @@ public class PluginCenterAuthenticator {
return getAuthentication().map(a -> a);
}
public String fetchAccessToken() {
public Optional<String> fetchAccessToken() {
PluginPermissions.read().check();
Authentication authentication = getAuthentication()
.orElseThrow(() -> new IllegalStateException("An access token can only be obtained, after a prior authentication"));
return fetchAccessToken(authentication);
try {
return Optional.of(fetchAccessToken(authentication));
} catch (FetchAccessTokenFailedException ex) {
LOG.warn("failed to fetch access token", ex);
return Optional.empty();
}
}
@CanIgnoreReturnValue
@@ -128,20 +139,29 @@ public class PluginCenterAuthenticator {
.request();
if (!response.isSuccessful()) {
authenticationFailed(authentication);
throw new FetchAccessTokenFailedException("failed to obtain access token, server returned status code " + response.getStatus());
}
RefreshResponse refresh = response.contentFromJson(RefreshResponse.class);
authentication.setRefreshToken(refresh.getRefreshToken());
authentication.setFailed(false);
configurationStore.set(authentication);
return refresh.getAccessToken();
} catch (IOException ex) {
authenticationFailed(authentication);
throw new FetchAccessTokenFailedException("failed to obtain an access token", ex);
}
}
private void authenticationFailed(Authentication authentication) {
authentication.setFailed(true);
configurationStore.set(authentication);
eventBus.post(new PluginCenterAuthenticationFailedEvent(authentication));
}
private String principal() {
return SecurityUtils.getSubject().getPrincipal().toString();
}
@@ -162,6 +182,7 @@ public class PluginCenterAuthenticator {
private String refreshToken;
@XmlJavaTypeAdapter(XmlInstantAdapter.class)
private Instant date;
private boolean failed;
}
@Value

View File

@@ -69,7 +69,7 @@ class PluginCenterLoader {
LOG.info("fetch plugins from {}", url);
AdvancedHttpRequest request = client.get(url).spanKind(SPAN_KIND);
if (authenticator.isAuthenticated()) {
request.bearerAuth(authenticator.fetchAccessToken());
authenticator.fetchAccessToken().ifPresent(request::bearerAuth);
}
PluginCenterDto pluginCenterDto = request.request().contentFromJson(PluginCenterDto.class);
return mapper.map(pluginCenterDto);

View File

@@ -132,7 +132,7 @@ class PluginInstaller {
private InputStream download(AvailablePlugin plugin) throws IOException {
AdvancedHttpRequest request = client.get(plugin.getDescriptor().getUrl()).spanKind(SPAN_KIND);
if (authenticator.isAuthenticated()) {
request.bearerAuth(authenticator.fetchAccessToken());
authenticator.fetchAccessToken().ifPresent(request::bearerAuth);
}
return request.request().contentAsStream();
}