Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Force refresh personal access token #695

Merged
merged 6 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
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;
Expand Down Expand Up @@ -188,6 +190,12 @@ private Optional<PersonalAccessToken> doGetPersonalAccessToken(
.access(null, namespaceMeta.getName())
.secrets()
.get(KUBERNETES_PERSONAL_ACCESS_TOKEN_LABEL_SELECTOR);

// sort secrets to get the newest one first
Collections.sort(
secrets, Comparator.comparing(secret -> secret.getMetadata().getCreationTimestamp()));
Collections.reverse(secrets);

for (Secret secret : secrets) {
LOG.debug("Checking secret {}", secret.getMetadata().getName());
if (deleteSecretIfMisconfigured(secret)) {
Expand Down Expand Up @@ -330,6 +338,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
@@ -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,35 @@ 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;
}

try {
credential.refreshToken();
credential = flow.loadCredential(userId);
return newDto(OAuthToken.class).withToken(credential.getAccessToken());
} catch (IOException ioEx) {
try {
invalidateTokenByUser(userId);
} catch (IOException ignored) {
}
return null;
}
}

/**
* Invalidate OAuth token for specified user.
*
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 @@ -32,7 +32,8 @@ public OAuthToken getToken(String oauthProviderName, String userId) throws IOExc
OAuthAuthenticator oAuthAuthenticator =
oAuthAuthenticatorProvider.getAuthenticator(oauthProviderName);
OAuthToken token;
if (oAuthAuthenticator != null && (token = oAuthAuthenticator.getToken(userId)) != null) {
if (oAuthAuthenticator != null
&& (token = oAuthAuthenticator.getOrRefreshToken(userId)) != null) {
return token;
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public class EmbeddedOAuthAPITest {
expectedExceptions = NotFoundException.class,
expectedExceptionsMessageRegExp = "Unsupported OAuth provider unknown")
public void shouldThrowExceptionIfNoSuchProviderFound() throws Exception {
embeddedOAuthAPI.getToken("unknown");
embeddedOAuthAPI.getOrRefreshToken("unknown");
}

@Test
Expand All @@ -70,9 +70,10 @@ public void shouldBeAbleToGetUserToken() throws Exception {
OAuthAuthenticator authenticator = mock(OAuthAuthenticator.class);
when(oauth2Providers.getAuthenticator(eq(provider))).thenReturn(authenticator);

when(authenticator.getToken(anyString())).thenReturn(newDto(OAuthToken.class).withToken(token));
when(authenticator.getOrRefreshToken(anyString()))
.thenReturn(newDto(OAuthToken.class).withToken(token));

OAuthToken result = embeddedOAuthAPI.getToken(provider);
OAuthToken result = embeddedOAuthAPI.getOrRefreshToken(provider);

assertEquals(result.getToken(), token);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,21 @@ public AzureDevOpsPersonalAccessTokenFetcher(
this.azureDevOpsApiClient = azureDevOpsApiClient;
}

@Override
public PersonalAccessToken refreshPersonalAccessToken(Subject cheSubject, String scmServerUrl)
throws ScmUnauthorizedException, ScmCommunicationException, UnknownScmProviderException {
return fetchOrRefreshPersonalAccessToken(cheSubject, scmServerUrl, true);
}

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String scmServerUrl)
throws ScmUnauthorizedException, ScmCommunicationException, UnknownScmProviderException {
return fetchOrRefreshPersonalAccessToken(cheSubject, scmServerUrl, false);
}

private PersonalAccessToken fetchOrRefreshPersonalAccessToken(
Subject cheSubject, String scmServerUrl, boolean forceRefreshToken)
throws ScmUnauthorizedException, ScmCommunicationException, UnknownScmProviderException {
OAuthToken oAuthToken;

if (!isValidScmServerUrl(scmServerUrl)) {
Expand All @@ -82,7 +94,10 @@ public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String s
}

try {
oAuthToken = oAuthAPI.getToken(AzureDevOps.PROVIDER_NAME);
oAuthToken =
forceRefreshToken
? oAuthAPI.refreshToken(AzureDevOps.PROVIDER_NAME)
: oAuthAPI.getOrRefreshToken(AzureDevOps.PROVIDER_NAME);
String tokenName = NameGenerator.generate(OAUTH_2_PREFIX, 5);
String tokenId = NameGenerator.generate("id-", 5);
Optional<Pair<Boolean, String>> valid =
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 @@ -94,7 +94,7 @@ public void fetchPersonalAccessTokenShouldReturnToken() throws Exception {
personalAccessTokenFetcher =
new AzureDevOpsPersonalAccessTokenFetcher(
"localhost", "https://dev.azure.com", new String[] {}, azureDevOpsApiClient, oAuthAPI);
when(oAuthAPI.getToken(AzureDevOps.PROVIDER_NAME)).thenReturn(oAuthToken);
when(oAuthAPI.getOrRefreshToken(AzureDevOps.PROVIDER_NAME)).thenReturn(oAuthToken);
when(azureDevOpsApiClient.getUserWithOAuthToken(any())).thenReturn(azureDevOpsUser);
when(azureDevOpsUser.getEmailAddress()).thenReturn("user-email");

Expand All @@ -112,7 +112,7 @@ public void fetchPersonalAccessTokenShouldReturnToken() throws Exception {
public void shouldThrowUnauthorizedExceptionIfTokenIsNotValid() throws Exception {
Subject subject = new SubjectImpl("Username", "id1", "token", false);
OAuthToken oAuthToken = newDto(OAuthToken.class).withToken(azureOauthToken).withScope("");
when(oAuthAPI.getToken(anyString())).thenReturn(oAuthToken);
when(oAuthAPI.getOrRefreshToken(anyString())).thenReturn(oAuthToken);
stubFor(
get(urlEqualTo("/_apis/profile/profiles/me?api-version=7.0"))
.withHeader(HttpHeaders.AUTHORIZATION, equalTo("token " + azureOauthToken))
Expand Down
Loading
Loading