use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project che-server by eclipse-che.
the class KubernetesPersonalAccessTokenManager method get.
@Override
public Optional<PersonalAccessToken> get(Subject cheUser, String scmServerUrl) throws ScmConfigurationPersistenceException, ScmUnauthorizedException, ScmCommunicationException {
try {
for (KubernetesNamespaceMeta namespaceMeta : namespaceFactory.list()) {
List<Secret> secrets = namespaceFactory.access(null, namespaceMeta.getName()).secrets().get(KUBERNETES_PERSONAL_ACCESS_TOKEN_LABEL_SELECTOR);
for (Secret secret : secrets) {
Map<String, String> annotations = secret.getMetadata().getAnnotations();
String trimmedUrl = StringUtils.trimEnd(annotations.get(ANNOTATION_SCM_URL), '/');
if (annotations.get(ANNOTATION_CHE_USERID).equals(cheUser.getUserId()) && trimmedUrl.equals(StringUtils.trimEnd(scmServerUrl, '/'))) {
PersonalAccessToken token = new PersonalAccessToken(trimmedUrl, annotations.get(ANNOTATION_CHE_USERID), annotations.get(ANNOTATION_SCM_USERNAME), annotations.get(ANNOTATION_SCM_USERID), annotations.get(ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_NAME), annotations.get(ANNOTATION_SCM_PERSONAL_ACCESS_TOKEN_ID), new String(Base64.getDecoder().decode(secret.getData().get("token"))));
if (scmPersonalAccessTokenFetcher.isValid(token)) {
return Optional.of(token);
} else {
// Removing token that is no longer valid. If several tokens exist the next one could
// be valid. If no valid token can be found, the caller should react in the same way
// as it reacts if no token exists. Usually, that means that process of new token
// retrieval would be initiated.
clientFactory.create().secrets().inNamespace(namespaceMeta.getName()).delete(secret);
}
}
}
}
} catch (InfrastructureException | UnknownScmProviderException e) {
throw new ScmConfigurationPersistenceException(e.getMessage(), e);
}
return Optional.empty();
}
use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project che-server by eclipse-che.
the class KubernetesGitCredentialManagerTest method testCreateAndSaveNewOAuthGitCredential.
@Test
public void testCreateAndSaveNewOAuthGitCredential() throws Exception {
KubernetesNamespaceMeta meta = new KubernetesNamespaceMetaImpl("test");
when(namespaceFactory.list()).thenReturn(Collections.singletonList(meta));
when(clientFactory.create()).thenReturn(kubeClient);
when(kubeClient.secrets()).thenReturn(secretsMixedOperation);
when(secretsMixedOperation.inNamespace(eq(meta.getName()))).thenReturn(nonNamespaceOperation);
when(nonNamespaceOperation.withLabels(anyMap())).thenReturn(filterWatchDeletable);
when(filterWatchDeletable.list()).thenReturn(secretList);
when(secretList.getItems()).thenReturn(emptyList());
ArgumentCaptor<Secret> captor = ArgumentCaptor.forClass(Secret.class);
PersonalAccessToken token = new PersonalAccessToken("https://bitbucket.com", "cheUser", "username", "userId", "oauth2-token-name", "tid-23434", "token123");
// when
kubernetesGitCredentialManager.createOrReplace(token);
// then
verify(nonNamespaceOperation).createOrReplace(captor.capture());
Secret createdSecret = captor.getValue();
assertNotNull(createdSecret);
assertEquals(new String(Base64.getDecoder().decode(createdSecret.getData().get("credentials"))), "https://oauth2:token123@bitbucket.com");
assertTrue(createdSecret.getMetadata().getName().startsWith(NAME_PATTERN));
assertFalse(createdSecret.getMetadata().getName().contains(token.getScmUserName()));
}
use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project che-server by eclipse-che.
the class GitlabOAuthTokenFetcherTest method shouldReturnToken.
@Test
public void shouldReturnToken() throws Exception {
Subject subject = new SubjectImpl("Username", "id1", "token", false);
OAuthToken oAuthToken = newDto(OAuthToken.class).withToken("oauthtoken").withScope("api write_repository openid");
when(oAuthAPI.getToken(anyString())).thenReturn(oAuthToken);
stubFor(get(urlEqualTo("/oauth/token/info")).withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer oauthtoken")).willReturn(aResponse().withHeader("Content-Type", "application/json; charset=utf-8").withBodyFile("gitlab/rest/api/v4/user/token_info.json")));
stubFor(get(urlEqualTo("/api/v4/user")).withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer oauthtoken")).willReturn(aResponse().withHeader("Content-Type", "application/json; charset=utf-8").withBodyFile("gitlab/rest/api/v4/user/response.json")));
PersonalAccessToken token = oAuthTokenFetcher.fetchPersonalAccessToken(subject, wireMockServer.url("/"));
assertNotNull(token);
}
use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project che-server by eclipse-che.
the class GithubPersonalAccessTokenFetcher method fetchPersonalAccessToken.
@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
OAuthToken oAuthToken;
if (githubApiClient == null || !githubApiClient.isConnected(scmServerUrl)) {
LOG.debug("not a valid url {} for current fetcher ", scmServerUrl);
return null;
}
try {
oAuthToken = oAuthAPI.getToken(OAUTH_PROVIDER_NAME);
// Find the user associated to the OAuth token by querying the GitHub API.
GithubUser user = githubApiClient.getUser(oAuthToken.getToken());
PersonalAccessToken token = new PersonalAccessToken(scmServerUrl, cheSubject.getUserId(), user.getLogin(), Long.toString(user.getId()), NameGenerator.generate(OAUTH_2_PREFIX, 5), NameGenerator.generate("id-", 5), oAuthToken.getToken());
Optional<Boolean> valid = isValid(token);
if (valid.isEmpty()) {
throw new ScmCommunicationException("Unable to verify if current token is a valid GitHub token. Token's scm-url needs to be '" + GithubApiClient.GITHUB_SERVER + "' and was '" + token.getScmProviderUrl() + "'");
} else if (!valid.get()) {
throw new ScmCommunicationException("Current token doesn't have the necessary privileges. Please make sure Che app scopes are correct and containing at least: " + DEFAULT_TOKEN_SCOPES.toString());
}
return token;
} catch (UnauthorizedException e) {
throw new ScmUnauthorizedException(cheSubject.getUserName() + " is not authorized in " + OAUTH_PROVIDER_NAME + " OAuth provider.", OAUTH_PROVIDER_NAME, "2.0", getLocalAuthenticateUrl());
} catch (NotFoundException | ServerException | ForbiddenException | BadRequestException | ScmItemNotFoundException | ScmBadRequestException | ConflictException e) {
LOG.error(e.getMessage());
throw new ScmCommunicationException(e.getMessage(), e);
}
}
use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project che-server by eclipse-che.
the class GitlabOAuthTokenFetcher method fetchPersonalAccessToken.
@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
scmServerUrl = StringUtils.trimEnd(scmServerUrl, '/');
GitlabApiClient gitlabApiClient = getApiClient(scmServerUrl);
if (gitlabApiClient == null || !gitlabApiClient.isConnected(scmServerUrl)) {
LOG.debug("not a valid url {} for current fetcher ", scmServerUrl);
return null;
}
if (oAuthAPI == null) {
throw new ScmCommunicationException(format("OAuth 2 is not configured for SCM provider [%s]. For details, refer " + "the documentation in section of SCM providers configuration.", OAUTH_PROVIDER_NAME));
}
OAuthToken oAuthToken;
try {
oAuthToken = oAuthAPI.getToken(OAUTH_PROVIDER_NAME);
GitlabUser user = gitlabApiClient.getUser(oAuthToken.getToken());
PersonalAccessToken token = new PersonalAccessToken(scmServerUrl, cheSubject.getUserId(), user.getUsername(), Long.toString(user.getId()), NameGenerator.generate(OAUTH_2_PREFIX, 5), NameGenerator.generate("id-", 5), oAuthToken.getToken());
Optional<Boolean> valid = isValid(token);
if (valid.isEmpty() || !valid.get()) {
throw new ScmCommunicationException("Current token doesn't have the necessary privileges. Please make sure Che app scopes are correct and containing at least: " + DEFAULT_TOKEN_SCOPES.toString());
}
return token;
} catch (UnauthorizedException e) {
throw new ScmUnauthorizedException(cheSubject.getUserName() + " is not authorized in " + OAUTH_PROVIDER_NAME + " OAuth provider.", OAUTH_PROVIDER_NAME, "2.0", getLocalAuthenticateUrl());
} catch (NotFoundException | ServerException | ForbiddenException | BadRequestException | ScmItemNotFoundException | ScmBadRequestException | ConflictException e) {
LOG.warn(e.getMessage());
throw new ScmCommunicationException(e.getMessage(), e);
}
}
Aggregations