-
Notifications
You must be signed in to change notification settings - Fork 70
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
Add Azure DevOps Server support #754
Open
vinokurig
wants to merge
2
commits into
main
Choose a base branch
from
che-23306
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,652
−309
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
281 changes: 281 additions & 0 deletions
281
...nfrastructure/kubernetes/namespace/configurator/GitconfigAutomauntSecretConfigurator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,281 @@ | ||
/* | ||
* Copyright (c) 2012-2025 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/ | ||
* | ||
* SPDX-License-Identifier: EPL-2.0 | ||
* | ||
* Contributors: | ||
* Red Hat, Inc. - initial API and implementation | ||
*/ | ||
package org.eclipse.che.workspace.infrastructure.kubernetes.namespace.configurator; | ||
|
||
import static com.google.common.base.Strings.isNullOrEmpty; | ||
import static java.nio.charset.StandardCharsets.UTF_8; | ||
import static org.eclipse.che.commons.lang.StringUtils.trimEnd; | ||
|
||
import com.google.common.collect.ImmutableMap; | ||
import io.fabric8.kubernetes.api.model.Secret; | ||
import io.fabric8.kubernetes.api.model.SecretBuilder; | ||
import io.fabric8.kubernetes.client.KubernetesClient; | ||
import java.util.Base64; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
import java.util.Set; | ||
import java.util.StringJoiner; | ||
import java.util.regex.Matcher; | ||
import java.util.regex.Pattern; | ||
import javax.inject.Inject; | ||
import org.eclipse.che.api.factory.server.scm.GitUserData; | ||
import org.eclipse.che.api.factory.server.scm.GitUserDataFetcher; | ||
import org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException; | ||
import org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException; | ||
import org.eclipse.che.api.factory.server.scm.exception.ScmConfigurationPersistenceException; | ||
import org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException; | ||
import org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException; | ||
import org.eclipse.che.api.workspace.server.spi.InfrastructureException; | ||
import org.eclipse.che.api.workspace.server.spi.NamespaceResolutionContext; | ||
import org.eclipse.che.commons.lang.Pair; | ||
import org.eclipse.che.workspace.infrastructure.kubernetes.CheServerKubernetesClientFactory; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
public class GitconfigAutomauntSecretConfigurator implements NamespaceConfigurator { | ||
private final CheServerKubernetesClientFactory cheServerKubernetesClientFactory; | ||
private final Set<GitUserDataFetcher> gitUserDataFetchers; | ||
private static final Logger LOG = | ||
LoggerFactory.getLogger(GitconfigAutomauntSecretConfigurator.class); | ||
private static final String CONFIGMAP_DATA_KEY = "gitconfig"; | ||
private static final String GITCONFIG_SECRET_NAME = "devworkspace-gitconfig-automaunt-secret"; | ||
private static final Map<String, String> TOKEN_SECRET_LABELS = | ||
ImmutableMap.of( | ||
"app.kubernetes.io/part-of", "che.eclipse.org", | ||
"app.kubernetes.io/component", "scm-personal-access-token"); | ||
private static final Map<String, String> GITCONFIG_SECRET_LABELS = | ||
ImmutableMap.of( | ||
"controller.devfile.io/mount-to-devworkspace", | ||
"true", | ||
"controller.devfile.io/watch-secret", | ||
"true"); | ||
private static final Map<String, String> GITCONFIG_SECRET_ANNOTATIONS = | ||
ImmutableMap.of( | ||
"controller.devfile.io/mount-as", "subpath", "controller.devfile.io/mount-path", "/etc"); | ||
private final Pattern usernmaePattern = | ||
Pattern.compile("\\[user](.|\\s)*name\\s*=\\s*(?<username>.*)"); | ||
private final Pattern emailPattern = | ||
Pattern.compile("\\[user](.|\\s)*email\\s*=\\s*(?<email>.*)"); | ||
Check failure Code scanning / CodeQL Inefficient regular expression
This part of the regular expression may cause exponential backtracking on strings starting with '\[user\]' and containing many repetitions of ' '.
|
||
private final Pattern emptyStringPattern = Pattern.compile("[\"']\\s*[\"']"); | ||
private final Pattern gitconfigSectionPattern = | ||
Pattern.compile("\\[(?<sectionName>[a-zA-Z0-9]+)](\\n\\s*\\S*\\s*=.*)*"); | ||
|
||
@Inject | ||
public GitconfigAutomauntSecretConfigurator( | ||
CheServerKubernetesClientFactory cheServerKubernetesClientFactory, | ||
Set<GitUserDataFetcher> gitUserDataFetchers) { | ||
this.cheServerKubernetesClientFactory = cheServerKubernetesClientFactory; | ||
this.gitUserDataFetchers = gitUserDataFetchers; | ||
} | ||
|
||
@Override | ||
public void configure(NamespaceResolutionContext namespaceResolutionContext, String namespaceName) | ||
throws InfrastructureException { | ||
KubernetesClient client = cheServerKubernetesClientFactory.create(); | ||
Optional<String> gitconfigOptional = getGitconfig(client, namespaceName); | ||
Optional<Pair<String, String>> usernameAndEmailFromGitconfigOptional = Optional.empty(); | ||
Optional<Pair<String, String>> usernameAndEmailFromFetcherOptional = | ||
getUsernameAndEmailFromFetcher(); | ||
Optional<String> tokenFromGitconfigOptional = Optional.empty(); | ||
Optional<String> tokenFromSecretOptional = getTokenFromSecret(client, namespaceName); | ||
if (gitconfigOptional.isPresent()) { | ||
String gitconfig = gitconfigOptional.get(); | ||
usernameAndEmailFromGitconfigOptional = getUsernameAndEmailFromGitconfig(gitconfig); | ||
tokenFromGitconfigOptional = getTokenFromGitconfig(gitconfig); | ||
} | ||
if (needUpdateGitconfigSecret( | ||
usernameAndEmailFromGitconfigOptional, | ||
usernameAndEmailFromFetcherOptional, | ||
tokenFromGitconfigOptional, | ||
tokenFromSecretOptional)) { | ||
Secret gitconfigSecret = buildGitconfigSecret(); | ||
Optional<Pair<String, String>> usernameAndEmailOptional = | ||
usernameAndEmailFromGitconfigOptional.isPresent() | ||
? usernameAndEmailFromGitconfigOptional | ||
: usernameAndEmailFromFetcherOptional; | ||
Optional<String> gitconfigSectionsOptional = | ||
generateGitconfigSections( | ||
gitconfigOptional, usernameAndEmailOptional, tokenFromSecretOptional); | ||
gitconfigSecret.setData( | ||
ImmutableMap.of( | ||
CONFIGMAP_DATA_KEY, | ||
gitconfigSectionsOptional.isPresent() | ||
? encode(gitconfigSectionsOptional.get()) | ||
: "")); | ||
client.secrets().inNamespace(namespaceName).createOrReplace(gitconfigSecret); | ||
} | ||
} | ||
|
||
private Secret buildGitconfigSecret() { | ||
return new SecretBuilder() | ||
.withNewMetadata() | ||
.withName(GITCONFIG_SECRET_NAME) | ||
.withLabels(GITCONFIG_SECRET_LABELS) | ||
.withAnnotations(GITCONFIG_SECRET_ANNOTATIONS) | ||
.endMetadata() | ||
.build(); | ||
} | ||
|
||
private boolean needUpdateGitconfigSecret( | ||
Optional<Pair<String, String>> usernameAndEmailFromGitconfigOptional, | ||
Optional<Pair<String, String>> usernameAndEmailFromFetcher, | ||
Optional<String> tokenFromGitconfigOptional, | ||
Optional<String> tokenFromSecretOptional) { | ||
if (tokenFromGitconfigOptional.isPresent() && tokenFromSecretOptional.isPresent()) { | ||
return !tokenFromGitconfigOptional.get().equals(tokenFromSecretOptional.get()); | ||
} else | ||
return (tokenFromSecretOptional.isPresent() || tokenFromGitconfigOptional.isPresent()) | ||
|| (usernameAndEmailFromGitconfigOptional.isEmpty() | ||
&& usernameAndEmailFromFetcher.isPresent()); | ||
} | ||
|
||
private Optional<String> generateGitconfigSections( | ||
Optional<String> gitconfigOptional, | ||
Optional<Pair<String, String>> usernameAndEmailOptional, | ||
Optional<String> tokenOptional) { | ||
Optional<String> userSectionOptional = Optional.empty(); | ||
Optional<String> httpSectionOPtional = Optional.empty(); | ||
if (usernameAndEmailOptional.isPresent()) { | ||
userSectionOptional = | ||
Optional.of( | ||
generateUserSection( | ||
usernameAndEmailOptional.get().first, usernameAndEmailOptional.get().second)); | ||
} | ||
if (tokenOptional.isPresent()) { | ||
httpSectionOPtional = Optional.of(generateHttpSection(tokenOptional.get())); | ||
} | ||
StringJoiner joiner = new StringJoiner("\n"); | ||
if (gitconfigOptional.isPresent()) { | ||
Optional<String> otherSectionsOptional = getOtherStoredSections(gitconfigOptional.get()); | ||
otherSectionsOptional.ifPresent(joiner::add); | ||
} | ||
userSectionOptional.ifPresent(joiner::add); | ||
httpSectionOPtional.ifPresent(joiner::add); | ||
return joiner.length() > 0 ? Optional.of(joiner.toString()) : Optional.empty(); | ||
} | ||
|
||
Optional<String> getOtherStoredSections(String gitconfig) { | ||
StringJoiner joiner = new StringJoiner("\n"); | ||
Matcher matcher = gitconfigSectionPattern.matcher(gitconfig); | ||
while (matcher.find()) { | ||
String sectionName = matcher.group("sectionName"); | ||
if (!sectionName.equals("user") && !sectionName.equals("http")) { | ||
joiner.add(matcher.group()); | ||
} | ||
} | ||
return joiner.length() > 0 ? Optional.of(joiner.toString()) : Optional.empty(); | ||
} | ||
|
||
private Optional<Pair<String, String>> getUsernameAndEmailFromGitconfig(String gitconfig) { | ||
if (gitconfig.contains("[user]")) { | ||
Matcher usernameMatcher = usernmaePattern.matcher(gitconfig); | ||
Matcher emailaMatcher = emailPattern.matcher(gitconfig); | ||
if (usernameMatcher.find() && emailaMatcher.find()) { | ||
String username = usernameMatcher.group("username"); | ||
String email = emailaMatcher.group("email"); | ||
if (!emptyStringPattern.matcher(username).matches() | ||
&& !emptyStringPattern.matcher(email).matches()) { | ||
return Optional.of(new Pair<>(username, email)); | ||
} | ||
} | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
private Optional<Pair<String, String>> getUsernameAndEmailFromFetcher() { | ||
GitUserData gitUserData; | ||
for (GitUserDataFetcher fetcher : gitUserDataFetchers) { | ||
try { | ||
gitUserData = fetcher.fetchGitUserData(); | ||
if (!isNullOrEmpty(gitUserData.getScmUsername()) | ||
&& !isNullOrEmpty(gitUserData.getScmUserEmail())) { | ||
return Optional.of( | ||
new Pair<>(gitUserData.getScmUsername(), gitUserData.getScmUserEmail())); | ||
} | ||
} catch (ScmUnauthorizedException | ||
| ScmCommunicationException | ||
| ScmConfigurationPersistenceException | ||
| ScmItemNotFoundException | ||
| ScmBadRequestException e) { | ||
LOG.debug("No GitUserDataFetcher is configured. " + e.getMessage()); | ||
} | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
private Optional<String> getTokenFromSecret(KubernetesClient client, String namespaceName) { | ||
for (Secret tokenSecret : | ||
client | ||
.secrets() | ||
.inNamespace(namespaceName) | ||
.withLabels(TOKEN_SECRET_LABELS) | ||
.list() | ||
.getItems()) { | ||
if ("azure-devops" | ||
.equals( | ||
tokenSecret | ||
.getMetadata() | ||
.getAnnotations() | ||
.get("che.eclipse.org/scm-provider-name")) | ||
&& !"https://dev.azure.com" | ||
.equals( | ||
trimEnd( | ||
tokenSecret.getMetadata().getAnnotations().get("che.eclipse.org/scm-url"), | ||
'/'))) { | ||
return Optional.of(decode(tokenSecret.getData().get("token"))); | ||
} | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
private Optional<String> getTokenFromGitconfig(String gitconfig) { | ||
if (gitconfig.contains("[http]")) { | ||
Matcher matcher = | ||
Pattern.compile( | ||
"\\[http]\\n\\s*extra[hH]eader\\s*=\\s*[\"']?Authorization: Basic (?<tokenEncoded>.*)[\"']?") | ||
.matcher(gitconfig); | ||
if (matcher.find()) { | ||
// remove the first character which is ':' from the token value | ||
return Optional.of(decode(matcher.group("tokenEncoded")).substring(1)); | ||
} | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
private String generateHttpSection(String token) { | ||
return "[http]\n\textraHeader = Authorization: Basic " + encode(":" + token); | ||
} | ||
|
||
private String generateUserSection(String username, String email) { | ||
return String.format("[user]\n\tname = %1$s\n\temail = %2$s", username, email); | ||
} | ||
|
||
private Optional<String> getGitconfig(KubernetesClient client, String namespaceName) { | ||
Secret gitconfigAutomauntSecret = | ||
client.secrets().inNamespace(namespaceName).withName(GITCONFIG_SECRET_NAME).get(); | ||
if (gitconfigAutomauntSecret != null) { | ||
String gitconfig = gitconfigAutomauntSecret.getData().get(CONFIGMAP_DATA_KEY); | ||
if (!isNullOrEmpty(gitconfig)) { | ||
return Optional.of(decode(gitconfig)); | ||
} | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
private String encode(String value) { | ||
return Base64.getEncoder().encodeToString(value.getBytes(UTF_8)); | ||
} | ||
|
||
private String decode(String value) { | ||
return new String(Base64.getDecoder().decode(value.getBytes(UTF_8))); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Inefficient regular expression