Skip to content

Commit

Permalink
feat: Force refresh personal access token (#695)
Browse files Browse the repository at this point in the history
* feat: Force refresh personal access token

Signed-off-by: Anatolii Bazko <abazko@redhat.com>

* feat: Force refresh personal access token

Signed-off-by: Anatolii Bazko <abazko@redhat.com>

* Fix tests

Signed-off-by: Anatolii Bazko <abazko@redhat.com>

* Use FORCE_REFRESH_TOKEN by default for testing purpose

Signed-off-by: Anatolii Bazko <abazko@redhat.com>

* Don't force refresh token by default

Signed-off-by: Anatolii Bazko <abazko@redhat.com>

* Fixup

Signed-off-by: Anatolii Bazko <abazko@redhat.com>

---------

Signed-off-by: Anatolii Bazko <abazko@redhat.com>
  • Loading branch information
tolusha authored Jun 28, 2024
1 parent 4a5faff commit de9e1ff
Show file tree
Hide file tree
Showing 32 changed files with 276 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@
import io.fabric8.kubernetes.client.KubernetesClientException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.eclipse.che.api.factory.server.scm.GitCredentialManager;
Expand Down Expand Up @@ -188,6 +191,15 @@ private Optional<PersonalAccessToken> doGetPersonalAccessToken(
.access(null, namespaceMeta.getName())
.secrets()
.get(KUBERNETES_PERSONAL_ACCESS_TOKEN_LABEL_SELECTOR);

// sort secrets to get the newest one first
// Assign to new list to avoid UnsupportedOperationException (ImmutableList)
secrets =
secrets.stream()
.sorted(Comparator.comparing(secret -> secret.getMetadata().getCreationTimestamp()))
.collect(Collectors.toList());
Collections.reverse(secrets);

for (Secret secret : secrets) {
LOG.debug("Checking secret {}", secret.getMetadata().getName());
if (deleteSecretIfMisconfigured(secret)) {
Expand Down Expand Up @@ -330,6 +342,17 @@ public PersonalAccessToken getAndStore(String scmServerUrl)
return personalAccessToken;
}

@Override
public void forceRefreshPersonalAccessToken(String scmServerUrl)
throws ScmUnauthorizedException, ScmCommunicationException, UnknownScmProviderException,
UnsatisfiedScmPreconditionException, ScmConfigurationPersistenceException {
Subject subject = EnvironmentContext.getCurrent().getSubject();
PersonalAccessToken personalAccessToken =
scmPersonalAccessTokenFetcher.refreshPersonalAccessToken(subject, scmServerUrl);
gitCredentialManager.createOrReplace(personalAccessToken);
store(personalAccessToken);
}

@Override
public void storeGitCredentials(String scmServerUrl)
throws UnsatisfiedScmPreconditionException, ScmConfigurationPersistenceException,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ public void shouldTrimBlankCharsInToken() throws Exception {

ObjectMeta meta1 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-01T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand Down Expand Up @@ -185,6 +186,7 @@ public void testGetTokenFromNamespace() throws Exception {

ObjectMeta meta1 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-01T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand All @@ -196,6 +198,7 @@ public void testGetTokenFromNamespace() throws Exception {
.build();
ObjectMeta meta2 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-02T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand All @@ -207,6 +210,7 @@ public void testGetTokenFromNamespace() throws Exception {
.build();
ObjectMeta meta3 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-03T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand Down Expand Up @@ -343,6 +347,7 @@ public void testGetTokenFromNamespaceWithTrailingSlashMismatch() throws Exceptio

ObjectMeta meta1 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-01T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand All @@ -354,6 +359,7 @@ public void testGetTokenFromNamespaceWithTrailingSlashMismatch() throws Exceptio
.build();
ObjectMeta meta2 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-08-01T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand Down Expand Up @@ -475,15 +481,17 @@ public void shouldReturnFirstValidToken() throws Exception {
? Optional.of("user")
: Optional.empty();
});
when(cheServerKubernetesClientFactory.create()).thenReturn(kubeClient);
when(kubeClient.secrets()).thenReturn(secretsMixedOperation);
when(secretsMixedOperation.inNamespace(eq(meta.getName()))).thenReturn(nonNamespaceOperation);
// when(cheServerKubernetesClientFactory.create()).thenReturn(kubeClient);
// when(kubeClient.secrets()).thenReturn(secretsMixedOperation);
//
// when(secretsMixedOperation.inNamespace(eq(meta.getName()))).thenReturn(nonNamespaceOperation);
Map<String, String> data1 =
Map.of("token", Base64.getEncoder().encodeToString("token1".getBytes(UTF_8)));
Map<String, String> data2 =
Map.of("token", Base64.getEncoder().encodeToString("token2".getBytes(UTF_8)));
ObjectMeta meta1 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-01T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand All @@ -497,6 +505,7 @@ public void shouldReturnFirstValidToken() throws Exception {
.build();
ObjectMeta meta2 =
new ObjectMetaBuilder()
.withCreationTimestamp("2021-07-02T12:00:00Z")
.withAnnotations(
Map.of(
ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012-2021 Red Hat, Inc.
* Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
Expand Down Expand Up @@ -67,7 +67,7 @@ public Response authenticate(
}

@Override
public OAuthToken getToken(String oauthProvider)
public OAuthToken getOrRefreshToken(String oauthProvider)
throws ForbiddenException, BadRequestException, NotFoundException, ServerException,
UnauthorizedException {
try {
Expand All @@ -81,6 +81,11 @@ public OAuthToken getToken(String oauthProvider)
}
}

@Override
public OAuthToken refreshToken(String oauthProvider) throws ForbiddenException {
throw new ForbiddenException("Method is not supported in this implementation of OAuth API");
}

@Override
public void invalidateToken(String oauthProvider) throws ForbiddenException {
throw new ForbiddenException("Method is not supported in this implementation of OAuth API");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012-2023 Red Hat, Inc.
* Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
Expand Down Expand Up @@ -85,8 +85,8 @@ public final String getOAuthProvider() {
}

@Override
public OAuthToken getToken(String userId) throws IOException {
final OAuthToken token = super.getToken(userId);
public OAuthToken getOrRefreshToken(String userId) throws IOException {
final OAuthToken token = super.getOrRefreshToken(userId);
try {
// check if user's token is valid by requesting user profile data
if (token == null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public final String getOAuthProvider() {
}

@Override
public OAuthToken getToken(String userId) throws IOException {
final OAuthToken token = super.getToken(userId);
public OAuthToken getOrRefreshToken(String userId) throws IOException {
final OAuthToken token = super.getOrRefreshToken(userId);
// Need to check if token is valid for requests, if valid - return it to caller.
try {
if (token == null || isNullOrEmpty(token.getToken())) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012-2023 Red Hat, Inc.
* Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
Expand Down Expand Up @@ -85,8 +85,8 @@ public boolean invalidateToken(String token) throws IOException {
}

@Override
public OAuthToken getToken(String oauthProvider) throws IOException {
final OAuthToken token = super.getToken(oauthProvider);
public OAuthToken getOrRefreshToken(String oauthProvider) throws IOException {
final OAuthToken token = super.getOrRefreshToken(oauthProvider);
// Need to check if token which is stored is valid for requests, then if valid - we returns it
// to
// caller
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ protected <O> O getJson(String getUserUrl, String accessToken, Class<O> userClas
}

@Override
public OAuthToken getToken(String userId) throws IOException {
final OAuthToken token = super.getToken(userId);
public OAuthToken getOrRefreshToken(String userId) throws IOException {
final OAuthToken token = super.getOrRefreshToken(userId);
try {
if (token == null || token.getToken() == null || token.getToken().isEmpty()) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public void shouldGetToken() throws Exception {
.withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer token"))
.willReturn(aResponse().withBody("{\"id\": \"testId\"}")));
// when
OAuthToken token = gitLabOAuthAuthenticator.getToken("userId");
OAuthToken token = gitLabOAuthAuthenticator.getOrRefreshToken("userId");
// then
assertEquals(token.getToken(), "token");
}
Expand All @@ -89,7 +89,7 @@ public void shouldGetEmptyToken() throws Exception {
.withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer token"))
.willReturn(aResponse().withBody("{}")));
// when
OAuthToken token = gitLabOAuthAuthenticator.getToken("userId");
OAuthToken token = gitLabOAuthAuthenticator.getOrRefreshToken("userId");
// then
assertNull(token);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012-2023 Red Hat, Inc.
* Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
Expand Down Expand Up @@ -63,8 +63,8 @@ public final String getOAuthProvider() {
}

@Override
public OAuthToken getToken(String userId) throws IOException {
final OAuthToken token = super.getToken(userId);
public OAuthToken getOrRefreshToken(String userId) throws IOException {
final OAuthToken token = super.getOrRefreshToken(userId);
// Check if the token is valid for requests.
if (!(token == null || token.getToken() == null || token.getToken().isEmpty())) {
HttpURLConnection http = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ public Set<OAuthAuthenticatorDescriptor> getRegisteredAuthenticators(UriInfo uri
}

@Override
public OAuthToken getToken(String oauthProvider)
public OAuthToken getOrRefreshToken(String oauthProvider)
throws NotFoundException, UnauthorizedException, ServerException {
OAuthAuthenticator provider = getAuthenticator(oauthProvider);
Subject subject = EnvironmentContext.getCurrent().getSubject();
try {
OAuthToken token = provider.getToken(subject.getUserId());
OAuthToken token = provider.getOrRefreshToken(subject.getUserId());
if (token == null) {
token = provider.getToken(subject.getUserName());
token = provider.getOrRefreshToken(subject.getUserName());
}
if (token != null) {
return token;
Expand All @@ -248,11 +248,33 @@ public OAuthToken getToken(String oauthProvider)
}
}

@Override
public OAuthToken refreshToken(String oauthProvider)
throws NotFoundException, UnauthorizedException, ServerException {
OAuthAuthenticator provider = getAuthenticator(oauthProvider);
Subject subject = EnvironmentContext.getCurrent().getSubject();
try {
OAuthToken token = provider.refreshToken(subject.getUserId());
if (token == null) {
token = provider.refreshToken(subject.getUserName());
}

if (token != null) {
return token;
} else {
throw new UnauthorizedException(
"OAuth token for user " + subject.getUserId() + " was not found");
}
} catch (IOException e) {
throw new ServerException(e.getLocalizedMessage(), e);
}
}

@Override
public void invalidateToken(String oauthProvider)
throws NotFoundException, UnauthorizedException, ServerException {
OAuthAuthenticator oauth = getAuthenticator(oauthProvider);
OAuthToken oauthToken = getToken(oauthProvider);
OAuthToken oauthToken = getOrRefreshToken(oauthProvider);
try {
if (!oauth.invalidateToken(oauthToken.getToken())) {
throw new UnauthorizedException(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012-2021 Red Hat, Inc.
* Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
Expand Down Expand Up @@ -49,10 +49,19 @@ Set<OAuthAuthenticatorDescriptor> getRegisteredAuthenticators(UriInfo uriInfo)
throws ForbiddenException;

/** Implementation of method {@link OAuthAuthenticationService#token(String)} */
OAuthToken getToken(String oauthProvider)
OAuthToken getOrRefreshToken(String oauthProvider)
throws NotFoundException, UnauthorizedException, ServerException, ForbiddenException,
BadRequestException, ConflictException;

/**
* Refreshes the token for the given OAuth provider.
*
* @param oauthProvider - the OAuth provider name
* @return the refreshed token
*/
OAuthToken refreshToken(String oauthProvider)
throws NotFoundException, UnauthorizedException, ServerException, ForbiddenException;

/** Implementation of method {@link OAuthAuthenticationService#invalidate(String)}} */
void invalidateToken(String oauthProvider)
throws NotFoundException, UnauthorizedException, ServerException, ForbiddenException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public Set<OAuthAuthenticatorDescriptor> getRegisteredAuthenticators() throws Fo
public OAuthToken token(@Required @QueryParam("oauth_provider") String oauthProvider)
throws ServerException, UnauthorizedException, NotFoundException, ForbiddenException,
BadRequestException, ConflictException {
return oAuthAPI.getToken(oauthProvider);
return oAuthAPI.getOrRefreshToken(oauthProvider);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ protected <O> O getJson(String getUserUrl, String accessToken, Class<O> userClas
* @see OAuthTokenProvider#getToken(String, String) TODO: return Optional<OAuthToken> to avoid
* returning null.
*/
public OAuthToken getToken(String userId) throws IOException {
public OAuthToken getOrRefreshToken(String userId) throws IOException {
if (!isConfigured()) {
throw new IOException(AUTHENTICATOR_IS_NOT_CONFIGURED);
}
Expand Down Expand Up @@ -319,6 +319,44 @@ public OAuthToken getToken(String userId) throws IOException {
return newDto(OAuthToken.class).withToken(credential.getAccessToken());
}

/**
* Refresh personal access token.
*
* @param userId user identifier
* @return a refreshed token value or {@code null}
* @throws IOException when error occurs during token loading
*/
public OAuthToken refreshToken(String userId) throws IOException {
if (!isConfigured()) {
throw new IOException(AUTHENTICATOR_IS_NOT_CONFIGURED);
}

Credential credential = flow.loadCredential(userId);
if (credential == null) {
return null;
}

boolean tokenRefreshed;
try {
tokenRefreshed = credential.refreshToken();
} catch (IOException ioEx) {
tokenRefreshed = false;
}

if (tokenRefreshed) {
credential = flow.loadCredential(userId);
} else {
// if token is not refreshed then old value should be invalidated
// and null result should be returned
try {
invalidateTokenByUser(userId);
} catch (IOException ignored) {
}
return null;
}
return newDto(OAuthToken.class).withToken(credential.getAccessToken());
}

/**
* Invalidate OAuth token for specified user.
*
Expand Down
Loading

0 comments on commit de9e1ff

Please sign in to comment.