repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/BranchesList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class BranchesList {
@SerializedName("values")
private List<Branch> branches;
public BranchesList() {
// http://stackoverflow.com/a/18645370/229031
this(new ArrayList<>());
}
public BranchesList(List<Branch> values) {
this.branches = values;
}
public Optional<Branch> findDefaultBranch() {
return branches.stream().filter(Branch::isDefault).findFirst();
}
public void addBranch(Branch branch) {
this.branches.add(branch);
}
public List<Branch> getBranches() {
return branches;
}
}
| 1,563 | 27.962963 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/Project.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
public class Project {
@SerializedName("key")
private String key;
@SerializedName("name")
private String name;
@SerializedName("id")
private long id;
public Project() {
// http://stackoverflow.com/a/18645370/229031
}
public Project(String key, String name, long id) {
this.key = key;
this.name = name;
this.id = id;
}
public String getKey() {
return key;
}
public Project setKey(String key) {
this.key = key;
return this;
}
public String getName() {
return name;
}
public Project setName(String name) {
this.name = name;
return this;
}
public long getId() {
return id;
}
public Project setId(long id) {
this.id = id;
return this;
}
@Override
public String toString() {
return "{" +
"key='" + key + '\'' +
", name='" + name + '\'' +
", id=" + id +
'}';
}
}
| 1,840 | 21.728395 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/ProjectList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class ProjectList {
@SerializedName("values")
private List<Project> values;
public ProjectList() {
// http://stackoverflow.com/a/18645370/229031
this(new ArrayList<>());
}
public ProjectList(List<Project> values) {
this.values = values;
}
public List<Project> getValues() {
return values;
}
public ProjectList setValues(List<Project> values) {
this.values = values;
return this;
}
@Override
public String toString() {
return "{" +
"values=" + values +
'}';
}
}
| 1,533 | 26.392857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/Repository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
public class Repository {
@SerializedName("slug")
private String slug;
@SerializedName("name")
private String name;
@SerializedName("id")
private long id;
@SerializedName("project")
private Project project;
public Repository() {
// http://stackoverflow.com/a/18645370/229031
}
public Repository(String slug, String name, long id, Project project) {
this.slug = slug;
this.name = name;
this.id = id;
this.project = project;
}
public String getSlug() {
return slug;
}
public Repository setSlug(String slug) {
this.slug = slug;
return this;
}
public String getName() {
return name;
}
public Repository setName(String name) {
this.name = name;
return this;
}
public long getId() {
return id;
}
public Repository setId(long id) {
this.id = id;
return this;
}
public Project getProject() {
return project;
}
public Repository setProject(Project project) {
this.project = project;
return this;
}
@Override
public String toString() {
return "{" +
"slug='" + slug + '\'' +
", name='" + name + '\'' +
", id=" + id +
", project=" + project +
'}';
}
}
| 2,161 | 21.757895 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/RepositoryList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class RepositoryList {
@SerializedName("isLastPage")
private boolean isLastPage;
@SerializedName("values")
private List<Repository> values;
public RepositoryList() {
// http://stackoverflow.com/a/18645370/229031
this(false, new ArrayList<>());
}
public RepositoryList(boolean isLastPage, List<Repository> values) {
this.isLastPage = isLastPage;
this.values = values;
}
static RepositoryList parse(String json) {
return new Gson().fromJson(json, RepositoryList.class);
}
public boolean isLastPage() {
return isLastPage;
}
public RepositoryList setLastPage(boolean lastPage) {
isLastPage = lastPage;
return this;
}
public List<Repository> getValues() {
return values;
}
public RepositoryList setValues(List<Repository> values) {
this.values = values;
return this;
}
@Override
public String toString() {
return "{" +
"isLastPage=" + isLastPage +
", values=" + values +
'}';
}
}
| 2,022 | 25.973333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/User.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
public class User {
@SerializedName("name")
private String name;
@SerializedName("slug")
private String slug;
@SerializedName("id")
private long id;
public User() {
// http://stackoverflow.com/a/18645370/229031
}
}
| 1,182 | 28.575 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/UserList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class UserList {
@SerializedName("isLastPage")
private final boolean isLastPage;
@SerializedName("values")
private final List<User> values;
public UserList() {
// http://stackoverflow.com/a/18645370/229031
this(false, new ArrayList<>());
}
public UserList(boolean isLastPage, List<User> values) {
this.isLastPage = isLastPage;
this.values = values;
}
}
| 1,390 | 29.911111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.bitbucketserver;
import javax.annotation.ParametersAreNonnullByDefault;
| 976 | 39.708333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/GithubApplicationClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.alm.client.github.config.GithubAppConfiguration;
import org.sonar.alm.client.github.config.GithubAppInstallation;
import org.sonar.alm.client.github.security.AccessToken;
import org.sonar.alm.client.github.security.UserAccessToken;
import org.sonar.api.server.ServerSide;
@ServerSide
public interface GithubApplicationClient {
/**
* Create a user access token for the enterprise app installation.
*
* See https://developer.github.com/enterprise/2.20/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#identifying-users-on-your-site
*
* @throws IllegalStateException if an internal error occured: network issue, invalid response, etc
* @throws IllegalArgumentException if the request failed due to one of the parameters being invalid.
*/
UserAccessToken createUserAccessToken(String appUrl, String clientId, String clientSecret, String code);
GithubBinding.GsonApp getApp(GithubAppConfiguration githubAppConfiguration);
/**
* Lists all the organizations accessible to the access token provided.
*/
Organizations listOrganizations(String appUrl, AccessToken accessToken, int page, int pageSize);
/**
* Retrieve all installations of the GitHub app, filtering out the ones not whitelisted in GitHub Settings (if set)
* @throws IllegalArgumentException if one of the arguments is invalid (for example, wrong private key)
*/
List<GithubAppInstallation> getWhitelistedGithubAppInstallations(GithubAppConfiguration githubAppConfiguration);
/**
* Lists all the repositories of the provided organization accessible to the access token provided.
*/
Repositories listRepositories(String appUrl, AccessToken accessToken, String organization, @Nullable String query, int page, int pageSize);
void checkApiEndpoint(GithubAppConfiguration githubAppConfiguration);
/**
* Checks if an app has all the permissions required.
*/
void checkAppPermissions(GithubAppConfiguration githubAppConfiguration);
/**
* Returns the repository identified by the repositoryKey owned by the provided organization.
*/
Optional<Repository> getRepository(String appUrl, AccessToken accessToken, String organization, String repositoryKey);
class Repositories {
private int total;
private List<Repository> repositories;
public Repositories() {
//nothing to do
}
public int getTotal() {
return total;
}
public Repositories setTotal(int total) {
this.total = total;
return this;
}
@CheckForNull
public List<Repository> getRepositories() {
return repositories;
}
public Repositories setRepositories(List<Repository> repositories) {
this.repositories = repositories;
return this;
}
}
@Immutable
final class Repository {
private final long id;
private final String name;
private final boolean isPrivate;
private final String fullName;
private final String url;
private final String defaultBranch;
public Repository(long id, String name, boolean isPrivate, String fullName, String url, String defaultBranch) {
this.id = id;
this.name = name;
this.isPrivate = isPrivate;
this.fullName = fullName;
this.url = url;
this.defaultBranch = defaultBranch;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public boolean isPrivate() {
return isPrivate;
}
public String getFullName() {
return fullName;
}
public String getUrl() {
return url;
}
public String getDefaultBranch() {
return defaultBranch;
}
@Override
public String toString() {
return "Repository{" +
"id=" + id +
", name='" + name + '\'' +
", isPrivate='" + isPrivate + '\'' +
", fullName='" + fullName + '\'' +
", url='" + url + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Repository that = (Repository) o;
return id == that.id;
}
@Override
public int hashCode() {
return Long.hashCode(id);
}
}
class Organizations {
private int total;
private List<Organization> organizations;
public Organizations() {
//nothing to do
}
public int getTotal() {
return total;
}
public Organizations setTotal(int total) {
this.total = total;
return this;
}
@CheckForNull
public List<Organization> getOrganizations() {
return organizations;
}
public Organizations setOrganizations(List<Organization> organizations) {
this.organizations = organizations;
return this;
}
}
class Organization {
private final long id;
private final String login;
private final String name;
private final String bio;
private final String blog;
@SerializedName("html_url")
private final String htmlUrl;
@SerializedName("avatar_url")
private final String avatarUrl;
private final String type;
public Organization(long id, String login, @Nullable String name, @Nullable String bio, @Nullable String blog, @Nullable String htmlUrl, @Nullable String avatarUrl,
String type) {
this.id = id;
this.login = login;
this.name = name;
this.bio = bio;
this.blog = blog;
this.htmlUrl = htmlUrl;
this.avatarUrl = avatarUrl;
this.type = type;
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
@CheckForNull
public String getName() {
return name;
}
@CheckForNull
public String getBio() {
return bio;
}
@CheckForNull
public String getBlog() {
return blog;
}
public String getHtmlUrl() {
return htmlUrl;
}
@CheckForNull
public String getAvatarUrl() {
return avatarUrl;
}
public String getType() {
return type;
}
}
}
| 7,235 | 26.203008 | 168 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/GithubApplicationClientImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.alm.client.github.GithubApplicationHttpClient.GetResponse;
import org.sonar.alm.client.github.GithubBinding.GsonGithubRepository;
import org.sonar.alm.client.github.GithubBinding.GsonInstallations;
import org.sonar.alm.client.github.GithubBinding.GsonRepositorySearch;
import org.sonar.alm.client.github.config.GithubAppConfiguration;
import org.sonar.alm.client.github.config.GithubAppInstallation;
import org.sonar.alm.client.github.security.AccessToken;
import org.sonar.alm.client.github.security.AppToken;
import org.sonar.alm.client.github.security.GithubAppSecurity;
import org.sonar.alm.client.github.security.UserAccessToken;
import org.sonar.alm.client.gitlab.GsonApp;
import org.sonar.api.internal.apachecommons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.auth.github.GitHubSettings;
import org.sonar.server.exceptions.ServerException;
import org.sonarqube.ws.client.HttpException;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
public class GithubApplicationClientImpl implements GithubApplicationClient {
private static final Logger LOG = LoggerFactory.getLogger(GithubApplicationClientImpl.class);
protected static final Gson GSON = new Gson();
protected static final String WRITE_PERMISSION_NAME = "write";
protected static final String READ_PERMISSION_NAME = "read";
protected static final String FAILED_TO_REQUEST_BEGIN_MSG = "Failed to request ";
protected final GithubApplicationHttpClient appHttpClient;
protected final GithubAppSecurity appSecurity;
private final GitHubSettings gitHubSettings;
public GithubApplicationClientImpl(GithubApplicationHttpClient appHttpClient, GithubAppSecurity appSecurity, GitHubSettings gitHubSettings) {
this.appHttpClient = appHttpClient;
this.appSecurity = appSecurity;
this.gitHubSettings = gitHubSettings;
}
private static void checkPageArgs(int page, int pageSize) {
checkArgument(page > 0, "'page' must be larger than 0.");
checkArgument(pageSize > 0 && pageSize <= 100, "'pageSize' must be a value larger than 0 and smaller or equal to 100.");
}
@Override
public void checkApiEndpoint(GithubAppConfiguration githubAppConfiguration) {
if (StringUtils.isBlank(githubAppConfiguration.getApiEndpoint())) {
throw new IllegalArgumentException("Missing URL");
}
URI apiEndpoint;
try {
apiEndpoint = URI.create(githubAppConfiguration.getApiEndpoint());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid URL, " + e.getMessage());
}
if (!"http".equalsIgnoreCase(apiEndpoint.getScheme()) && !"https".equalsIgnoreCase(apiEndpoint.getScheme())) {
throw new IllegalArgumentException("Only http and https schemes are supported");
} else if (!"api.github.com".equalsIgnoreCase(apiEndpoint.getHost()) && !apiEndpoint.getPath().toLowerCase(Locale.ENGLISH).startsWith("/api/v3")) {
throw new IllegalArgumentException("Invalid GitHub URL");
}
}
@Override
public void checkAppPermissions(GithubAppConfiguration githubAppConfiguration) {
AppToken appToken = appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey());
Map<String, String> permissions = new HashMap<>();
permissions.put("checks", WRITE_PERMISSION_NAME);
permissions.put("pull_requests", WRITE_PERMISSION_NAME);
permissions.put("metadata", READ_PERMISSION_NAME);
String endPoint = "/app";
GetResponse response;
try {
response = appHttpClient.get(githubAppConfiguration.getApiEndpoint(), appToken, endPoint);
} catch (IOException e) {
LOG.warn(FAILED_TO_REQUEST_BEGIN_MSG + githubAppConfiguration.getApiEndpoint() + endPoint, e);
throw new IllegalArgumentException("Failed to validate configuration, check URL and Private Key");
}
if (response.getCode() == HTTP_OK) {
Map<String, String> perms = handleResponse(response, endPoint, GsonApp.class)
.map(GsonApp::getPermissions)
.orElseThrow(() -> new IllegalArgumentException("Failed to get app permissions, unexpected response body"));
List<String> missingPermissions = permissions.entrySet().stream()
.filter(permission -> !Objects.equals(permission.getValue(), perms.get(permission.getKey())))
.map(Map.Entry::getKey)
.toList();
if (!missingPermissions.isEmpty()) {
String message = missingPermissions.stream()
.map(perm -> perm + " is '" + perms.get(perm) + "', should be '" + permissions.get(perm) + "'")
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("Missing permissions; permission granted on " + message);
}
} else if (response.getCode() == HTTP_UNAUTHORIZED || response.getCode() == HTTP_FORBIDDEN) {
throw new IllegalArgumentException("Authentication failed, verify the Client Id, Client Secret and Private Key fields");
} else {
throw new IllegalArgumentException("Failed to check permissions with Github, check the configuration");
}
}
@Override
public Organizations listOrganizations(String appUrl, AccessToken accessToken, int page, int pageSize) {
checkPageArgs(page, pageSize);
try {
Organizations organizations = new Organizations();
GetResponse response = appHttpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", page, pageSize));
Optional<GsonInstallations> gsonInstallations = response.getContent().map(content -> GSON.fromJson(content, GsonInstallations.class));
if (!gsonInstallations.isPresent()) {
return organizations;
}
organizations.setTotal(gsonInstallations.get().totalCount);
if (gsonInstallations.get().installations != null) {
organizations.setOrganizations(gsonInstallations.get().installations.stream()
.map(gsonInstallation -> new Organization(gsonInstallation.account.id, gsonInstallation.account.login, null, null, null, null, null,
gsonInstallation.targetType))
.toList());
}
return organizations;
} catch (IOException e) {
throw new IllegalStateException(format("Failed to list all organizations accessible by user access token on %s", appUrl), e);
}
}
@Override
public List<GithubAppInstallation> getWhitelistedGithubAppInstallations(GithubAppConfiguration githubAppConfiguration) {
GithubBinding.GsonInstallation[] gsonAppInstallations = fetchAppInstallationsFromGithub(githubAppConfiguration);
Set<String> allowedOrganizations = gitHubSettings.getOrganizations();
return convertToGithubAppInstallationAndFilterWhitelisted(gsonAppInstallations, allowedOrganizations);
}
private static List<GithubAppInstallation> convertToGithubAppInstallationAndFilterWhitelisted(GithubBinding.GsonInstallation[] gsonAppInstallations,
Set<String> allowedOrganizations) {
return Arrays.stream(gsonAppInstallations)
.filter(appInstallation -> appInstallation.getAccount().getType().equalsIgnoreCase("Organization"))
.map(GithubApplicationClientImpl::toGithubAppInstallation)
.filter(appInstallation -> isOrganizationWhiteListed(allowedOrganizations, appInstallation.organizationName()))
.toList();
}
private static GithubAppInstallation toGithubAppInstallation(GithubBinding.GsonInstallation gsonInstallation) {
return new GithubAppInstallation(
Long.toString(gsonInstallation.getId()),
gsonInstallation.getAccount().getLogin(),
gsonInstallation.getPermissions(),
org.apache.commons.lang.StringUtils.isNotEmpty(gsonInstallation.getSuspendedAt()));
}
private static boolean isOrganizationWhiteListed(Set<String> allowedOrganizations, String organizationName) {
return allowedOrganizations.isEmpty() || allowedOrganizations.contains(organizationName);
}
private GithubBinding.GsonInstallation[] fetchAppInstallationsFromGithub(GithubAppConfiguration githubAppConfiguration) {
AppToken appToken = appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey());
String endpoint = "/app/installations";
return get(githubAppConfiguration.getApiEndpoint(), appToken, endpoint,
GithubBinding.GsonInstallation[].class).orElseThrow(
() -> new IllegalStateException("An error occurred when retrieving your GitHup App installations. "
+ "It might be related to your GitHub App configuration or a connectivity problem."));
}
protected <T> Optional<T> get(String baseUrl, AccessToken token, String endPoint, Class<T> gsonClass) {
try {
GetResponse response = appHttpClient.get(baseUrl, token, endPoint);
return handleResponse(response, endPoint, gsonClass);
} catch (Exception e) {
LOG.warn(FAILED_TO_REQUEST_BEGIN_MSG + endPoint, e);
return Optional.empty();
}
}
@Override
public Repositories listRepositories(String appUrl, AccessToken accessToken, String organization, @Nullable String query, int page, int pageSize) {
checkPageArgs(page, pageSize);
String searchQuery = "fork:true+org:" + organization;
if (query != null) {
searchQuery = query.replace(" ", "+") + "+" + searchQuery;
}
try {
Repositories repositories = new Repositories();
GetResponse response = appHttpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", searchQuery, page, pageSize));
Optional<GsonRepositorySearch> gsonRepositories = response.getContent().map(content -> GSON.fromJson(content, GsonRepositorySearch.class));
if (!gsonRepositories.isPresent()) {
return repositories;
}
repositories.setTotal(gsonRepositories.get().totalCount);
if (gsonRepositories.get().items != null) {
repositories.setRepositories(gsonRepositories.get().items.stream()
.map(GsonGithubRepository::toRepository)
.toList());
}
return repositories;
} catch (Exception e) {
throw new IllegalStateException(format("Failed to list all repositories of '%s' accessible by user access token on '%s' using query '%s'", organization, appUrl, searchQuery),
e);
}
}
@Override
public Optional<Repository> getRepository(String appUrl, AccessToken accessToken, String organization, String repositoryKey) {
try {
GetResponse response = appHttpClient.get(appUrl, accessToken, String.format("/repos/%s", repositoryKey));
return response.getContent()
.map(content -> GSON.fromJson(content, GsonGithubRepository.class))
.map(GsonGithubRepository::toRepository);
} catch (Exception e) {
throw new IllegalStateException(format("Failed to get repository '%s' of '%s' accessible by user access token on '%s'", repositoryKey, organization, appUrl), e);
}
}
@Override
public UserAccessToken createUserAccessToken(String appUrl, String clientId, String clientSecret, String code) {
try {
String endpoint = "/login/oauth/access_token?client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + code;
String baseAppUrl;
int apiIndex = appUrl.indexOf("/api/v3");
if (apiIndex > 0) {
baseAppUrl = appUrl.substring(0, apiIndex);
} else if (appUrl.startsWith("https://api.github.com")) {
baseAppUrl = "https://github.com";
} else {
baseAppUrl = appUrl;
}
GithubApplicationHttpClient.Response response = appHttpClient.post(baseAppUrl, null, endpoint);
if (response.getCode() != HTTP_OK) {
throw new IllegalStateException("Failed to create GitHub's user access token. GitHub returned code " + code + ". " + response.getContent().orElse(""));
}
Optional<String> content = response.getContent();
Optional<UserAccessToken> accessToken = content.flatMap(c -> Arrays.stream(c.split("&"))
.filter(t -> t.startsWith("access_token="))
.map(t -> t.split("=")[1])
.findAny())
.map(UserAccessToken::new);
if (accessToken.isPresent()) {
return accessToken.get();
}
// If token is not in the 200's body, it's because the client ID or client secret are incorrect
LOG.error("Failed to create GitHub's user access token. GitHub's response: " + content);
throw new IllegalArgumentException();
} catch (IOException e) {
throw new IllegalStateException("Failed to create GitHub's user access token", e);
}
}
@Override
public GithubBinding.GsonApp getApp(GithubAppConfiguration githubAppConfiguration) {
AppToken appToken = appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey());
String endpoint = "/app";
return getOrThrowIfNotHttpOk(githubAppConfiguration.getApiEndpoint(), appToken, endpoint, GithubBinding.GsonApp.class);
}
private <T> T getOrThrowIfNotHttpOk(String baseUrl, AccessToken token, String endPoint, Class<T> gsonClass) {
try {
GetResponse response = appHttpClient.get(baseUrl, token, endPoint);
if (response.getCode() != HTTP_OK) {
throw new HttpException(baseUrl + endPoint, response.getCode(), response.getContent().orElse(""));
}
return handleResponse(response, endPoint, gsonClass).orElseThrow(() -> new ServerException(HTTP_INTERNAL_ERROR, "Http response withuot content"));
} catch (IOException e) {
throw new ServerException(HTTP_INTERNAL_ERROR, e.getMessage());
}
}
protected static <T> Optional<T> handleResponse(GithubApplicationHttpClient.Response response, String endPoint, Class<T> gsonClass) {
try {
return response.getContent().map(c -> GSON.fromJson(c, gsonClass));
} catch (Exception e) {
LOG.warn(FAILED_TO_REQUEST_BEGIN_MSG + endPoint, e);
return Optional.empty();
}
}
}
| 15,363 | 45.699088 | 180 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/GithubApplicationHttpClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import java.io.IOException;
import java.util.Optional;
import org.sonar.alm.client.github.security.AccessToken;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
@ServerSide
@ComputeEngineSide
public interface GithubApplicationHttpClient {
/**
* Content of the response is populated if response's HTTP code is {@link java.net.HttpURLConnection#HTTP_OK OK}.
*/
GetResponse get(String appUrl, AccessToken token, String endPoint) throws IOException;
/**
* Content of the response is populated if response's HTTP code is {@link java.net.HttpURLConnection#HTTP_OK OK}.
* No log if there is an issue during the call.
*/
GetResponse getSilent(String appUrl, AccessToken token, String endPoint) throws IOException;
/**
* Content of the response is populated if response's HTTP code is {@link java.net.HttpURLConnection#HTTP_OK OK} or
* {@link java.net.HttpURLConnection#HTTP_CREATED CREATED}.
*/
Response post(String appUrl, AccessToken token, String endPoint) throws IOException;
/**
* Content of the response is populated if response's HTTP code is {@link java.net.HttpURLConnection#HTTP_OK OK} or
* {@link java.net.HttpURLConnection#HTTP_CREATED CREATED}.
*
* Content type will be application/json; charset=utf-8
*/
Response post(String appUrl, AccessToken token, String endPoint, String json) throws IOException;
/**
* Content of the response is populated if response's HTTP code is {@link java.net.HttpURLConnection#HTTP_OK OK}.
*
* Content type will be application/json; charset=utf-8
*/
Response patch(String appUrl, AccessToken token, String endPoint, String json) throws IOException;
/**
* Content of the response is populated if response's HTTP code is {@link java.net.HttpURLConnection#HTTP_OK OK}.
*
* Content type will be application/json; charset=utf-8
*
*/
Response delete(String appUrl, AccessToken token, String endPoint) throws IOException;
interface Response {
/**
* @return the HTTP code of the response.
*/
int getCode();
/**
* @return the content of the response if the response had an HTTP code for which we expect a content for the current
* HTTP method (see {@link #get(String, AccessToken, String)} and {@link #post(String, AccessToken, String)}).
*/
Optional<String> getContent();
}
interface GetResponse extends Response {
Optional<String> getNextEndPoint();
}
}
| 3,357 | 37.159091 | 122 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/GithubApplicationHttpClientImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.apache.commons.lang.StringUtils;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.alm.client.github.security.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static com.google.common.base.Preconditions.checkArgument;
import static java.net.HttpURLConnection.HTTP_ACCEPTED;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
public class GithubApplicationHttpClientImpl implements GithubApplicationHttpClient {
private static final Logger LOG = LoggerFactory.getLogger(GithubApplicationHttpClientImpl.class);
private static final Pattern NEXT_LINK_PATTERN = Pattern.compile("<([^<]+)>; rel=\"next\"");
private static final String GH_API_VERSION_HEADER = "X-GitHub-Api-Version";
private static final String GH_API_VERSION = "2022-11-28";
private final OkHttpClient client;
public GithubApplicationHttpClientImpl(TimeoutConfiguration timeoutConfiguration) {
client = new OkHttpClientBuilder()
.setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
.setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
.setFollowRedirects(false)
.build();
}
@Override
public GetResponse get(String appUrl, AccessToken token, String endPoint) throws IOException {
return get(appUrl, token, endPoint, true);
}
@Override
public GetResponse getSilent(String appUrl, AccessToken token, String endPoint) throws IOException {
return get(appUrl, token, endPoint, false);
}
private GetResponse get(String appUrl, AccessToken token, String endPoint, boolean withLog) throws IOException {
validateEndPoint(endPoint);
try (okhttp3.Response response = client.newCall(newGetRequest(appUrl, token, endPoint)).execute()) {
int responseCode = response.code();
if (responseCode != HTTP_OK) {
String content = StringUtils.trimToNull(attemptReadContent(response));
if (withLog) {
LOG.warn("GET response did not have expected HTTP code (was {}): {}", responseCode, content);
}
return new GetResponseImpl(responseCode, content, null);
}
return new GetResponseImpl(responseCode, readContent(response.body()).orElse(null), readNextEndPoint(response));
}
}
private static void validateEndPoint(String endPoint) {
checkArgument(endPoint.startsWith("/") || endPoint.startsWith("http") || endPoint.isEmpty(),
"endpoint must start with '/' or 'http'");
}
private static Request newGetRequest(String appUrl, AccessToken token, String endPoint) {
return newRequestBuilder(appUrl, token, endPoint).get().build();
}
@Override
public Response post(String appUrl, AccessToken token, String endPoint) throws IOException {
return doPost(appUrl, token, endPoint, new FormBody.Builder().build());
}
@Override
public Response post(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
return doPost(appUrl, token, endPoint, body);
}
@Override
public Response patch(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
return doPatch(appUrl, token, endPoint, body);
}
@Override
public Response delete(String appUrl, AccessToken token, String endPoint) throws IOException {
validateEndPoint(endPoint);
try (okhttp3.Response response = client.newCall(newDeleteRequest(appUrl, token, endPoint)).execute()) {
int responseCode = response.code();
if (responseCode != HTTP_NO_CONTENT) {
String content = attemptReadContent(response);
LOG.warn("DELETE response did not have expected HTTP code (was {}): {}", responseCode, content);
return new ResponseImpl(responseCode, content);
}
return new ResponseImpl(responseCode, null);
}
}
private static Request newDeleteRequest(String appUrl, AccessToken token, String endPoint) {
return newRequestBuilder(appUrl, token, endPoint).delete().build();
}
private Response doPost(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) throws IOException {
validateEndPoint(endPoint);
try (okhttp3.Response response = client.newCall(newPostRequest(appUrl, token, endPoint, body)).execute()) {
int responseCode = response.code();
if (responseCode == HTTP_OK || responseCode == HTTP_CREATED || responseCode == HTTP_ACCEPTED) {
return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
} else if (responseCode == HTTP_NO_CONTENT) {
return new ResponseImpl(responseCode, null);
}
String content = attemptReadContent(response);
LOG.warn("POST response did not have expected HTTP code (was {}): {}", responseCode, content);
return new ResponseImpl(responseCode, content);
}
}
private Response doPatch(String appUrl, AccessToken token, String endPoint, RequestBody body) throws IOException {
validateEndPoint(endPoint);
try (okhttp3.Response response = client.newCall(newPatchRequest(token, appUrl, endPoint, body)).execute()) {
int responseCode = response.code();
if (responseCode == HTTP_OK) {
return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
} else if (responseCode == HTTP_NO_CONTENT) {
return new ResponseImpl(responseCode, null);
}
String content = attemptReadContent(response);
LOG.warn("PATCH response did not have expected HTTP code (was {}): {}", responseCode, content);
return new ResponseImpl(responseCode, content);
}
}
private static Request newPostRequest(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) {
return newRequestBuilder(appUrl, token, endPoint).post(body).build();
}
private static Request newPatchRequest(AccessToken token, String appUrl, String endPoint, RequestBody body) {
return newRequestBuilder(appUrl, token, endPoint).patch(body).build();
}
private static Request.Builder newRequestBuilder(String appUrl, @Nullable AccessToken token, String endPoint) {
Request.Builder url = new Request.Builder().url(toAbsoluteEndPoint(appUrl, endPoint));
if (token != null) {
url.addHeader("Authorization", token.getAuthorizationHeaderPrefix() + " " + token);
url.addHeader(GH_API_VERSION_HEADER, GH_API_VERSION);
}
return url;
}
private static String toAbsoluteEndPoint(String host, String endPoint) {
if (endPoint.startsWith("http")) {
return endPoint;
}
try {
return new URL(host + endPoint).toExternalForm();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(String.format("%s is not a valid url", host + endPoint));
}
}
private static String attemptReadContent(okhttp3.Response response) {
try {
return readContent(response.body()).orElse(null);
} catch (IOException e) {
return null;
}
}
private static Optional<String> readContent(@Nullable ResponseBody body) throws IOException {
if (body == null) {
return empty();
}
try {
return of(body.string());
} finally {
body.close();
}
}
@CheckForNull
private static String readNextEndPoint(okhttp3.Response response) {
String links = response.headers().get("link");
if (links == null || links.isEmpty() || !links.contains("rel=\"next\"")) {
return null;
}
Matcher nextLinkMatcher = NEXT_LINK_PATTERN.matcher(links);
if (!nextLinkMatcher.find()) {
return null;
}
return nextLinkMatcher.group(1);
}
private static class ResponseImpl implements Response {
private final int code;
private final String content;
private ResponseImpl(int code, @Nullable String content) {
this.code = code;
this.content = content;
}
@Override
public int getCode() {
return code;
}
@Override
public Optional<String> getContent() {
return ofNullable(content);
}
}
private static final class GetResponseImpl extends ResponseImpl implements GetResponse {
private final String nextEndPoint;
private GetResponseImpl(int code, @Nullable String content, @Nullable String nextEndPoint) {
super(code, content);
this.nextEndPoint = nextEndPoint;
}
@Override
public Optional<String> getNextEndPoint() {
return ofNullable(nextEndPoint);
}
}
}
| 10,159 | 36.910448 | 125 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/GithubBinding.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static org.sonar.alm.client.github.GithubApplicationClient.Repository;
public class GithubBinding {
private GithubBinding() {
// nothing to do
}
public static class GsonApp {
@SerializedName("installations_count")
private long installationsCount;
@SerializedName("permissions")
Permissions permissions;
public GsonApp(long installationsCount, Permissions permissions) {
this.installationsCount = installationsCount;
this.permissions = permissions;
}
public GsonApp() {
// http://stackoverflow.com/a/18645370/229031
}
public Permissions getPermissions() {
return permissions;
}
public long getInstallationsCount() {
return installationsCount;
}
}
public static class GsonInstallations {
@SerializedName("total_count")
int totalCount;
@SerializedName("installations")
List<GsonInstallation> installations;
public GsonInstallations() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
}
public static class GsonInstallation {
@SerializedName("id")
long id;
@SerializedName("target_type")
String targetType;
@SerializedName("permissions")
Permissions permissions;
@SerializedName("account")
GsonAccount account;
@SerializedName("suspended_at")
String suspendedAt;
public GsonInstallation(long id, String targetType, Permissions permissions, GsonAccount account, String suspendedAt) {
this.id = id;
this.targetType = targetType;
this.permissions = permissions;
this.account = account;
this.suspendedAt = suspendedAt;
}
public GsonInstallation() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public long getId() {
return id;
}
public String getTargetType() {
return targetType;
}
public Permissions getPermissions() {
return permissions;
}
public GsonAccount getAccount() {
return account;
}
public String getSuspendedAt() {
return suspendedAt;
}
public static class GsonAccount {
@SerializedName("id")
long id;
@SerializedName("login")
String login;
@SerializedName("type")
String type;
public GsonAccount() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public String getLogin() {
return login;
}
public String getType() {
return type;
}
}
}
public static class Permissions {
@SerializedName("checks")
String checks;
@SerializedName("members")
String members;
@SerializedName("emails")
String emails;
@SerializedName("contents")
String contents;
public Permissions(@Nullable String checks, @Nullable String members, @Nullable String emails, @Nullable String contents) {
this.checks = checks;
this.members = members;
this.emails = emails;
this.contents = contents;
}
public Permissions() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
@CheckForNull
public String getMembers() {
return members;
}
@CheckForNull
public String getChecks() {
return checks;
}
@CheckForNull
public String getEmails() {
return emails;
}
@CheckForNull
public String getContents() {
return contents;
}
}
public static class GsonRepositorySearch {
@SerializedName("total_count")
int totalCount;
@SerializedName("items")
List<GsonGithubRepository> items;
public GsonRepositorySearch() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
}
public static class GsonGithubRepository {
@SerializedName("id")
long id;
@SerializedName("name")
String name;
@SerializedName("full_name")
String fullName;
@SerializedName("private")
boolean isPrivate;
@SerializedName("html_url")
String htmlUrl;
@SerializedName("default_branch")
String defaultBranch;
public GsonGithubRepository() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public Repository toRepository() {
return new Repository(this.id, this.name, this.isPrivate, this.fullName,
this.htmlUrl, this.defaultBranch);
}
}
public static class GsonGithubCodeScanningAlert {
@SerializedName("number")
long id;
@SerializedName("state")
GithubCodeScanningAlertState state;
@SerializedName("dismissed_reason")
String dismissedReason;
@SerializedName("dismissed_comment")
String dismissedComment;
@SerializedName("tool")
GsonGithubCodeScanningAlertTool tool;
@SerializedName("most_recent_instance")
GsonGithubCodeScanningAlertInstance mostRecentInstance;
public GsonGithubCodeScanningAlert() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public long getId() {
return id;
}
public GithubCodeScanningAlertState getState() {
return state;
}
public String getDismissedReason() {
return dismissedReason;
}
public String getDismissedComment() {
return dismissedComment;
}
public GsonGithubCodeScanningAlertTool getTool() {
return tool;
}
public GsonGithubCodeScanningAlertInstance getMostRecentInstance() {
return mostRecentInstance;
}
public String getMessageText() {
return getMostRecentInstance().getMessageText();
}
}
public static class GsonGithubCodeScanningAlertWebhookPayload {
@SerializedName("action")
String action;
@SerializedName("alert")
GsonGithubCodeScanningAlert alert;
@SerializedName("sender")
GsonGithubCodeScanningAlertWebhookPayloadSender sender;
public GsonGithubCodeScanningAlertWebhookPayload() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public String getAction() {
return action;
}
public GsonGithubCodeScanningAlert getAlert() {
return alert;
}
public GsonGithubCodeScanningAlertWebhookPayloadSender getSender() {
return sender;
}
}
public static class GsonGithubCodeScanningAlertInstance {
@SerializedName("state")
GithubCodeScanningAlertState state;
@SerializedName("message")
GsonGithubCodeScanningAlertMessage message;
public GsonGithubCodeScanningAlertInstance() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public GsonGithubCodeScanningAlertMessage getMessage() {
return message;
}
public String getMessageText() {
return getMessage().getText();
}
}
public enum GithubCodeScanningAlertState {
@SerializedName("open")
OPEN,
@SerializedName("fixed")
FIXED,
@SerializedName("dismissed")
DISMISSED
}
public static class GsonGithubCodeScanningAlertMessage {
@SerializedName("text")
String text;
public GsonGithubCodeScanningAlertMessage() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public String getText() {
return text;
}
}
public static class GsonGithubCodeScanningAlertWebhookPayloadSender {
@SerializedName("login")
String login;
public GsonGithubCodeScanningAlertWebhookPayloadSender() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public String getLogin() {
return login;
}
}
public static class GsonGithubCodeScanningAlertTool {
@SerializedName("name")
String name;
public GsonGithubCodeScanningAlertTool() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public String getName() {
return name;
}
}
}
| 9,779 | 24.873016 | 127 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/GithubGlobalSettingsValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import java.util.Optional;
import org.sonar.alm.client.github.config.GithubAppConfiguration;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.server.ServerSide;
import org.sonar.db.alm.setting.AlmSettingDto;
import static org.apache.commons.lang.StringUtils.isBlank;
@ServerSide
public class GithubGlobalSettingsValidator {
private final Encryption encryption;
private final GithubApplicationClient githubApplicationClient;
public GithubGlobalSettingsValidator(GithubApplicationClientImpl githubApplicationClient, Settings settings) {
this.encryption = settings.getEncryption();
this.githubApplicationClient = githubApplicationClient;
}
public GithubAppConfiguration validate(AlmSettingDto settings) {
long appId;
try {
appId = Long.parseLong(Optional.ofNullable(settings.getAppId()).orElseThrow(() -> new IllegalArgumentException("Missing appId")));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid appId; " + e.getMessage());
}
if (isBlank(settings.getClientId())) {
throw new IllegalArgumentException("Missing Client Id");
}
if (isBlank(settings.getDecryptedClientSecret(encryption))) {
throw new IllegalArgumentException("Missing Client Secret");
}
GithubAppConfiguration configuration = new GithubAppConfiguration(appId, settings.getDecryptedPrivateKey(encryption),
settings.getUrl());
githubApplicationClient.checkApiEndpoint(configuration);
githubApplicationClient.checkAppPermissions(configuration);
return configuration;
}
}
| 2,519 | 38.375 | 136 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/SonarQubeIssueKeyFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import java.util.Optional;
import static org.apache.commons.lang.StringUtils.substringBetween;
public final class SonarQubeIssueKeyFormatter {
static final String SONAR_ISSUE_KEY_PREFIX = "<!--SONAR_ISSUE_KEY:";
static final String SONAR_ISSUE_KEY_SUFFIX = "-->";
private SonarQubeIssueKeyFormatter() {
}
public static String serialize(String key) {
return SONAR_ISSUE_KEY_PREFIX + key + SONAR_ISSUE_KEY_SUFFIX;
}
public static Optional<String> deserialize(String messageText) {
return Optional.ofNullable(substringBetween(messageText, SONAR_ISSUE_KEY_PREFIX, SONAR_ISSUE_KEY_SUFFIX));
}
}
| 1,501 | 34.761905 | 110 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.github;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/config/ConfigCheckResult.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.config;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import javax.annotation.Nullable;
public record ConfigCheckResult(@SerializedName("application") ApplicationStatus application, @SerializedName("installations") List<InstallationStatus> installations) {
public record ConfigStatus(@SerializedName("status") String status, @Nullable @SerializedName("errorMessage") String errorMessage) {
public static final String SUCCESS_STATUS = "SUCCESS";
public static final String FAILED_STATUS = "FAILED";
public static final ConfigStatus SUCCESS = new ConfigStatus(SUCCESS_STATUS);
public ConfigStatus(String status) {
this(status, null);
}
public static ConfigStatus failed(String errorMessage) {
return new ConfigStatus(FAILED_STATUS, errorMessage);
}
}
public record ApplicationStatus(@SerializedName("jit") ConfigStatus jit, @SerializedName("autoProvisioning") ConfigStatus autoProvisioning) {
}
public record InstallationStatus(@SerializedName("organization") String organization, @SerializedName("jit") ConfigStatus jit,
@SerializedName("autoProvisioning") ConfigStatus autoProvisioning) {
}
}
| 2,066 | 38.75 | 168 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/config/GithubAppConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.config;
import com.google.common.base.MoreObjects;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static java.lang.String.format;
public class GithubAppConfiguration {
private static final Pattern TRAILING_SLASHES = Pattern.compile("/+$");
private final Long id;
private final String privateKey;
private final String apiEndpoint;
public GithubAppConfiguration(@Nullable Long id, @Nullable String privateKey, @Nullable String apiEndpoint) {
this.id = id;
this.privateKey = privateKey;
this.apiEndpoint = sanitizedEndPoint(apiEndpoint);
}
/**
* Check configuration is complete with {@link #isComplete()} before calling this method.
*
* @throws IllegalStateException if configuration is not complete
*/
public long getId() {
checkConfigurationComplete();
return id;
}
public String getApiEndpoint() {
checkConfigurationComplete();
return apiEndpoint;
}
/**
* Check configuration is complete with {@link #isComplete()} before calling this method.
*
* @throws IllegalStateException if configuration is not complete
*/
public String getPrivateKey() {
checkConfigurationComplete();
return privateKey;
}
private void checkConfigurationComplete() {
if (!isComplete()) {
throw new IllegalStateException(format("Configuration is not complete : %s", toString()));
}
}
public boolean isComplete() {
return id != null &&
privateKey != null &&
apiEndpoint != null;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(GithubAppConfiguration.class)
.add("id", id)
.add("privateKey", secureToString(privateKey))
.add("apiEndpoint", toString(apiEndpoint))
.toString();
}
@CheckForNull
private static String toString(@Nullable String s) {
if (s == null) {
return null;
}
return '\'' + s + '\'';
}
@CheckForNull
private static String secureToString(@Nullable String token) {
if (token == null) {
return null;
}
return "'***(" + token.length() + ")***'";
}
private static String sanitizedEndPoint(@Nullable String endPoint) {
if (endPoint == null) {
return null;
}
return TRAILING_SLASHES.matcher(endPoint).replaceAll("");
}
}
| 3,215 | 27.460177 | 111 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/config/GithubAppInstallation.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.config;
import org.sonar.alm.client.github.GithubBinding;
public record GithubAppInstallation(String installationId, String organizationName, GithubBinding.Permissions permissions, boolean isSuspended) {}
| 1,086 | 42.48 | 146 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/config/GithubProvisioningConfigValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.sonar.alm.client.github.GithubApplicationClient;
import org.sonar.alm.client.github.GithubBinding.Permissions;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import org.sonar.auth.github.GitHubSettings;
import org.sonarqube.ws.client.HttpException;
import static java.lang.Long.parseLong;
import static org.sonar.alm.client.github.GithubBinding.GsonApp;
import static org.sonar.alm.client.github.config.ConfigCheckResult.ApplicationStatus;
import static org.sonar.alm.client.github.config.ConfigCheckResult.ConfigStatus;
import static org.sonar.alm.client.github.config.ConfigCheckResult.InstallationStatus;
@ServerSide
@ComputeEngineSide
public class GithubProvisioningConfigValidator {
private static final String MEMBERS_PERMISSION = "Organization permissions -> Members";
private static final String EMAILS_PERMISSION = "Account permissions -> Email addresses";
private static final ConfigStatus INVALID_APP_CONFIG_STATUS = ConfigStatus.failed("The GitHub App configuration is not complete.");
private static final ConfigStatus INVALID_APP_ID_STATUS = ConfigStatus.failed("GitHub App ID must be a number.");
private static final ConfigStatus SUSPENDED_INSTALLATION_STATUS = ConfigStatus.failed("Installation suspended");
private static final ConfigStatus NO_INSTALLATION_FOUND_STATUS = ConfigStatus.failed(
"The GitHub App is not installed on any organizations or the organization is not white-listed.");
private static final ConfigCheckResult NO_INSTALLATIONS_RESULT = new ConfigCheckResult(
new ApplicationStatus(
NO_INSTALLATION_FOUND_STATUS,
NO_INSTALLATION_FOUND_STATUS),
List.of());
private final GithubApplicationClient githubClient;
private final GitHubSettings gitHubSettings;
public GithubProvisioningConfigValidator(GithubApplicationClient githubClient, GitHubSettings gitHubSettings) {
this.githubClient = githubClient;
this.gitHubSettings = gitHubSettings;
}
public ConfigCheckResult checkConfig() {
Optional<Long> appId = getAppId();
if (appId.isEmpty()) {
return failedApplicationStatus(INVALID_APP_ID_STATUS);
}
GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDefault());
return checkConfig(githubAppConfiguration);
}
private Optional<Long> getAppId() {
try {
return Optional.of(parseLong(gitHubSettings.appId()));
} catch (NumberFormatException numberFormatException) {
return Optional.empty();
}
}
public ConfigCheckResult checkConfig(GithubAppConfiguration githubAppConfiguration) {
if (!githubAppConfiguration.isComplete()) {
return failedApplicationStatus(INVALID_APP_CONFIG_STATUS);
}
try {
GsonApp app = githubClient.getApp(githubAppConfiguration);
return checkNonEmptyConfig(githubAppConfiguration, app);
} catch (HttpException e) {
return failedApplicationStatus(
ConfigStatus.failed("Error response from GitHub: " + e.getMessage()));
} catch (IllegalArgumentException e) {
return failedApplicationStatus(
ConfigStatus.failed(e.getMessage()));
}
}
private static ConfigCheckResult failedApplicationStatus(ConfigStatus configStatus) {
return new ConfigCheckResult(new ApplicationStatus(configStatus, configStatus), List.of());
}
private ConfigCheckResult checkNonEmptyConfig(GithubAppConfiguration githubAppConfiguration, GsonApp app) {
ApplicationStatus appStatus = checkNonEmptyAppConfig(app);
List<InstallationStatus> installations = checkInstallations(githubAppConfiguration, appStatus);
if (installations.isEmpty()) {
return NO_INSTALLATIONS_RESULT;
}
return new ConfigCheckResult(
appStatus,
installations);
}
private static ApplicationStatus checkNonEmptyAppConfig(GsonApp app) {
return new ApplicationStatus(
jitAppConfigStatus(app.getPermissions()),
autoProvisioningAppConfigStatus(app.getPermissions()));
}
private static ConfigStatus jitAppConfigStatus(Permissions permissions) {
if (permissions.getEmails() == null) {
return failedStatus(List.of(EMAILS_PERMISSION));
}
return ConfigStatus.SUCCESS;
}
private static ConfigStatus autoProvisioningAppConfigStatus(Permissions permissions) {
List<String> missingPermissions = new ArrayList<>();
if (permissions.getEmails() == null) {
missingPermissions.add(EMAILS_PERMISSION);
}
if (permissions.getMembers() == null) {
missingPermissions.add(MEMBERS_PERMISSION);
}
if (missingPermissions.isEmpty()) {
return ConfigStatus.SUCCESS;
}
return failedStatus(missingPermissions);
}
private static ConfigStatus failedStatus(List<String> missingPermissions) {
return ConfigStatus.failed("Missing permissions: " + String.join(",", missingPermissions));
}
private List<InstallationStatus> checkInstallations(GithubAppConfiguration githubAppConfiguration, ApplicationStatus appStatus) {
return githubClient.getWhitelistedGithubAppInstallations(githubAppConfiguration)
.stream()
.map(installation -> statusForInstallation(installation, appStatus))
.toList();
}
private static InstallationStatus statusForInstallation(GithubAppInstallation installation, ApplicationStatus appStatus) {
if (installation.isSuspended()) {
return new InstallationStatus(installation.organizationName(), SUSPENDED_INSTALLATION_STATUS, SUSPENDED_INSTALLATION_STATUS);
}
return new InstallationStatus(
installation.organizationName(),
appStatus.jit(),
autoProvisioningInstallationConfigStatus(installation.permissions()));
}
private static ConfigStatus autoProvisioningInstallationConfigStatus(Permissions permissions) {
if (permissions.getMembers() == null) {
return failedStatus(List.of(MEMBERS_PERMISSION));
}
return ConfigStatus.SUCCESS;
}
}
| 6,945 | 40.345238 | 155 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/config/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.github.config;
import javax.annotation.ParametersAreNonnullByDefault;
| 974 | 39.625 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/scanning/alert/GithubScanningAlertState.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.scanning.alert;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nullable;
public class GithubScanningAlertState {
@SerializedName("state")
private final String state;
@SerializedName("dismissed_reason")
private final String dismissedReason;
public GithubScanningAlertState(String state, @Nullable String dismissedReason) {
this.state = state;
this.dismissedReason = dismissedReason;
}
}
| 1,316 | 35.583333 | 83 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/scanning/alert/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.github.scanning.alert;
import javax.annotation.ParametersAreNonnullByDefault;
| 982 | 39.958333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/security/AccessToken.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
/**
* Token used to authenticate requests to Github API
*
*/
public interface AccessToken {
String getValue();
/**
* Value of the HTTP header "Authorization"
*/
String getAuthorizationHeaderPrefix();
}
| 1,110 | 29.861111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/security/AppToken.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
/**
* JWT (Json Web Token) to authenticate API requests on behalf
* of the Github App.
*
* Token expires after {@link #EXPIRATION_PERIOD_IN_MINUTES} minutes.
*
* IMPORTANT
* Rate limit is 5'000 API requests per hour for ALL the clients
* of the Github App (all instances of {@link AppToken} from Compute Engines/web servers
* and from the other SonarSource services using the App). For example three calls with
* three different tokens will consume 3 hits. Remaining quota will be 4'997.
* When the token is expired, the rate limit is 60 calls per hour for the public IP
* of the machine. BE CAREFUL, THAT SHOULD NEVER OCCUR.
*
* See https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app
*/
@Immutable
public class AppToken implements AccessToken {
// maximum allowed by GitHub is 10 minutes but we use 9 minutes just in case clocks are not synchronized
static final int EXPIRATION_PERIOD_IN_MINUTES = 9;
private final String jwt;
public AppToken(String jwt) {
this.jwt = requireNonNull(jwt, "jwt can't be null");
}
@Override
public String getValue() {
return jwt;
}
@Override
public String getAuthorizationHeaderPrefix() {
return "Bearer";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AppToken appToken = (AppToken) o;
return jwt.equals(appToken.jwt);
}
@Override
public int hashCode() {
return jwt.hashCode();
}
@Override
public String toString() {
return jwt;
}
}
| 2,633 | 29.627907 | 125 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/security/GithubAppSecurity.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
@ServerSide
@ComputeEngineSide
public interface GithubAppSecurity {
/**
* @throws IllegalArgumentException if the key is invalid
*/
AppToken createAppToken(long appId, String privateKey);
}
| 1,174 | 34.606061 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/security/GithubAppSecurityImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.RSAKeyProvider;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import static java.nio.charset.StandardCharsets.UTF_8;
public class GithubAppSecurityImpl implements GithubAppSecurity {
private final Clock clock;
public GithubAppSecurityImpl(Clock clock) {
this.clock = clock;
}
@Override
public AppToken createAppToken(long appId, String privateKey) {
Algorithm algorithm = readApplicationPrivateKey(appId, privateKey);
LocalDateTime now = LocalDateTime.now(clock);
// Expiration period is configurable and could be greater if needed.
// See https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app
LocalDateTime expiresAt = now.plus(AppToken.EXPIRATION_PERIOD_IN_MINUTES, ChronoUnit.MINUTES);
ZoneOffset offset = clock.getZone().getRules().getOffset(now);
Date nowDate = Date.from(now.toInstant(offset));
Date expiresAtDate = Date.from(expiresAt.toInstant(offset));
JWTCreator.Builder builder = JWT.create()
.withIssuer(String.valueOf(appId))
.withIssuedAt(nowDate)
.withExpiresAt(expiresAtDate);
return new AppToken(builder.sign(algorithm));
}
private static Algorithm readApplicationPrivateKey(long appId, String encodedPrivateKey) {
byte[] decodedPrivateKey = encodedPrivateKey.getBytes(UTF_8);
try (PemReader pemReader = new PemReader(new InputStreamReader(new ByteArrayInputStream(decodedPrivateKey)))) {
Security.addProvider(new BouncyCastleProvider());
PemObject pemObject = pemReader.readPemObject();
if (pemObject == null) {
throw new IllegalArgumentException("Failed to decode Github Application private key");
}
PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(pemObject.getContent());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec1);
return Algorithm.RSA256(new RSAKeyProvider() {
@Override
public RSAPublicKey getPublicKeyById(String keyId) {
throw new UnsupportedOperationException("getPublicKeyById not implemented");
}
@Override
public RSAPrivateKey getPrivateKey() {
return (RSAPrivateKey) privateKey;
}
@Override
public String getPrivateKeyId() {
return "github_app_" + appId;
}
});
} catch (Exception e) {
throw new IllegalArgumentException("The Github App private key is not valid", e);
} finally {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
}
}
| 4,191 | 38.17757 | 129 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/security/UserAccessToken.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
public class UserAccessToken implements AccessToken {
private final String token;
public UserAccessToken(String token) {
this.token = token;
}
@Override
public String getValue() {
return token;
}
@Override
public String getAuthorizationHeaderPrefix() {
return "token";
}
@Override
public String toString() {
return getValue();
}
}
| 1,266 | 27.155556 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/github/security/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.github.security;
import javax.annotation.ParametersAreNonnullByDefault;
| 976 | 39.708333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GitLabBranch.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nullable;
public class GitLabBranch {
@SerializedName("name")
private final String name;
@SerializedName("default")
private final boolean isDefault;
public GitLabBranch() {
// http://stackoverflow.com/a/18645370/229031
this(null, false);
}
public GitLabBranch(@Nullable String name, boolean isDefault) {
this.name = name;
this.isDefault = isDefault;
}
public String getName() {
return name;
}
public boolean isDefault() {
return isDefault;
}
}
| 1,455 | 27.54902 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GitlabGlobalSettingsValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.server.ServerSide;
import org.sonar.db.alm.setting.AlmSettingDto;
@ServerSide
public class GitlabGlobalSettingsValidator {
private final Encryption encryption;
private final GitlabHttpClient gitlabHttpClient;
public GitlabGlobalSettingsValidator(GitlabHttpClient gitlabHttpClient, Settings settings) {
this.encryption = settings.getEncryption();
this.gitlabHttpClient = gitlabHttpClient;
}
public void validate(AlmSettingDto almSettingDto) {
String gitlabUrl = almSettingDto.getUrl();
String accessToken = almSettingDto.getDecryptedPersonalAccessToken(encryption);
if (gitlabUrl == null || accessToken == null) {
throw new IllegalArgumentException("Your Gitlab global configuration is incomplete.");
}
gitlabHttpClient.checkUrl(gitlabUrl);
gitlabHttpClient.checkToken(gitlabUrl, accessToken);
gitlabHttpClient.checkReadPermission(gitlabUrl, accessToken);
gitlabHttpClient.checkWritePermission(gitlabUrl, accessToken);
}
}
| 1,985 | 36.471698 | 94 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GitlabHttpClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.logging.log4j.util.Strings;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.api.server.ServerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.nio.charset.StandardCharsets.UTF_8;
@ServerSide
public class GitlabHttpClient {
private static final Logger LOG = LoggerFactory.getLogger(GitlabHttpClient.class);
protected static final String PRIVATE_TOKEN = "Private-Token";
protected final OkHttpClient client;
public GitlabHttpClient(TimeoutConfiguration timeoutConfiguration) {
client = new OkHttpClientBuilder()
.setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
.setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
.setFollowRedirects(false)
.build();
}
public void checkReadPermission(@Nullable String gitlabUrl, @Nullable String personalAccessToken) {
checkProjectAccess(gitlabUrl, personalAccessToken, "Could not validate GitLab read permission. Got an unexpected answer.");
}
public void checkUrl(@Nullable String gitlabUrl) {
checkProjectAccess(gitlabUrl, null, "Could not validate GitLab url. Got an unexpected answer.");
}
private void checkProjectAccess(@Nullable String gitlabUrl, @Nullable String personalAccessToken, String errorMessage) {
String url = String.format("%s/projects", gitlabUrl);
LOG.debug(String.format("get projects : [%s]", url));
Request.Builder builder = new Request.Builder()
.url(url)
.get();
if (personalAccessToken != null) {
builder.addHeader(PRIVATE_TOKEN, personalAccessToken);
}
Request request = builder.build();
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response, errorMessage);
Project.parseJsonArray(response.body().string());
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to verify read permission. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalArgumentException(errorMessage);
}
}
private static void logException(String url, IOException e) {
LOG.info(String.format("Gitlab API call to [%s] failed with error message : [%s]", url, e.getMessage()), e);
}
public void checkToken(String gitlabUrl, String personalAccessToken) {
String url = String.format("%s/user", gitlabUrl);
LOG.debug(String.format("get current user : [%s]", url));
Request.Builder builder = new Request.Builder()
.addHeader(PRIVATE_TOKEN, personalAccessToken)
.url(url)
.get();
Request request = builder.build();
String errorMessage = "Could not validate GitLab token. Got an unexpected answer.";
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response, errorMessage);
GsonId.parseOne(response.body().string());
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to verify token. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalArgumentException(errorMessage);
}
}
public void checkWritePermission(String gitlabUrl, String personalAccessToken) {
String url = String.format("%s/markdown", gitlabUrl);
LOG.debug(String.format("verify write permission by formating some markdown : [%s]", url));
Request.Builder builder = new Request.Builder()
.url(url)
.addHeader(PRIVATE_TOKEN, personalAccessToken)
.addHeader("Content-Type", MediaTypes.JSON)
.post(RequestBody.create("{\"text\":\"validating write permission\"}".getBytes(UTF_8)));
Request request = builder.build();
String errorMessage = "Could not validate GitLab write permission. Got an unexpected answer.";
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response, errorMessage);
GsonMarkdown.parseOne(response.body().string());
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to verify write permission. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalArgumentException(errorMessage);
}
}
private static String urlEncode(String value) {
try {
return URLEncoder.encode(value, UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new IllegalStateException(ex.getCause());
}
}
protected static void checkResponseIsSuccessful(Response response) throws IOException {
checkResponseIsSuccessful(response, "GitLab Merge Request did not happen, please check your configuration");
}
protected static void checkResponseIsSuccessful(Response response, String errorMessage) throws IOException {
if (!response.isSuccessful()) {
String body = response.body().string();
LOG.error(String.format("Gitlab API call to [%s] failed with %s http code. gitlab response content : [%s]", response.request().url().toString(), response.code(), body));
if (isTokenRevoked(response, body)) {
throw new GitlabServerException(response.code(), "Your GitLab token was revoked");
} else if (isTokenExpired(response, body)) {
throw new GitlabServerException(response.code(), "Your GitLab token is expired");
} else if (isInsufficientScope(response, body)) {
throw new GitlabServerException(response.code(), "Your GitLab token has insufficient scope");
} else if (response.code() == HTTP_UNAUTHORIZED) {
throw new GitlabServerException(response.code(), "Invalid personal access token");
} else if (response.isRedirect()) {
throw new GitlabServerException(response.code(), "Request was redirected, please provide the correct URL");
} else {
throw new GitlabServerException(response.code(), errorMessage);
}
}
}
private static boolean isTokenRevoked(Response response, String body) {
if (response.code() == HTTP_UNAUTHORIZED) {
try {
Optional<GsonError> gitlabError = GsonError.parseOne(body);
return gitlabError.map(GsonError::getErrorDescription).map(description -> description.contains("Token was revoked")).orElse(false);
} catch (JsonParseException e) {
// nothing to do
}
}
return false;
}
private static boolean isTokenExpired(Response response, String body) {
if (response.code() == HTTP_UNAUTHORIZED) {
try {
Optional<GsonError> gitlabError = GsonError.parseOne(body);
return gitlabError.map(GsonError::getErrorDescription).map(description -> description.contains("Token is expired")).orElse(false);
} catch (JsonParseException e) {
// nothing to do
}
}
return false;
}
private static boolean isInsufficientScope(Response response, String body) {
if (response.code() == HTTP_FORBIDDEN) {
try {
Optional<GsonError> gitlabError = GsonError.parseOne(body);
return gitlabError.map(GsonError::getError).map("insufficient_scope"::equals).orElse(false);
} catch (JsonParseException e) {
// nothing to do
}
}
return false;
}
public Project getProject(String gitlabUrl, String pat, Long gitlabProjectId) {
String url = String.format("%s/projects/%s", gitlabUrl, gitlabProjectId);
LOG.debug(String.format("get project : [%s]", url));
Request request = new Request.Builder()
.addHeader(PRIVATE_TOKEN, pat)
.get()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response);
String body = response.body().string();
LOG.trace(String.format("loading project payload result : [%s]", body));
return new GsonBuilder().create().fromJson(body, Project.class);
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to retrieve a project. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalStateException(e.getMessage(), e);
}
}
//
// This method is used to check if a user has REPORTER level access to the project, which is a requirement for PR decoration.
// As of June 9, 2021 there is no better way to do this check and still support GitLab 11.7.
//
public Optional<Project> getReporterLevelAccessProject(String gitlabUrl, String pat, Long gitlabProjectId) {
String url = String.format("%s/projects?min_access_level=20&id_after=%s&id_before=%s", gitlabUrl, gitlabProjectId - 1,
gitlabProjectId + 1);
LOG.debug(String.format("get project : [%s]", url));
Request request = new Request.Builder()
.addHeader(PRIVATE_TOKEN, pat)
.get()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response);
String body = response.body().string();
LOG.trace(String.format("loading project payload result : [%s]", body));
List<Project> projects = Project.parseJsonArray(body);
if (projects.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(projects.get(0));
}
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to retrieve a project. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalStateException(e.getMessage(), e);
}
}
public List<GitLabBranch> getBranches(String gitlabUrl, String pat, Long gitlabProjectId) {
String url = String.format("%s/projects/%s/repository/branches", gitlabUrl, gitlabProjectId);
LOG.debug(String.format("get branches : [%s]", url));
Request request = new Request.Builder()
.addHeader(PRIVATE_TOKEN, pat)
.get()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response);
String body = response.body().string();
LOG.trace(String.format("loading branches payload result : [%s]", body));
return Arrays.asList(new GsonBuilder().create().fromJson(body, GitLabBranch[].class));
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to retrieve project branches. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalStateException(e.getMessage(), e);
}
}
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName,
@Nullable Integer pageNumber, @Nullable Integer pageSize) {
String url = String.format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s",
gitlabUrl,
projectName == null ? "" : urlEncode(projectName),
pageNumber == null ? "" : String.format("&page=%d", pageNumber),
pageSize == null ? "" : String.format("&per_page=%d", pageSize)
);
LOG.debug(String.format("get projects : [%s]", url));
Request request = new Request.Builder()
.addHeader(PRIVATE_TOKEN, personalAccessToken)
.url(url)
.get()
.build();
try (Response response = client.newCall(request).execute()) {
Headers headers = response.headers();
checkResponseIsSuccessful(response, "Could not get projects from GitLab instance");
List<Project> projectList = Project.parseJsonArray(response.body().string());
int returnedPageNumber = parseAndGetIntegerHeader(headers.get("X-Page"));
int returnedPageSize = parseAndGetIntegerHeader(headers.get("X-Per-Page"));
String xtotal = headers.get("X-Total");
Integer totalProjects = Strings.isEmpty(xtotal) ? null : parseAndGetIntegerHeader(xtotal);
return new ProjectList(projectList, returnedPageNumber, returnedPageSize, totalProjects);
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to search projects. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalStateException(e.getMessage(), e);
}
}
private static int parseAndGetIntegerHeader(@Nullable String header) {
if (header == null) {
throw new IllegalArgumentException("Pagination data from GitLab response is missing");
} else {
try {
return Integer.parseInt(header);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Could not parse pagination number", e);
}
}
}
}
| 14,306 | 41.079412 | 175 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GitlabServerException.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
public class GitlabServerException extends IllegalArgumentException {
private final int httpStatus;
public GitlabServerException(int httpStatus, String clientErrorMessage) {
super(clientErrorMessage);
this.httpStatus = httpStatus;
}
public int getHttpStatus() {
return httpStatus;
}
}
| 1,191 | 33.057143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GsonApp.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
public class GsonApp {
@SerializedName("installations_count")
private long installationsCount;
@SerializedName("permissions")
private Map<String, String> permissions;
public GsonApp() {
// http://stackoverflow.com/a/18645370/229031
}
public GsonApp(long installationsCount, Map<String, String> permissions) {
this.installationsCount = installationsCount;
this.permissions = permissions;
}
public long getInstallationsCount() {
return installationsCount;
}
public Map<String, String> getPermissions() {
return permissions;
}
}
| 1,531 | 29.64 | 76 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GsonError.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import java.util.Optional;
public class GsonError {
@SerializedName("error")
private final String error;
@SerializedName("error_description")
private final String errorDescription;
@SerializedName("message")
private final String message;
public GsonError() {
this("", "", "");
}
public GsonError(String error, String errorDescription, String message) {
this.error = error;
this.errorDescription = errorDescription;
this.message = message;
}
public static Optional<GsonError> parseOne(String json) {
Gson gson = new Gson();
return Optional.ofNullable(gson.fromJson(json, GsonError.class));
}
public String getError() {
return error;
}
public String getErrorDescription() {
return errorDescription;
}
public String getMessage() {
return message;
}
}
| 1,790 | 27.428571 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GsonId.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class GsonId {
@SerializedName("id")
private final long id;
public GsonId() {
// http://stackoverflow.com/a/18645370/229031
this(0);
}
public GsonId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public static GsonId parseOne(String json) {
Gson gson = new Gson();
return gson.fromJson(json, GsonId.class);
}
}
| 1,345 | 26.469388 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/GsonMarkdown.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nullable;
public class GsonMarkdown {
@SerializedName("html")
private final String html;
public GsonMarkdown() {
// http://stackoverflow.com/a/18645370/229031
this(null);
}
public GsonMarkdown(@Nullable String html) {
this.html = html;
}
public static GsonMarkdown parseOne(String json) {
Gson gson = new Gson();
return gson.fromJson(json, GsonMarkdown.class);
}
}
| 1,392 | 29.282609 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/Project.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.util.LinkedList;
import java.util.List;
public class Project {
// https://docs.gitlab.com/ee/api/projects.html#get-single-project
// https://docs.gitlab.com/ee/api/projects.html#list-all-projects
@SerializedName("id")
private long id;
@SerializedName("name")
private final String name;
@SerializedName("name_with_namespace")
private String nameWithNamespace;
@SerializedName("path")
private String path;
@SerializedName("path_with_namespace")
private final String pathWithNamespace;
@SerializedName("web_url")
private String webUrl;
public Project(String name, String pathWithNamespace) {
this.name = name;
this.pathWithNamespace = pathWithNamespace;
}
public Project() {
// http://stackoverflow.com/a/18645370/229031
this(0, "", "", "", "", "");
}
public Project(long id, String name, String nameWithNamespace, String path, String pathWithNamespace,
String webUrl) {
this.id = id;
this.name = name;
this.nameWithNamespace = nameWithNamespace;
this.path = path;
this.pathWithNamespace = pathWithNamespace;
this.webUrl = webUrl;
}
public static Project parseJson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, Project.class);
}
public static List<Project> parseJsonArray(String json) {
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<LinkedList<Project>>() {
}.getType());
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getNameWithNamespace() {
return nameWithNamespace;
}
public String getPath() {
return path;
}
public String getPathWithNamespace() {
return pathWithNamespace;
}
public String getWebUrl() {
return webUrl;
}
}
| 2,802 | 25.443396 | 103 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/ProjectList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
public class ProjectList {
private final List<Project> projects;
private final int pageNumber;
private final int pageSize;
private final Integer total;
public ProjectList(List<Project> projects, int pageNumber, int pageSize, @Nullable Integer total) {
this.projects = projects;
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.total = total;
}
public List<Project> getProjects() {
return projects;
}
public int getPageNumber() {
return pageNumber;
}
public int getPageSize() {
return pageSize;
}
@CheckForNull
public Integer getTotal() {
return total;
}
}
| 1,613 | 27.315789 | 101 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/gitlab/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.gitlab;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/ConstantTimeoutConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client;
public class ConstantTimeoutConfiguration implements TimeoutConfiguration {
private final long timeout;
public ConstantTimeoutConfiguration(long timeout) {
this.timeout = timeout;
}
@Override
public long getConnectTimeout() {
return timeout;
}
@Override
public long getReadTimeout() {
return timeout;
}
}
| 1,212 | 30.102564 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/TimeoutConfigurationImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class TimeoutConfigurationImplTest {
private final MapSettings settings = new MapSettings();
private final TimeoutConfigurationImpl underTest = new TimeoutConfigurationImpl(settings.asConfig());
@Test
public void getConnectTimeout_returns_10000_when_property_is_not_defined() {
assertThat(underTest.getConnectTimeout()).isEqualTo(30_000L);
}
@Test
@UseDataProvider("notALongPropertyValues")
public void getConnectTimeout_returns_10000_when_property_is_not_a_long(String notALong) {
settings.setProperty("sonar.alm.timeout.connect", notALong);
assertThat(underTest.getConnectTimeout()).isEqualTo(30_000L);
}
@Test
public void getConnectTimeout_returns_value_of_property() {
long expected = new Random().nextInt(9_456_789);
settings.setProperty("sonar.alm.timeout.connect", expected);
assertThat(underTest.getConnectTimeout()).isEqualTo(expected);
}
@Test
public void getReadTimeout_returns_10000_when_property_is_not_defined() {
assertThat(underTest.getReadTimeout()).isEqualTo(30_000L);
}
@Test
@UseDataProvider("notALongPropertyValues")
public void getReadTimeout_returns_10000_when_property_is_not_a_long(String notALong) {
settings.setProperty("sonar.alm.timeout.read", notALong);
assertThat(underTest.getReadTimeout()).isEqualTo(30_000L);
}
@Test
public void getReadTimeout_returns_value_of_property() {
long expected = new Random().nextInt(9_456_789);
settings.setProperty("sonar.alm.timeout.read", expected);
assertThat(underTest.getReadTimeout()).isEqualTo(expected);
}
@DataProvider
public static Object[][] notALongPropertyValues() {
return new Object[][] {
{"foo"},
{""},
{"12.5"}
};
}
}
| 3,020 | 33.329545 | 103 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/azure/AzureDevOpsHttpClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.azure;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
public class AzureDevOpsHttpClientTest {
public static final String UNABLE_TO_CONTACT_AZURE = "Unable to contact Azure DevOps server, got an unexpected response";
@Rule
public LogTester logTester = new LogTester();
private static final String NON_JSON_PAYLOAD = "non json payload";
private final MockWebServer server = new MockWebServer();
private AzureDevOpsHttpClient underTest;
@Before
public void prepare() throws IOException {
logTester.setLevel(Level.DEBUG);
server.start();
TimeoutConfiguration timeoutConfiguration = new ConstantTimeoutConfiguration(10_000);
underTest = new AzureDevOpsHttpClient(timeoutConfiguration);
}
@After
public void stopServer() throws IOException {
server.shutdown();
}
@Test
public void check_pat() throws InterruptedException {
enqueueResponse(200, " { \"count\": 1,\n" +
" \"value\": [\n" +
" {\n" +
" \"id\": \"3311cd05-3f00-4a5e-b47f-df94a9982b6e\",\n" +
" \"name\": \"Project\",\n" +
" \"description\": \"Project Description\",\n" +
" \"url\": \"https://ado.sonarqube.com/DefaultCollection/_apis/projects/3311cd05-3f00-4a5e-b47f-df94a9982b6e\",\n" +
" \"state\": \"wellFormed\",\n" +
" \"revision\": 63,\n" +
" \"visibility\": \"private\"\n" +
" }]}");
underTest.checkPAT(server.url("").toString(), "token");
RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
String azureDevOpsUrlCall = request.getRequestUrl().toString();
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "_apis/projects?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.DEBUG))
.contains("check pat : [" + server.url("").toString() + "_apis/projects?api-version=3.0]");
}
@Test
public void check_invalid_pat() {
enqueueResponse(401);
String serverUrl = server.url("").toString();
assertThatThrownBy(() -> underTest.checkPAT(serverUrl, "invalid-token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
}
@Test
public void check_pat_with_server_error() {
enqueueResponse(500);
String serverUrl = server.url("").toString();
assertThatThrownBy(() -> underTest.checkPAT(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Azure DevOps server");
}
@Test
public void get_projects() throws InterruptedException {
enqueueResponse(200, " { \"count\": 2,\n" +
" \"value\": [\n" +
" {\n" +
" \"id\": \"3311cd05-3f00-4a5e-b47f-df94a9982b6e\",\n" +
" \"name\": \"Project 1\",\n" +
" \"description\": \"Project Description\",\n" +
" \"url\": \"https://ado.sonarqube.com/DefaultCollection/_apis/projects/3311cd05-3f00-4a5e-b47f-df94a9982b6e\",\n" +
" \"state\": \"wellFormed\",\n" +
" \"revision\": 63,\n" +
" \"visibility\": \"private\"\n" +
" }," +
"{\n" +
" \"id\": \"3be0f34d-c931-4ff8-8d37-18a83663bd3c\",\n" +
" \"name\": \"Project 2\",\n" +
" \"url\": \"https://ado.sonarqube.com/DefaultCollection/_apis/projects/3be0f34d-c931-4ff8-8d37-18a83663bd3c\",\n" +
" \"state\": \"wellFormed\",\n" +
" \"revision\": 52,\n" +
" \"visibility\": \"private\"\n" +
" }]}");
GsonAzureProjectList projects = underTest.getProjects(server.url("").toString(), "token");
RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
String azureDevOpsUrlCall = request.getRequestUrl().toString();
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "_apis/projects?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(logTester.logs(Level.DEBUG)).hasSize(1);
assertThat(logTester.logs(Level.DEBUG))
.contains("get projects : [" + server.url("") + "_apis/projects?api-version=3.0]");
assertThat(projects.getValues()).hasSize(2);
assertThat(projects.getValues())
.extracting(GsonAzureProject::getName, GsonAzureProject::getDescription)
.containsExactly(tuple("Project 1", "Project Description"), tuple("Project 2", null));
}
@Test
public void get_projects_non_json_payload() {
enqueueResponse(200, NON_JSON_PAYLOAD);
assertThatThrownBy(() -> underTest.getProjects(server.url("").toString(), "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(UNABLE_TO_CONTACT_AZURE);
assertThat(logTester.logs(Level.ERROR)).hasSize(1);
assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Response from Azure for request [" + server.url("") + "_apis/projects?api-version=3.0] could not be parsed:");
}
@Test
public void get_projects_with_invalid_pat() {
enqueueResponse(401);
assertThatThrownBy(() -> underTest.getProjects(server.url("").toString(), "invalid-token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
assertThat(logTester.logs(Level.ERROR)).hasSize(1);
assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Unable to contact Azure DevOps server for request [" + server.url("") + "_apis/projects?api-version=3.0]: Invalid personal access token");
}
@Test
public void get_projects_with_invalid_url() {
enqueueResponse(404);
assertThatThrownBy(() -> underTest.getProjects(server.url("").toString(), "invalid-token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid Azure URL");
assertThat(logTester.logs(Level.ERROR)).hasSize(1);
assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Unable to contact Azure DevOps server for request [" + server.url("") + "_apis/projects?api-version=3.0]: URL Not Found");
}
@Test
public void get_projects_with_server_error() {
enqueueResponse(500);
assertThatThrownBy(() -> underTest.getProjects(server.url("").toString(), "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Azure DevOps server");
assertThat(logTester.logs(Level.ERROR)).hasSize(1);
assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Azure API call to [" + server.url("") + "_apis/projects?api-version=3.0] failed with 500 http code. Azure response content :");
}
@Test
public void get_repos_with_project_name() throws InterruptedException {
enqueueResponse(200, "{\n" +
" \"value\": [\n" +
" {\n" +
" \"id\": \"741248a4-285e-4a6d-af52-1a49d8070638\",\n" +
" \"name\": \"Repository 1\",\n" +
" \"url\": \"https://ado.sonarqube.com/repositories/\",\n" +
" \"project\": {\n" +
" \"id\": \"c88ddb32-ced8-420d-ab34-764133038b34\",\n" +
" \"name\": \"projectName\",\n" +
" \"url\": \"https://ado.sonarqube.com/DefaultCollection/_apis/projects/c88ddb32-ced8-420d-ab34-764133038b34\",\n" +
" \"state\": \"wellFormed\",\n" +
" \"revision\": 29,\n" +
" \"visibility\": \"private\",\n" +
" \"lastUpdateTime\": \"2020-11-11T09:38:03.3Z\"\n" +
" },\n" +
" \"size\": 0\n" +
" }\n" +
" ],\n" +
" \"count\": 1\n" +
"}");
GsonAzureRepoList repos = underTest.getRepos(server.url("").toString(), "token", "projectName");
RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
String azureDevOpsUrlCall = request.getRequestUrl().toString();
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "projectName/_apis/git/repositories?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(logTester.logs(Level.DEBUG)).hasSize(1);
assertThat(logTester.logs(Level.DEBUG))
.contains("get repos : [" + server.url("").toString() + "projectName/_apis/git/repositories?api-version=3.0]");
assertThat(repos.getValues()).hasSize(1);
assertThat(repos.getValues())
.extracting(GsonAzureRepo::getName, GsonAzureRepo::getUrl, r -> r.getProject().getName())
.containsExactly(tuple("Repository 1", "https://ado.sonarqube.com/repositories/", "projectName"));
}
@Test
public void get_repos_without_project_name() throws InterruptedException {
enqueueResponse(200, "{ \"value\": [], \"count\": 0 }");
GsonAzureRepoList repos = underTest.getRepos(server.url("").toString(), "token", null);
RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
String azureDevOpsUrlCall = request.getRequestUrl().toString();
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "_apis/git/repositories?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(repos.getValues()).isEmpty();
}
@Test
public void get_repos_non_json_payload() {
enqueueResponse(200, NON_JSON_PAYLOAD);
assertThatThrownBy(() -> underTest.getRepos(server.url("").toString(), "token", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(UNABLE_TO_CONTACT_AZURE);
}
@Test
public void get_repo() throws InterruptedException {
enqueueResponse(200, "{ " +
" \"id\": \"Repo-Id-1\",\n" +
" \"name\": \"Repo-Name-1\",\n" +
" \"url\": \"https://ado.sonarqube.com/DefaultCollection/Repo-Id-1\",\n" +
" \"project\": {\n" +
" \"id\": \"84ea9d51-0c8a-44ad-be92-b2af7fe2c299\",\n" +
" \"name\": \"Project-Name\",\n" +
" \"description\": \"Project's description\" \n" +
" },\n" +
" \"defaultBranch\": \"refs/heads/default-branch\",\n" +
" \"size\": 0" +
"}");
GsonAzureRepo repo = underTest.getRepo(server.url("").toString(), "token", "Project-Name", "Repo-Name-1");
RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
String azureDevOpsUrlCall = request.getRequestUrl().toString();
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "Project-Name/_apis/git/repositories/Repo-Name-1?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(logTester.logs(Level.DEBUG)).hasSize(1);
assertThat(logTester.logs(Level.DEBUG))
.contains("get repo : [" + server.url("").toString() + "Project-Name/_apis/git/repositories/Repo-Name-1?api-version=3.0]");
assertThat(repo.getId()).isEqualTo("Repo-Id-1");
assertThat(repo.getName()).isEqualTo("Repo-Name-1");
assertThat(repo.getUrl()).isEqualTo("https://ado.sonarqube.com/DefaultCollection/Repo-Id-1");
assertThat(repo.getProject().getName()).isEqualTo("Project-Name");
assertThat(repo.getDefaultBranchName()).isEqualTo("default-branch");
}
@Test
public void get_repo_non_json_payload() {
enqueueResponse(200, NON_JSON_PAYLOAD);
assertThatThrownBy(() -> underTest.getRepo(server.url("").toString(), "token", "projectName", "repoName"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(UNABLE_TO_CONTACT_AZURE);
}
@Test
public void get_repo_json_error_payload() {
enqueueResponse(400,
"{'message':'TF200016: The following project does not exist: projectName. Verify that the name of the project is correct and that the project exists on the specified Azure DevOps Server.'}");
assertThatThrownBy(() -> underTest.getRepo(server.url("").toString(), "token", "projectName", "repoName"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(
"Unable to contact Azure DevOps server : TF200016: The following project does not exist: projectName. Verify that the name of the project is correct and that the project exists on the specified Azure DevOps Server.");
}
private void enqueueResponse(int responseCode) {
enqueueResponse(responseCode, "");
}
private void enqueueResponse(int responseCode, @Nullable String body) {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setResponseCode(responseCode)
.setBody(body));
}
@Test
public void trim_url() {
assertThat(AzureDevOpsHttpClient.getTrimmedUrl("http://localhost:4564/"))
.isEqualTo("http://localhost:4564");
}
@Test
public void trim_url_without_ending_slash() {
assertThat(AzureDevOpsHttpClient.getTrimmedUrl("http://localhost:4564"))
.isEqualTo("http://localhost:4564");
}
@Test
public void trim_null_url() {
assertThat(AzureDevOpsHttpClient.getTrimmedUrl(null))
.isNull();
}
@Test
public void trim_empty_url() {
assertThat(AzureDevOpsHttpClient.getTrimmedUrl(""))
.isEmpty();
}
}
| 14,397 | 40.373563 | 225 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/azure/AzureDevOpsValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.azure;
import org.junit.Test;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.alm.setting.AlmSettingDto;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AzureDevOpsValidatorTest {
private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class);
private final Settings settings = mock(Settings.class);
private final AzureDevOpsValidator underTest = new AzureDevOpsValidator(azureDevOpsHttpClient, settings);
@Test
public void validate_givenHttpClientThrowingException_throwException() {
AlmSettingDto dto = createMockDto();
doThrow(new IllegalArgumentException()).when(azureDevOpsHttpClient).checkPAT(any(), any());
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate(dto))
.withMessage("Invalid Azure URL or Personal Access Token");
}
@Test(expected = Test.None.class /* no exception expected */)
public void validate_givenHttpClientNotThrowingException_doesNotThrowException() {
AlmSettingDto dto = createMockDto();
underTest.validate(dto);
}
private AlmSettingDto createMockDto() {
AlmSettingDto dto = mock(AlmSettingDto.class);
when(dto.getUrl()).thenReturn("http://azure-devops-url.url");
when(dto.getDecryptedPersonalAccessToken(any())).thenReturn("decrypted-token");
return dto;
}
}
| 2,443 | 37.1875 | 107 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/azure/GsonAzureRepoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.azure;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class GsonAzureRepoTest {
@Test
@UseDataProvider("data")
public void extract_branch_name_from_full_branch_name(String actualFullBranchName, String expectedBranchName) {
GsonAzureRepo repo = new GsonAzureRepo(
"repo_id",
"repo_name",
"repo_url",
new GsonAzureProject(),
actualFullBranchName
);
assertThat(repo.getDefaultBranchName()).isEqualTo(expectedBranchName);
}
@DataProvider
public static Object[][] data() {
return new Object[][]{
{"refs/heads/default_branch_name", "default_branch_name"},
{"refs/HEADS/default_branch_name", "default_branch_name"},
{"refs/heads/Default_branch_name", "Default_branch_name"},
{"branch_Name_without_prefix", "branch_Name_without_prefix"},
{"", null},
{null, null}
};
}
}
| 2,028 | 33.982759 | 113 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucket/bitbucketcloud/BitbucketCloudRestClientConfigurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucket.bitbucketcloud;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Test;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.alm.client.TimeoutConfigurationImpl;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.alm.client.TimeoutConfigurationImpl.CONNECT_TIMEOUT_PROPERTY;
import static org.sonar.alm.client.TimeoutConfigurationImpl.READ_TIMEOUT_PROPERTY;
public class BitbucketCloudRestClientConfigurationTest {
private static final long CONNECT_TIMEOUT_VALUE = 5435L;
private static final long READ_TIMEOUT_VALUE = 13123L;
private final MapSettings settings = new MapSettings();
private final TimeoutConfiguration timeoutConfiguration = new TimeoutConfigurationImpl(settings.asConfig());
private final BitbucketCloudRestClientConfiguration underTest = new BitbucketCloudRestClientConfiguration(timeoutConfiguration);
public MockWebServer server = new MockWebServer();
@Test
public void bitBucketCloudHttpClient_returnsCorrectlyConfiguredHttpClient() throws Exception {
settings.setProperty(CONNECT_TIMEOUT_PROPERTY, CONNECT_TIMEOUT_VALUE);
settings.setProperty(READ_TIMEOUT_PROPERTY, READ_TIMEOUT_VALUE);
OkHttpClient client = underTest.bitbucketCloudHttpClient();
assertThat(client.connectTimeoutMillis()).isEqualTo(CONNECT_TIMEOUT_VALUE);
assertThat(client.readTimeoutMillis()).isEqualTo(READ_TIMEOUT_VALUE);
assertThat(client.proxy()).isNull();
assertThat(client.followRedirects()).isFalse();
RecordedRequest recordedRequest = call(client);
assertThat(recordedRequest.getHeader("Proxy-Authorization")).isNull();
}
private RecordedRequest call(OkHttpClient client) throws IOException, InterruptedException {
server.enqueue(new MockResponse().setBody("pong"));
client.newCall(new Request.Builder().url(server.url("/ping")).build()).execute();
return server.takeRequest();
}
}
| 3,021 | 41.56338 | 130 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucket/bitbucketcloud/BitbucketCloudRestClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import javax.net.ssl.SSLHandshakeException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.BBC_FAIL_WITH_ERROR;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.BBC_FAIL_WITH_RESPONSE;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.ERROR_BBC_SERVERS;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.JSON_MEDIA_TYPE;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.MISSING_PULL_REQUEST_READ_PERMISSION;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.OAUTH_CONSUMER_NOT_PRIVATE;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.SCOPE;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.UNABLE_TO_CONTACT_BBC_SERVERS;
import static org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient.UNAUTHORIZED_CLIENT;
public class BitbucketCloudRestClientTest {
@Rule
public LogTester logTester = new LogTester();
private final MockWebServer server = new MockWebServer();
private BitbucketCloudRestClient underTest;
private String serverURL;
@Before
public void prepare() throws IOException {
server.start();
serverURL = server.url("/").toString();
underTest = new BitbucketCloudRestClient(new OkHttpClientBuilder().build(), serverURL, serverURL);
}
@After
public void stopServer() throws IOException {
server.shutdown();
}
@Test
public void get_repos() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody("{\n" +
" \"values\": [\n" +
" {\n" +
" \"slug\": \"banana\",\n" +
" \"uuid\": \"BANANA-UUID\",\n" +
" \"name\": \"banana\",\n" +
" \"project\": {\n" +
" \"key\": \"HOY\",\n" +
" \"uuid\": \"BANANA-PROJECT-UUID\",\n" +
" \"name\": \"hoy\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"slug\": \"potato\",\n" +
" \"uuid\": \"POTATO-UUID\",\n" +
" \"name\": \"potato\",\n" +
" \"project\": {\n" +
" \"key\": \"HEY\",\n" +
" \"uuid\": \"POTATO-PROJECT-UUID\",\n" +
" \"name\": \"hey\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}"));
RepositoryList repositoryList = underTest.searchRepos("user:apppwd", "", null, 1, 100);
assertThat(repositoryList.getNext()).isNull();
assertThat(repositoryList.getValues())
.hasSize(2)
.extracting(Repository::getUuid, Repository::getName, Repository::getSlug,
g -> g.getProject().getUuid(), g -> g.getProject().getKey(), g -> g.getProject().getName())
.containsExactlyInAnyOrder(
tuple("BANANA-UUID", "banana", "banana", "BANANA-PROJECT-UUID", "HOY", "hoy"),
tuple("POTATO-UUID", "potato", "potato", "POTATO-PROJECT-UUID", "HEY", "hey"));
}
@Test
public void get_repo() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody(
" {\n" +
" \"slug\": \"banana\",\n" +
" \"uuid\": \"BANANA-UUID\",\n" +
" \"name\": \"banana\",\n" +
" \"mainbranch\": {\n" +
" \"type\": \"branch\",\n" +
" \"name\": \"develop\"\n" +
" }," +
" \"project\": {\n" +
" \"key\": \"HOY\",\n" +
" \"uuid\": \"BANANA-PROJECT-UUID\",\n" +
" \"name\": \"hoy\"\n" +
" }\n" +
" }"));
Repository repository = underTest.getRepo("user:apppwd", "workspace", "rep");
assertThat(repository.getUuid()).isEqualTo("BANANA-UUID");
assertThat(repository.getName()).isEqualTo("banana");
assertThat(repository.getSlug()).isEqualTo("banana");
assertThat(repository.getProject())
.extracting(Project::getUuid, Project::getKey, Project::getName)
.contains("BANANA-PROJECT-UUID", "HOY", "hoy");
assertThat(repository.getMainBranch())
.extracting(MainBranch::getType, MainBranch::getName)
.contains("branch", "develop");
}
@Test
public void bbc_object_serialization_deserialization() {
Project project = new Project("PROJECT-UUID-ONE", "projectKey", "projectName");
MainBranch mainBranch = new MainBranch("branch", "develop");
Repository repository = new Repository("REPO-UUID-ONE", "repo-slug", "repoName", project, mainBranch);
RepositoryList repos = new RepositoryList(null, List.of(repository), 1, 100);
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody(new Gson().toJson(repos)));
RepositoryList repositoryList = underTest.searchRepos("user:apppwd", "", null, 1, 100);
assertThat(repositoryList.getNext()).isNull();
assertThat(repositoryList.getPage()).isOne();
assertThat(repositoryList.getPagelen()).isEqualTo(100);
assertThat(repositoryList.getValues())
.hasSize(1)
.extracting(Repository::getUuid, Repository::getName, Repository::getSlug,
g -> g.getProject().getUuid(), g -> g.getProject().getKey(), g -> g.getProject().getName(),
g -> g.getMainBranch().getType(), g -> g.getMainBranch().getName())
.containsExactlyInAnyOrder(
tuple("REPO-UUID-ONE", "repoName", "repo-slug",
"PROJECT-UUID-ONE", "projectKey", "projectName",
"branch", "develop"));
}
@Test
public void validate_fails_if_unauthorized() {
server.enqueue(new MockResponse().setResponseCode(401).setBody("Unauthorized"));
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "401", "Unauthorized"));
}
@Test
public void validate_fails_with_IAE_if_timeout() {
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"));
}
@Test
public void validate_success() throws Exception {
String tokenResponse = "{\"scopes\": \"webhook pullrequest:write\", \"access_token\": \"token\", \"expires_in\": 7200, "
+ "\"token_type\": \"bearer\", \"state\": \"client_credentials\", \"refresh_token\": \"abc\"}";
server.enqueue(new MockResponse().setBody(tokenResponse));
server.enqueue(new MockResponse().setBody("OK"));
underTest.validate("clientId", "clientSecret", "workspace");
RecordedRequest request = server.takeRequest();
assertThat(request.getPath()).isEqualTo("/");
assertThat(request.getHeader("Authorization")).isNotNull();
assertThat(request.getBody().readUtf8()).isEqualTo("grant_type=client_credentials");
}
@Test
public void validate_fails_if_unsufficient_pull_request_privileges() throws Exception {
String tokenResponse = "{\"scopes\": \"\", \"access_token\": \"token\", \"expires_in\": 7200, "
+ "\"token_type\": \"bearer\", \"state\": \"client_credentials\", \"refresh_token\": \"abc\"}";
server.enqueue(new MockResponse().setBody(tokenResponse));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(ERROR_BBC_SERVERS + ": " + MISSING_PULL_REQUEST_READ_PERMISSION);
assertThat(logTester.logs(Level.INFO)).containsExactly(MISSING_PULL_REQUEST_READ_PERMISSION + String.format(SCOPE, ""));
}
@Test
public void validate_with_invalid_workspace() {
String tokenResponse = "{\"scopes\": \"webhook pullrequest:write\", \"access_token\": \"token\", \"expires_in\": 7200, "
+ "\"token_type\": \"bearer\", \"state\": \"client_credentials\", \"refresh_token\": \"abc\"}";
server.enqueue(new MockResponse().setBody(tokenResponse).setResponseCode(200).setHeader("Content-Type", JSON_MEDIA_TYPE));
String response = "{\"type\": \"error\", \"error\": {\"message\": \"No workspace with identifier 'workspace'.\"}}";
server.enqueue(new MockResponse().setBody(response).setResponseCode(404).setHeader("Content-Type", JSON_MEDIA_TYPE));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage("Error returned by Bitbucket Cloud: No workspace with identifier 'workspace'.");
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "404", response));
}
@Test
public void validate_with_private_consumer() {
String response = "{\"error_description\": \"Cannot use client_credentials with a consumer marked as \\\"public\\\". "
+ "Calls for auto generated consumers should use urn:bitbucket:oauth2:jwt instead.\", \"error\": \"invalid_grant\"}";
server.enqueue(new MockResponse().setBody(response).setResponseCode(400).setHeader("Content-Type", JSON_MEDIA_TYPE));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS + ": " + OAUTH_CONSUMER_NOT_PRIVATE);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "400", "invalid_grant"));
}
@Test
public void validate_with_invalid_credentials() {
String response = "{\"error_description\": \"Invalid OAuth client credentials\", \"error\": \"unauthorized_client\"}";
server.enqueue(new MockResponse().setBody(response).setResponseCode(400).setHeader("Content-Type", JSON_MEDIA_TYPE));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS + ": " + UNAUTHORIZED_CLIENT);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "400", "unauthorized_client"));
}
@Test
public void validate_with_insufficient_privileges() {
String tokenResponse = "{\"scopes\": \"webhook pullrequest:write\", \"access_token\": \"token\", \"expires_in\": 7200, "
+ "\"token_type\": \"bearer\", \"state\": \"client_credentials\", \"refresh_token\": \"abc\"}";
server.enqueue(new MockResponse().setBody(tokenResponse).setResponseCode(200).setHeader("Content-Type", JSON_MEDIA_TYPE));
String error = "{\"type\": \"error\", \"error\": {\"message\": \"Your credentials lack one or more required privilege scopes.\", \"detail\": "
+ "{\"granted\": [\"email\"], \"required\": [\"account\"]}}}\n";
server.enqueue(new MockResponse().setBody(error).setResponseCode(400).setHeader("Content-Type", JSON_MEDIA_TYPE));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage("Error returned by Bitbucket Cloud: Your credentials lack one or more required privilege scopes.");
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "400", error));
}
@Test
public void validate_app_password_success() throws Exception {
String reposResponse = "{\"pagelen\": 10,\n" +
"\"values\": [],\n" +
"\"page\": 1,\n" +
"\"size\": 0\n" +
"}";
server.enqueue(new MockResponse().setBody(reposResponse));
server.enqueue(new MockResponse().setBody("OK"));
underTest.validateAppPassword("user:password", "workspace");
RecordedRequest request = server.takeRequest();
assertThat(request.getPath()).isEqualTo("/2.0/repositories/workspace");
assertThat(request.getHeader("Authorization")).isNotNull();
}
@Test
public void validate_app_password_with_invalid_credentials() {
String response = "{\"type\": \"error\", \"error\": {\"message\": \"Invalid credentials.\"}}";
server.enqueue(new MockResponse().setBody(response).setResponseCode(401).setHeader("Content-Type", JSON_MEDIA_TYPE));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validateAppPassword("wrong:wrong", "workspace"))
.withMessage("Error returned by Bitbucket Cloud: Invalid credentials.");
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "401", response));
}
@Test
public void nullErrorBodyIsSupported() throws IOException {
OkHttpClient clientMock = mock(OkHttpClient.class);
Call callMock = mock(Call.class);
String url = "http://any.test/";
String message = "Unknown issue";
when(callMock.execute()).thenReturn(new Response.Builder()
.request(new Request.Builder().url(url).build())
.protocol(Protocol.HTTP_1_1)
.code(500)
.message(message)
.build());
when(clientMock.newCall(any())).thenReturn(callMock);
underTest = new BitbucketCloudRestClient(clientMock);
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, url, "500", message));
}
@Test
public void invalidJsonResponseBodyIsSupported() {
String body = "not a JSON string";
server.enqueue(new MockResponse().setResponseCode(500)
.setHeader("content-type", "application/json; charset=utf-8")
.setBody(body));
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "500", body));
}
@Test
public void responseBodyWithoutErrorFieldIsSupported() {
String body = "{\"foo\": \"bar\"}";
server.enqueue(new MockResponse().setResponseCode(500)
.setHeader("content-type", "application/json; charset=utf-8")
.setBody(body));
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "500", body));
}
@Test
public void validate_fails_when_ssl_verification_failed() throws IOException {
//GIVEN
OkHttpClient okHttpClient = mock(OkHttpClient.class);
Call call = mock(Call.class);
underTest = new BitbucketCloudRestClient(okHttpClient, serverURL, serverURL);
when(okHttpClient.newCall(any())).thenReturn(call);
when(call.execute()).thenThrow(new SSLHandshakeException("SSL verification failed"));
//WHEN
//THEN
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_ERROR, serverURL, "SSL verification failed"));
}
}
| 17,549 | 45.925134 | 157 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucket/bitbucketcloud/BitbucketCloudValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucket.bitbucketcloud;
import org.junit.Test;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.alm.setting.AlmSettingDto;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class BitbucketCloudValidatorTest {
private final BitbucketCloudRestClient bitbucketCloudRestClient = mock(BitbucketCloudRestClient.class);
private final Settings settings = mock(Settings.class);
private final BitbucketCloudValidator underTest = new BitbucketCloudValidator(bitbucketCloudRestClient, settings);
private static final String EXAMPLE_APP_ID = "123";
@Test
public void validate_forwardsExceptionFromRestClient() {
AlmSettingDto dto = mock(AlmSettingDto.class);
when(dto.getAppId()).thenReturn(EXAMPLE_APP_ID);
when(dto.getClientId()).thenReturn("clientId");
when(dto.getDecryptedClientSecret(any())).thenReturn("secret");
doThrow(new IllegalArgumentException("Exception from bitbucket cloud rest client"))
.when(bitbucketCloudRestClient).validate(any(), any(), any());
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate(dto))
.withMessage("Exception from bitbucket cloud rest client");
}
@Test
public void validate_callsValidate() {
AlmSettingDto dto = mock(AlmSettingDto.class);
when(dto.getAppId()).thenReturn(EXAMPLE_APP_ID);
when(dto.getClientId()).thenReturn("clientId");
when(dto.getDecryptedClientSecret(any())).thenReturn("secret");
underTest.validate(dto);
verify(bitbucketCloudRestClient, times(1)).validate("clientId", "secret", EXAMPLE_APP_ID);
}
}
| 2,764 | 38.5 | 116 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BitbucketServerRestClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import java.io.IOException;
import java.util.function.Function;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import okhttp3.MediaType;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy;
import okio.Buffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
@RunWith(DataProviderRunner.class)
public class BitbucketServerRestClientTest {
private final MockWebServer server = new MockWebServer();
private static final String REPOS_BODY = "{\n" +
" \"isLastPage\": true,\n" +
" \"values\": [\n" +
" {\n" +
" \"slug\": \"banana\",\n" +
" \"id\": 2,\n" +
" \"name\": \"banana\",\n" +
" \"project\": {\n" +
" \"key\": \"HOY\",\n" +
" \"id\": 2,\n" +
" \"name\": \"hoy\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"slug\": \"potato\",\n" +
" \"id\": 1,\n" +
" \"name\": \"potato\",\n" +
" \"project\": {\n" +
" \"key\": \"HEY\",\n" +
" \"id\": 1,\n" +
" \"name\": \"hey\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
@Rule
public LogTester logTester = new LogTester();
private BitbucketServerRestClient underTest;
@Before
public void prepare() throws IOException {
server.start();
underTest = new BitbucketServerRestClient(new ConstantTimeoutConfiguration(500));
}
@After
public void stopServer() throws IOException {
server.shutdown();
}
@Test
public void get_repos() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody("{\n" +
" \"isLastPage\": true,\n" +
" \"values\": [\n" +
" {\n" +
" \"slug\": \"banana\",\n" +
" \"id\": 2,\n" +
" \"name\": \"banana\",\n" +
" \"project\": {\n" +
" \"key\": \"HOY\",\n" +
" \"id\": 2,\n" +
" \"name\": \"hoy\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"slug\": \"potato\",\n" +
" \"id\": 1,\n" +
" \"name\": \"potato\",\n" +
" \"project\": {\n" +
" \"key\": \"HEY\",\n" +
" \"id\": 1,\n" +
" \"name\": \"hey\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}"));
RepositoryList gsonBBSRepoList = underTest.getRepos(server.url("/").toString(), "token", "", "");
assertThat(gsonBBSRepoList.isLastPage()).isTrue();
assertThat(gsonBBSRepoList.getValues()).hasSize(2);
assertThat(gsonBBSRepoList.getValues()).extracting(Repository::getId, Repository::getName, Repository::getSlug,
g -> g.getProject().getId(), g -> g.getProject().getKey(), g -> g.getProject().getName())
.containsExactlyInAnyOrder(
tuple(2L, "banana", "banana", 2L, "HOY", "hoy"),
tuple(1L, "potato", "potato", 1L, "HEY", "hey"));
}
@Test
public void get_recent_repos() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody("{\n" +
" \"isLastPage\": true,\n" +
" \"values\": [\n" +
" {\n" +
" \"slug\": \"banana\",\n" +
" \"id\": 2,\n" +
" \"name\": \"banana\",\n" +
" \"project\": {\n" +
" \"key\": \"HOY\",\n" +
" \"id\": 2,\n" +
" \"name\": \"hoy\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"slug\": \"potato\",\n" +
" \"id\": 1,\n" +
" \"name\": \"potato\",\n" +
" \"project\": {\n" +
" \"key\": \"HEY\",\n" +
" \"id\": 1,\n" +
" \"name\": \"hey\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}"));
RepositoryList gsonBBSRepoList = underTest.getRecentRepo(server.url("/").toString(), "token");
assertThat(gsonBBSRepoList.isLastPage()).isTrue();
assertThat(gsonBBSRepoList.getValues()).hasSize(2);
assertThat(gsonBBSRepoList.getValues()).extracting(Repository::getId, Repository::getName, Repository::getSlug,
g -> g.getProject().getId(), g -> g.getProject().getKey(), g -> g.getProject().getName())
.containsExactlyInAnyOrder(
tuple(2L, "banana", "banana", 2L, "HOY", "hoy"),
tuple(1L, "potato", "potato", 1L, "HEY", "hey"));
}
@Test
public void get_repo() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody(
" {" +
" \"slug\": \"banana-slug\"," +
" \"id\": 2,\n" +
" \"name\": \"banana\"," +
" \"project\": {\n" +
" \"key\": \"HOY\"," +
" \"id\": 3,\n" +
" \"name\": \"hoy\"" +
" }" +
" }"));
Repository repository = underTest.getRepo(server.url("/").toString(), "token", "", "");
assertThat(repository.getId()).isEqualTo(2L);
assertThat(repository.getName()).isEqualTo("banana");
assertThat(repository.getSlug()).isEqualTo("banana-slug");
assertThat(repository.getProject())
.extracting(Project::getId, Project::getKey, Project::getName)
.contains(3L, "HOY", "hoy");
}
@Test
public void get_projects() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody("{\n" +
" \"isLastPage\": true,\n" +
" \"values\": [\n" +
" {\n" +
" \"key\": \"HEY\",\n" +
" \"id\": 1,\n" +
" \"name\": \"hey\"\n" +
" },\n" +
" {\n" +
" \"key\": \"HOY\",\n" +
" \"id\": 2,\n" +
" \"name\": \"hoy\"\n" +
" }\n" +
" ]\n" +
"}"));
final ProjectList gsonBBSProjectList = underTest.getProjects(server.url("/").toString(), "token");
assertThat(gsonBBSProjectList.getValues()).hasSize(2);
assertThat(gsonBBSProjectList.getValues()).extracting(Project::getId, Project::getKey, Project::getName)
.containsExactlyInAnyOrder(
tuple(1L, "HEY", "hey"),
tuple(2L, "HOY", "hoy"));
}
@Test
public void get_projects_failed() {
server.enqueue(new MockResponse()
.setBody(new Buffer().write(new byte[4096]))
.setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.getProjects(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
assertThat(String.join(", ", logTester.logs())).contains("Unable to contact Bitbucket server");
}
@Test
public void getBranches_given0Branches_returnEmptyList() {
String bodyWith0Branches = "{\n" +
" \"size\": 0,\n" +
" \"limit\": 25,\n" +
" \"isLastPage\": true,\n" +
" \"values\": [],\n" +
" \"start\": 0\n" +
"}";
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody(bodyWith0Branches));
BranchesList branches = underTest.getBranches(server.url("/").toString(), "token", "projectSlug", "repoSlug");
assertThat(branches.getBranches()).isEmpty();
}
@Test
public void getBranches_given1Branch_returnListWithOneBranch() {
String bodyWith1Branch = "{\n" +
" \"size\": 1,\n" +
" \"limit\": 25,\n" +
" \"isLastPage\": true,\n" +
" \"values\": [{\n" +
" \"id\": \"refs/heads/demo\",\n" +
" \"displayId\": \"demo\",\n" +
" \"type\": \"BRANCH\",\n" +
" \"latestCommit\": \"3e30a6701af6f29f976e9a6609a6076b32a69ac3\",\n" +
" \"latestChangeset\": \"3e30a6701af6f29f976e9a6609a6076b32a69ac3\",\n" +
" \"isDefault\": false\n" +
" }],\n" +
" \"start\": 0\n" +
"}";
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody(bodyWith1Branch));
BranchesList branches = underTest.getBranches(server.url("/").toString(), "token", "projectSlug", "repoSlug");
assertThat(branches.getBranches()).hasSize(1);
Branch branch = branches.getBranches().get(0);
assertThat(branch.getName()).isEqualTo("demo");
assertThat(branch.isDefault()).isFalse();
}
@Test
public void getBranches_given2Branches_returnListWithTwoBranches() {
String bodyWith2Branches = "{\n" +
" \"size\": 2,\n" +
" \"limit\": 25,\n" +
" \"isLastPage\": true,\n" +
" \"values\": [{\n" +
" \"id\": \"refs/heads/demo\",\n" +
" \"displayId\": \"demo\",\n" +
" \"type\": \"BRANCH\",\n" +
" \"latestCommit\": \"3e30a6701af6f29f976e9a6609a6076b32a69ac3\",\n" +
" \"latestChangeset\": \"3e30a6701af6f29f976e9a6609a6076b32a69ac3\",\n" +
" \"isDefault\": false\n" +
" }, {\n" +
" \"id\": \"refs/heads/master\",\n" +
" \"displayId\": \"master\",\n" +
" \"type\": \"BRANCH\",\n" +
" \"latestCommit\": \"66633864d27c531ff43892f6dfea6d91632682fa\",\n" +
" \"latestChangeset\": \"66633864d27c531ff43892f6dfea6d91632682fa\",\n" +
" \"isDefault\": true\n" +
" }],\n" +
" \"start\": 0\n" +
"}";
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody(bodyWith2Branches));
BranchesList branches = underTest.getBranches(server.url("/").toString(), "token", "projectSlug", "repoSlug");
assertThat(branches.getBranches()).hasSize(2);
}
@Test
public void invalid_empty_url() {
assertThatThrownBy(() -> BitbucketServerRestClient.buildUrl(null, ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("url must start with http:// or https://");
}
@Test
public void invalid_url() {
assertThatThrownBy(() -> BitbucketServerRestClient.buildUrl("file://wrong-url", ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("url must start with http:// or https://");
}
@Test
public void malformed_json() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody("I'm malformed JSON"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.getRepo(serverUrl, "token", "", ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unexpected response from Bitbucket server");
assertThat(String.join(", ", logTester.logs()))
.contains("Unexpected response from Bitbucket server : [I'm malformed JSON]");
}
@Test
public void fail_json_error_handling() {
assertThatThrownBy(() -> underTest.applyHandler(body -> underTest.buildGson().fromJson(body, Object.class), "not json"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server, got an unexpected response");
assertThat(String.join(", ", logTester.logs()))
.contains("Unable to contact Bitbucket server. Unexpected body response was : [not json]");
}
@Test
public void validate_handler_call_on_empty_body() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(""));
assertThat(underTest.doGet("token", server.url("/"), Function.identity()))
.isEmpty();
}
@Test
public void error_handling() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setResponseCode(400)
.setBody("{\n" +
" \"errors\": [\n" +
" {\n" +
" \"context\": null,\n" +
" \"message\": \"Bad message\",\n" +
" \"exceptionName\": \"com.atlassian.bitbucket.auth.BadException\"\n" +
" }\n" +
" ]\n" +
"}"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.getRepo(serverUrl, "token", "", ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
}
@Test
public void unauthorized_error() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setResponseCode(401)
.setBody("{\n" +
" \"errors\": [\n" +
" {\n" +
" \"context\": null,\n" +
" \"message\": \"Bad message\",\n" +
" \"exceptionName\": \"com.atlassian.bitbucket.auth.BadException\"\n" +
" }\n" +
" ]\n" +
"}"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.getRepo(serverUrl, "token", "", ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
}
@DataProvider
public static Object[][] expectedErrorMessageFromHttpNoJsonBody() {
return new Object[][] {
{200, "content ready", "application/json;charset=UTF-8", "Unexpected response from Bitbucket server"},
{201, "content ready!", "application/xhtml+xml", "Unexpected response from Bitbucket server"},
{401, "<p>unauthorized</p>", "application/json;charset=UTF-8", "Invalid personal access token"},
{401, "<p>unauthorized</p>", "application/json", "Invalid personal access token"},
{401, "<not-authorized>401</not-authorized>", "application/xhtml+xml", "Invalid personal access token"},
{403, "<p>forbidden</p>", "application/json;charset=UTF-8", "Unable to contact Bitbucket server"},
{404, "<p>not found</p>","application/json;charset=UTF-8", "Error 404. The requested Bitbucket server is unreachable."},
{406, "<p>not accepted</p>", "application/json;charset=UTF-8", "Unable to contact Bitbucket server"},
{409, "<p>conflict</p>", "application/json;charset=UTF-8", "Unable to contact Bitbucket server"}
};
}
@Test
@UseDataProvider("expectedErrorMessageFromHttpNoJsonBody")
public void fail_response_when_http_no_json_body(int responseCode, String body, String headerContent, String expectedErrorMessage) {
server.enqueue(new MockResponse()
.setHeader("Content-Type", headerContent)
.setResponseCode(responseCode)
.setBody(body));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.getRepo(serverUrl, "token", "", ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(expectedErrorMessage);
}
@Test
public void fail_validate_on_io_exception() throws IOException {
server.shutdown();
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
assertThat(String.join(", ", logTester.logs())).contains("Unable to contact Bitbucket server");
}
@Test
public void fail_validate_url_on_non_json_result_log_correctly_the_response() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setResponseCode(500)
.setBody("not json"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateReadPermission(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
assertThat(String.join(", ", logTester.logs())).contains("Unable to contact Bitbucket server: 500 not json");
}
@Test
public void fail_validate_url_on_text_result_log_the_returned_payload() {
server.enqueue(new MockResponse()
.setResponseCode(500)
.setBody("this is a text payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateReadPermission(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
assertThat(String.join(", ", logTester.logs())).contains("Unable to contact Bitbucket server: 500 this is a text payload");
}
@Test
public void validate_url_success() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(REPOS_BODY));
underTest.validateUrl(server.url("/").toString());
}
@Test
public void validate_url_fail_when_not_starting_with_protocol() {
assertThatThrownBy(() -> underTest.validateUrl("any_url_not_starting_with_http.com"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("url must start with http:// or https://");
}
@Test
public void validate_token_success() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody("{\n" +
" \"size\":10,\n" +
" \"limit\":25,\n" +
" \"isLastPage\":true,\n" +
" \"values\":[\n" +
" {\n" +
" \"name\":\"jean.michel\",\n" +
" \"emailAddress\":\"jean.michel@sonarsource.com\",\n" +
" \"id\":2,\n" +
" \"displayName\":\"Jean Michel\",\n" +
" \"active\":true,\n" +
" \"slug\":\"jean.michel\",\n" +
" \"type\":\"NORMAL\",\n" +
" \"links\":{\n" +
" \"self\":[\n" +
" {\n" +
" \"href\":\"https://bitbucket-testing.valiantys.sonarsource.com/users/jean.michel\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"name\":\"prince.de.lu\",\n" +
" \"emailAddress\":\"prince.de.lu@sonarsource.com\",\n" +
" \"id\":103,\n" +
" \"displayName\":\"Prince de Lu\",\n" +
" \"active\":true,\n" +
" \"slug\":\"prince.de.lu\",\n" +
" \"type\":\"NORMAL\",\n" +
" \"links\":{\n" +
" \"self\":[\n" +
" {\n" +
" \"href\":\"https://bitbucket-testing.valiantys.sonarsource.com/users/prince.de.lu\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" ],\n" +
" \"start\":0\n" +
"}"));
underTest.validateToken(server.url("/").toString(), "token");
}
@Test
public void validate_read_permission_success() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(REPOS_BODY));
underTest.validateReadPermission(server.url("/").toString(), "token");
}
@Test
public void fail_validate_url_when_on_http_error() {
server.enqueue(new MockResponse().setResponseCode(500)
.setBody("something unexpected"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
}
@Test
public void fail_validate_url_when_not_found_is_returned() {
server.enqueue(new MockResponse().setResponseCode(404)
.setBody("something unexpected"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(BitbucketServerException.class)
.hasMessage("Error 404. The requested Bitbucket server is unreachable.")
.extracting(e -> ((BitbucketServerException) e).getHttpStatus()).isEqualTo(404);
}
@Test
public void fail_validate_url_when_body_is_empty() {
server.enqueue(new MockResponse().setResponseCode(404).setBody(""));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(BitbucketServerException.class)
.hasMessage("Error 404. The requested Bitbucket server is unreachable.")
.extracting(e -> ((BitbucketServerException) e).getHttpStatus()).isEqualTo(404);
}
@Test
public void fail_validate_url_when_validate_url_return_non_json_payload() {
server.enqueue(new MockResponse().setResponseCode(400)
.setBody("this is not a json payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
}
@Test
public void fail_validate_url_when_returning_non_json_payload_with_a_200_code() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody("this is not a json payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unexpected response from Bitbucket server");
assertThat(String.join(", ", logTester.logs()))
.contains("Unexpected response from Bitbucket server : [this is not a json payload]");
}
@Test
public void fail_validate_token_when_server_return_non_json_payload() {
server.enqueue(new MockResponse().setResponseCode(400)
.setBody("this is not a json payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateToken(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
}
@Test
public void fail_validate_token_when_returning_non_json_payload_with_a_200_code() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody("this is not a json payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateToken(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unexpected response from Bitbucket server");
assertThat(String.join(", ", logTester.logs()))
.contains("Unexpected response from Bitbucket server : [this is not a json payload]");
}
@Test
public void fail_validate_token_when_using_an_invalid_token() {
server.enqueue(new MockResponse().setResponseCode(401)
.setBody("com.atlassian.bitbucket.AuthorisationException You are not permitted to access this resource"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateToken(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
}
@Test
public void fail_validate_read_permission_when_server_return_non_json_payload() {
server.enqueue(new MockResponse().setResponseCode(400)
.setBody("this is not a json payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateReadPermission(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Bitbucket server");
}
@Test
public void fail_validate_read_permission_when_returning_non_json_payload_with_a_200_code() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody("this is not a json payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateReadPermission(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unexpected response from Bitbucket server");
assertThat(String.join(", ", logTester.logs()))
.contains("Unexpected response from Bitbucket server : [this is not a json payload]");
}
@Test
public void fail_validate_read_permission_when_permissions_are_not_granted() {
server.enqueue(new MockResponse().setResponseCode(401)
.setBody("com.atlassian.bitbucket.AuthorisationException You are not permitted to access this resource"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateReadPermission(serverUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
}
@Test
public void check_mediaTypes_equality() {
assertThat(underTest.equals(null, null)).isFalse();
assertThat(underTest.equals(MediaType.parse("application/json"), null)).isFalse();
assertThat(underTest.equals(null, MediaType.parse("application/json"))).isFalse();
assertThat(underTest.equals(MediaType.parse("application/ json"), MediaType.parse("text/html; charset=UTF-8"))).isFalse();
assertThat(underTest.equals(MediaType.parse("application/Json"), MediaType.parse("application/JSON"))).isTrue();
}
}
| 26,277 | 37.530792 | 134 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BitbucketServerSettingsValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.alm.setting.ALM;
import org.sonar.db.alm.setting.AlmSettingDto;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class BitbucketServerSettingsValidatorTest {
private static final Encryption encryption = mock(Encryption.class);
private static final Settings settings = mock(Settings.class);
private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class);
private final BitbucketServerSettingsValidator underTest = new BitbucketServerSettingsValidator(bitbucketServerRestClient, settings);
@BeforeClass
public static void setUp() {
when(settings.getEncryption()).thenReturn(encryption);
}
@Test
public void validate_success() {
AlmSettingDto almSettingDto = createNewBitbucketDto("http://abc.com", "abc");
when(encryption.isEncrypted(any())).thenReturn(false);
underTest.validate(almSettingDto);
verify(bitbucketServerRestClient, times(1)).validateUrl("http://abc.com");
verify(bitbucketServerRestClient, times(1)).validateToken("http://abc.com", "abc");
verify(bitbucketServerRestClient, times(1)).validateReadPermission("http://abc.com", "abc");
}
@Test
public void validate_success_with_encrypted_token() {
String encryptedToken = "abc";
String decryptedToken = "decrypted-token";
AlmSettingDto almSettingDto = createNewBitbucketDto("http://abc.com", encryptedToken);
when(encryption.isEncrypted(encryptedToken)).thenReturn(true);
when(encryption.decrypt(encryptedToken)).thenReturn(decryptedToken);
underTest.validate(almSettingDto);
verify(bitbucketServerRestClient, times(1)).validateUrl("http://abc.com");
verify(bitbucketServerRestClient, times(1)).validateToken("http://abc.com", decryptedToken);
verify(bitbucketServerRestClient, times(1)).validateReadPermission("http://abc.com", decryptedToken);
}
@Test
public void validate_failure_on_incomplete_configuration() {
AlmSettingDto almSettingDto = createNewBitbucketDto(null, "abc");
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void validate_failure_on_bitbucket_server_api_error() {
doThrow(new IllegalArgumentException("error")).when(bitbucketServerRestClient).validateUrl(anyString());
AlmSettingDto almSettingDto = createNewBitbucketDto("http://abc.com", "abc");
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class);
}
private AlmSettingDto createNewBitbucketDto(String url, String pat) {
AlmSettingDto dto = new AlmSettingDto();
dto.setAlm(ALM.BITBUCKET);
dto.setUrl(url);
dto.setPersonalAccessToken(pat);
return dto;
}
}
| 4,135 | 39.54902 | 135 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BranchesListTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.bitbucketserver;
import java.util.Optional;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BranchesListTest {
@Test
public void findDefaultBranch_givenNoBranches_returnEmptyOptional(){
BranchesList branchesList = new BranchesList();
Optional<Branch> defaultBranch = branchesList.findDefaultBranch();
assertThat(defaultBranch).isNotPresent();
}
@Test
public void findDefaultBranch_givenBranchesWithoutDefaultOne_returnEmptyOptional(){
BranchesList branchesList = new BranchesList();
branchesList.addBranch(new Branch("1", false));
branchesList.addBranch(new Branch("2", false));
Optional<Branch> defaultBranch = branchesList.findDefaultBranch();
assertThat(defaultBranch).isNotPresent();
}
@Test
public void findDefaultBranch_givenBranchesWithDefaultOne_returnOptionalWithThisBranch(){
BranchesList branchesList = new BranchesList();
branchesList.addBranch(new Branch("1", false));
branchesList.addBranch(new Branch("2", false));
branchesList.addBranch(new Branch("default", true));
Optional<Branch> defaultBranchOptional = branchesList.findDefaultBranch();
assertThat(defaultBranchOptional).isPresent();
assertThat(defaultBranchOptional.get().isDefault()).isTrue();
assertThat(defaultBranchOptional.get().getName()).isEqualTo("default");
}
}
| 2,255 | 34.809524 | 91 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubApplicationClientImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.alm.client.github.config.GithubAppConfiguration;
import org.sonar.alm.client.github.config.GithubAppInstallation;
import org.sonar.alm.client.github.security.AccessToken;
import org.sonar.alm.client.github.security.AppToken;
import org.sonar.alm.client.github.security.GithubAppSecurity;
import org.sonar.alm.client.github.security.UserAccessToken;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.auth.github.GitHubSettings;
import org.sonarqube.ws.client.HttpException;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class GithubApplicationClientImplTest {
private static final String APP_JWT_TOKEN = "APP_TOKEN_JWT";
private static final String PAYLOAD_2_ORGS = """
[
{
"id": 1,
"account": {
"login": "org1",
"type": "Organization"
},
"target_type": "Organization",
"permissions": {
"members": "read",
"metadata": "read"
},
"suspended_at": "2023-05-30T08:40:55Z"
},
{
"id": 2,
"account": {
"login": "org2",
"type": "Organization"
},
"target_type": "Organization",
"permissions": {
"members": "read",
"metadata": "read"
}
}
]""";
@ClassRule
public static LogTester logTester = new LogTester().setLevel(LoggerLevel.WARN);
private GithubApplicationHttpClientImpl httpClient = mock(GithubApplicationHttpClientImpl.class);
private GithubAppSecurity appSecurity = mock(GithubAppSecurity.class);
private GithubAppConfiguration githubAppConfiguration = mock(GithubAppConfiguration.class);
private GitHubSettings gitHubSettings = mock(GitHubSettings.class);
private GithubApplicationClient underTest;
private String appUrl = "Any URL";
@Before
public void setup() {
when(githubAppConfiguration.getApiEndpoint()).thenReturn(appUrl);
underTest = new GithubApplicationClientImpl(httpClient, appSecurity, gitHubSettings);
logTester.clear();
}
@Test
@UseDataProvider("invalidApiEndpoints")
public void checkApiEndpoint_Invalid(String url, String expectedMessage) {
GithubAppConfiguration configuration = new GithubAppConfiguration(1L, "", url);
assertThatThrownBy(() -> underTest.checkApiEndpoint(configuration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(expectedMessage);
}
@DataProvider
public static Object[][] invalidApiEndpoints() {
return new Object[][] {
{"", "Missing URL"},
{"ftp://api.github.com", "Only http and https schemes are supported"},
{"https://github.com", "Invalid GitHub URL"}
};
}
@Test
@UseDataProvider("validApiEndpoints")
public void checkApiEndpoint(String url) {
GithubAppConfiguration configuration = new GithubAppConfiguration(1L, "", url);
assertThatCode(() -> underTest.checkApiEndpoint(configuration)).isNull();
}
@DataProvider
public static Object[][] validApiEndpoints() {
return new Object[][] {
{"https://github.sonarsource.com/api/v3"},
{"https://api.github.com"},
{"https://github.sonarsource.com/api/v3/"},
{"https://api.github.com/"},
{"HTTPS://api.github.com/"},
{"HTTP://api.github.com/"},
{"HtTpS://github.SonarSource.com/api/v3"},
{"HtTpS://github.sonarsource.com/api/V3"},
{"HtTpS://github.sonarsource.COM/ApI/v3"}
};
}
@Test
public void checkAppPermissions_IOException() throws IOException {
AppToken appToken = mockAppToken();
when(httpClient.get(appUrl, appToken, "/app")).thenThrow(new IOException("OOPS"));
assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Failed to validate configuration, check URL and Private Key");
}
@Test
@UseDataProvider("checkAppPermissionsErrorCodes")
public void checkAppPermissions_ErrorCodes(int errorCode, String expectedMessage) throws IOException {
AppToken appToken = mockAppToken();
when(httpClient.get(appUrl, appToken, "/app")).thenReturn(new ErrorGetResponse(errorCode, null));
assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(expectedMessage);
}
@DataProvider
public static Object[][] checkAppPermissionsErrorCodes() {
return new Object[][] {
{HTTP_UNAUTHORIZED, "Authentication failed, verify the Client Id, Client Secret and Private Key fields"},
{HTTP_FORBIDDEN, "Authentication failed, verify the Client Id, Client Secret and Private Key fields"},
{HTTP_NOT_FOUND, "Failed to check permissions with Github, check the configuration"}
};
}
@Test
public void checkAppPermissions_MissingPermissions() throws IOException {
AppToken appToken = mockAppToken();
when(httpClient.get(appUrl, appToken, "/app")).thenReturn(new OkGetResponse("{}"));
assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Failed to get app permissions, unexpected response body");
}
@Test
public void checkAppPermissions_IncorrectPermissions() throws IOException {
AppToken appToken = mockAppToken();
String json = "{"
+ " \"permissions\": {\n"
+ " \"checks\": \"read\",\n"
+ " \"metadata\": \"read\",\n"
+ " \"pull_requests\": \"read\"\n"
+ " }\n"
+ "}";
when(httpClient.get(appUrl, appToken, "/app")).thenReturn(new OkGetResponse(json));
assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Missing permissions; permission granted on pull_requests is 'read', should be 'write', checks is 'read', should be 'write'");
}
@Test
public void checkAppPermissions() throws IOException {
AppToken appToken = mockAppToken();
String json = "{"
+ " \"permissions\": {\n"
+ " \"checks\": \"write\",\n"
+ " \"metadata\": \"read\",\n"
+ " \"pull_requests\": \"write\"\n"
+ " }\n"
+ "}";
when(httpClient.get(appUrl, appToken, "/app")).thenReturn(new OkGetResponse(json));
assertThatCode(() -> underTest.checkAppPermissions(githubAppConfiguration)).isNull();
}
@Test
@UseDataProvider("githubServers")
public void createUserAccessToken_returns_empty_if_access_token_cant_be_created(String apiUrl, String appUrl) throws IOException {
when(httpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
.thenReturn(new Response(400, null));
assertThatThrownBy(() -> underTest.createUserAccessToken(appUrl, "clientId", "clientSecret", "code"))
.isInstanceOf(IllegalStateException.class);
verify(httpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
}
@Test
@UseDataProvider("githubServers")
public void createUserAccessToken_fail_if_access_token_request_fails(String apiUrl, String appUrl) throws IOException {
when(httpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
.thenThrow(new IOException("OOPS"));
assertThatThrownBy(() -> underTest.createUserAccessToken(apiUrl, "clientId", "clientSecret", "code"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to create GitHub's user access token");
verify(httpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
}
@Test
@UseDataProvider("githubServers")
public void createUserAccessToken_throws_illegal_argument_exception_if_access_token_code_is_expired(String apiUrl, String appUrl) throws IOException {
when(httpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
.thenReturn(new OkGetResponse("error_code=100&error=expired_or_invalid"));
assertThatThrownBy(() -> underTest.createUserAccessToken(apiUrl, "clientId", "clientSecret", "code"))
.isInstanceOf(IllegalArgumentException.class);
verify(httpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
}
@Test
@UseDataProvider("githubServers")
public void createUserAccessToken_from_authorization_code_returns_access_token(String apiUrl, String appUrl) throws IOException {
String token = randomAlphanumeric(10);
when(httpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
.thenReturn(new OkGetResponse("access_token=" + token + "&status="));
UserAccessToken userAccessToken = underTest.createUserAccessToken(apiUrl, "clientId", "clientSecret", "code");
assertThat(userAccessToken)
.extracting(UserAccessToken::getValue, UserAccessToken::getAuthorizationHeaderPrefix)
.containsOnly(token, "token");
verify(httpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
}
@Test
public void getApp_returns_id() throws IOException {
AppToken appToken = new AppToken(APP_JWT_TOKEN);
when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
when(httpClient.get(appUrl, appToken, "/app"))
.thenReturn(new OkGetResponse("{\"installations_count\": 2}"));
assertThat(underTest.getApp(githubAppConfiguration).getInstallationsCount()).isEqualTo(2L);
}
@Test
public void getApp_whenStatusCodeIsNotOk_shouldThrowHttpException() throws IOException {
AppToken appToken = new AppToken(APP_JWT_TOKEN);
when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
when(httpClient.get(appUrl, appToken, "/app"))
.thenReturn(new ErrorGetResponse(418, "I'm a teapot"));
assertThatThrownBy(() -> underTest.getApp(githubAppConfiguration))
.isInstanceOfSatisfying(HttpException.class, httpException -> {
assertThat(httpException.code()).isEqualTo(418);
assertThat(httpException.url()).isEqualTo("Any URL/app");
assertThat(httpException.content()).isEqualTo("I'm a teapot");
});
}
@DataProvider
public static Object[][] githubServers() {
return new Object[][] {
{"https://github.sonarsource.com/api/v3", "https://github.sonarsource.com"},
{"https://api.github.com", "https://github.com"},
{"https://github.sonarsource.com/api/v3/", "https://github.sonarsource.com"},
{"https://api.github.com/", "https://github.com"},
};
}
@Test
public void listOrganizations_fail_on_failure() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
when(httpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100)))
.thenThrow(new IOException("OOPS"));
assertThatThrownBy(() -> underTest.listOrganizations(appUrl, accessToken, 1, 100))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to list all organizations accessible by user access token on %s", appUrl);
}
@Test
public void listOrganizations_fail_if_pageIndex_out_of_bounds() {
UserAccessToken token = new UserAccessToken("token");
assertThatThrownBy(() -> underTest.listOrganizations(appUrl, token, 0, 100))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'page' must be larger than 0.");
}
@Test
public void listOrganizations_fail_if_pageSize_out_of_bounds() {
UserAccessToken token = new UserAccessToken("token");
assertThatThrownBy(() -> underTest.listOrganizations(appUrl, token, 1, 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
assertThatThrownBy(() -> underTest.listOrganizations("", token, 1, 101))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
}
@Test
public void listOrganizations_returns_no_installations() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
String responseJson = "{\n"
+ " \"total_count\": 0\n"
+ "} ";
when(httpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100)))
.thenReturn(new OkGetResponse(responseJson));
GithubApplicationClient.Organizations organizations = underTest.listOrganizations(appUrl, accessToken, 1, 100);
assertThat(organizations.getTotal()).isZero();
assertThat(organizations.getOrganizations()).isNull();
}
@Test
public void listOrganizations_returns_pages_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
String responseJson = "{\n"
+ " \"total_count\": 2,\n"
+ " \"installations\": [\n"
+ " {\n"
+ " \"id\": 1,\n"
+ " \"account\": {\n"
+ " \"login\": \"github\",\n"
+ " \"id\": 1,\n"
+ " \"node_id\": \"MDEyOk9yZ2FuaXphdGlvbjE=\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/orgs/github\",\n"
+ " \"repos_url\": \"https://github.sonarsource.com/api/v3/orgs/github/repos\",\n"
+ " \"events_url\": \"https://github.sonarsource.com/api/v3/orgs/github/events\",\n"
+ " \"hooks_url\": \"https://github.sonarsource.com/api/v3/orgs/github/hooks\",\n"
+ " \"issues_url\": \"https://github.sonarsource.com/api/v3/orgs/github/issues\",\n"
+ " \"members_url\": \"https://github.sonarsource.com/api/v3/orgs/github/members{/member}\",\n"
+ " \"public_members_url\": \"https://github.sonarsource.com/api/v3/orgs/github/public_members{/member}\",\n"
+ " \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n"
+ " \"description\": \"A great organization\"\n"
+ " },\n"
+ " \"access_tokens_url\": \"https://github.sonarsource.com/api/v3/app/installations/1/access_tokens\",\n"
+ " \"repositories_url\": \"https://github.sonarsource.com/api/v3/installation/repositories\",\n"
+ " \"html_url\": \"https://github.com/organizations/github/settings/installations/1\",\n"
+ " \"app_id\": 1,\n"
+ " \"target_id\": 1,\n"
+ " \"target_type\": \"Organization\",\n"
+ " \"permissions\": {\n"
+ " \"checks\": \"write\",\n"
+ " \"metadata\": \"read\",\n"
+ " \"contents\": \"read\"\n"
+ " },\n"
+ " \"events\": [\n"
+ " \"push\",\n"
+ " \"pull_request\"\n"
+ " ],\n"
+ " \"single_file_name\": \"config.yml\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": 3,\n"
+ " \"account\": {\n"
+ " \"login\": \"octocat\",\n"
+ " \"id\": 2,\n"
+ " \"node_id\": \"MDQ6VXNlcjE=\",\n"
+ " \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n"
+ " \"gravatar_id\": \"\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n"
+ " \"html_url\": \"https://github.com/octocat\",\n"
+ " \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n"
+ " \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n"
+ " \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n"
+ " \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n"
+ " \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n"
+ " \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n"
+ " \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n"
+ " \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n"
+ " \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n"
+ " \"type\": \"User\",\n"
+ " \"site_admin\": false\n"
+ " },\n"
+ " \"access_tokens_url\": \"https://github.sonarsource.com/api/v3/app/installations/1/access_tokens\",\n"
+ " \"repositories_url\": \"https://github.sonarsource.com/api/v3/installation/repositories\",\n"
+ " \"html_url\": \"https://github.com/organizations/github/settings/installations/1\",\n"
+ " \"app_id\": 1,\n"
+ " \"target_id\": 1,\n"
+ " \"target_type\": \"Organization\",\n"
+ " \"permissions\": {\n"
+ " \"checks\": \"write\",\n"
+ " \"metadata\": \"read\",\n"
+ " \"contents\": \"read\"\n"
+ " },\n"
+ " \"events\": [\n"
+ " \"push\",\n"
+ " \"pull_request\"\n"
+ " ],\n"
+ " \"single_file_name\": \"config.yml\"\n"
+ " }\n"
+ " ]\n"
+ "} ";
when(httpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100)))
.thenReturn(new OkGetResponse(responseJson));
GithubApplicationClient.Organizations organizations = underTest.listOrganizations(appUrl, accessToken, 1, 100);
assertThat(organizations.getTotal()).isEqualTo(2);
assertThat(organizations.getOrganizations()).extracting(GithubApplicationClient.Organization::getLogin).containsOnly("github", "octocat");
}
@Test
public void getWhitelistedGithubAppInstallations_whenWhitelistNotSpecified_doesNotFilter() throws IOException {
List<GithubAppInstallation> allOrgInstallations = getGithubAppInstallationsFromGithubResponse(PAYLOAD_2_ORGS);
assertOrgDeserialization(allOrgInstallations);
}
private static void assertOrgDeserialization(List<GithubAppInstallation> orgs) {
GithubAppInstallation org1 = orgs.get(0);
assertThat(org1.installationId()).isEqualTo("1");
assertThat(org1.organizationName()).isEqualTo("org1");
assertThat(org1.permissions().getMembers()).isEqualTo("read");
assertThat(org1.isSuspended()).isTrue();
GithubAppInstallation org2 = orgs.get(1);
assertThat(org2.installationId()).isEqualTo("2");
assertThat(org2.organizationName()).isEqualTo("org2");
assertThat(org2.permissions().getMembers()).isEqualTo("read");
assertThat(org2.isSuspended()).isFalse();
}
@Test
public void getWhitelistedGithubAppInstallations_whenWhitelistSpecified_filtersWhitelistedOrgs() throws IOException {
when(gitHubSettings.getOrganizations()).thenReturn(Set.of("org2"));
List<GithubAppInstallation> orgInstallations = getGithubAppInstallationsFromGithubResponse(PAYLOAD_2_ORGS);
assertThat(orgInstallations)
.hasSize(1)
.extracting(GithubAppInstallation::organizationName)
.containsExactlyInAnyOrder("org2");
}
@Test
public void getWhitelistedGithubAppInstallations_whenEmptyResponse_shouldReturnEmpty() throws IOException {
List<GithubAppInstallation> allOrgInstallations = getGithubAppInstallationsFromGithubResponse("[]");
assertThat(allOrgInstallations).isEmpty();
}
@Test
public void getWhitelistedGithubAppInstallations_whenNoOrganization_shouldReturnEmpty() throws IOException {
List<GithubAppInstallation> allOrgInstallations = getGithubAppInstallationsFromGithubResponse("""
[
{
"id": 1,
"account": {
"login": "user1",
"type": "User"
},
"target_type": "User",
"permissions": {
"metadata": "read"
}
}
]""");
assertThat(allOrgInstallations).isEmpty();
}
private List<GithubAppInstallation> getGithubAppInstallationsFromGithubResponse(String content) throws IOException {
AppToken appToken = new AppToken(APP_JWT_TOKEN);
when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
when(httpClient.get(appUrl, appToken, "/app/installations"))
.thenReturn(new OkGetResponse(content));
return underTest.getWhitelistedGithubAppInstallations(githubAppConfiguration);
}
@Test
public void getWhitelistedGithubAppInstallations_whenGithubReturnsError_shouldThrow() throws IOException {
AppToken appToken = new AppToken(APP_JWT_TOKEN);
when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
when(httpClient.get(appUrl, appToken, "/app/installations"))
.thenReturn(new ErrorGetResponse());
assertThatThrownBy(() -> underTest.getWhitelistedGithubAppInstallations(githubAppConfiguration))
.isInstanceOf(IllegalStateException.class)
.hasMessage("An error occurred when retrieving your GitHup App installations. "
+ "It might be related to your GitHub App configuration or a connectivity problem.");
}
@Test
public void listRepositories_fail_on_failure() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
when(httpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "org:test", 1, 100)))
.thenThrow(new IOException("OOPS"));
assertThatThrownBy(() -> underTest.listRepositories(appUrl, accessToken, "test", null, 1, 100))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to list all repositories of 'test' accessible by user access token on 'https://github.sonarsource.com' using query 'fork:true+org:test'");
}
@Test
public void listRepositories_fail_if_pageIndex_out_of_bounds() {
UserAccessToken token = new UserAccessToken("token");
assertThatThrownBy(() -> underTest.listRepositories(appUrl, token, "test", null, 0, 100))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'page' must be larger than 0.");
}
@Test
public void listRepositories_fail_if_pageSize_out_of_bounds() {
UserAccessToken token = new UserAccessToken("token");
assertThatThrownBy(() -> underTest.listRepositories(appUrl, token, "test", null, 1, 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
assertThatThrownBy(() -> underTest.listRepositories("", token, "test", null, 1, 101))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
}
@Test
public void listRepositories_returns_empty_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
String responseJson = "{\n"
+ " \"total_count\": 0\n"
+ "}";
when(httpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "fork:true+org:github", 1, 100)))
.thenReturn(new OkGetResponse(responseJson));
GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", null, 1, 100);
assertThat(repositories.getTotal()).isZero();
assertThat(repositories.getRepositories()).isNull();
}
@Test
public void listRepositories_returns_pages_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
String responseJson = "{\n"
+ " \"total_count\": 2,\n"
+ " \"incomplete_results\": false,\n"
+ " \"items\": [\n"
+ " {\n"
+ " \"id\": 3081286,\n"
+ " \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n"
+ " \"name\": \"HelloWorld\",\n"
+ " \"full_name\": \"github/HelloWorld\",\n"
+ " \"owner\": {\n"
+ " \"login\": \"github\",\n"
+ " \"id\": 872147,\n"
+ " \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n"
+ " \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
+ " \"gravatar_id\": \"\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n"
+ " \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n"
+ " \"type\": \"User\"\n"
+ " },\n"
+ " \"private\": false,\n"
+ " \"html_url\": \"https://github.com/github/HelloWorld\",\n"
+ " \"description\": \"A C implementation of HelloWorld\",\n"
+ " \"fork\": false,\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloWorld\",\n"
+ " \"created_at\": \"2012-01-01T00:31:50Z\",\n"
+ " \"updated_at\": \"2013-01-05T17:58:47Z\",\n"
+ " \"pushed_at\": \"2012-01-01T00:37:02Z\",\n"
+ " \"homepage\": \"\",\n"
+ " \"size\": 524,\n"
+ " \"stargazers_count\": 1,\n"
+ " \"watchers_count\": 1,\n"
+ " \"language\": \"Assembly\",\n"
+ " \"forks_count\": 0,\n"
+ " \"open_issues_count\": 0,\n"
+ " \"master_branch\": \"master\",\n"
+ " \"default_branch\": \"master\",\n"
+ " \"score\": 1.0\n"
+ " },\n"
+ " {\n"
+ " \"id\": 3081286,\n"
+ " \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n"
+ " \"name\": \"HelloUniverse\",\n"
+ " \"full_name\": \"github/HelloUniverse\",\n"
+ " \"owner\": {\n"
+ " \"login\": \"github\",\n"
+ " \"id\": 872147,\n"
+ " \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n"
+ " \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
+ " \"gravatar_id\": \"\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n"
+ " \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n"
+ " \"type\": \"User\"\n"
+ " },\n"
+ " \"private\": false,\n"
+ " \"html_url\": \"https://github.com/github/HelloUniverse\",\n"
+ " \"description\": \"A C implementation of HelloUniverse\",\n"
+ " \"fork\": false,\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloUniverse\",\n"
+ " \"created_at\": \"2012-01-01T00:31:50Z\",\n"
+ " \"updated_at\": \"2013-01-05T17:58:47Z\",\n"
+ " \"pushed_at\": \"2012-01-01T00:37:02Z\",\n"
+ " \"homepage\": \"\",\n"
+ " \"size\": 524,\n"
+ " \"stargazers_count\": 1,\n"
+ " \"watchers_count\": 1,\n"
+ " \"language\": \"Assembly\",\n"
+ " \"forks_count\": 0,\n"
+ " \"open_issues_count\": 0,\n"
+ " \"master_branch\": \"master\",\n"
+ " \"default_branch\": \"master\",\n"
+ " \"score\": 1.0\n"
+ " }\n"
+ " ]\n"
+ "}";
when(httpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "fork:true+org:github", 1, 100)))
.thenReturn(new OkGetResponse(responseJson));
GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", null, 1, 100);
assertThat(repositories.getTotal()).isEqualTo(2);
assertThat(repositories.getRepositories())
.extracting(GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName)
.containsOnly(tuple("HelloWorld", "github/HelloWorld"), tuple("HelloUniverse", "github/HelloUniverse"));
}
@Test
public void listRepositories_returns_search_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
String responseJson = "{\n"
+ " \"total_count\": 2,\n"
+ " \"incomplete_results\": false,\n"
+ " \"items\": [\n"
+ " {\n"
+ " \"id\": 3081286,\n"
+ " \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n"
+ " \"name\": \"HelloWorld\",\n"
+ " \"full_name\": \"github/HelloWorld\",\n"
+ " \"owner\": {\n"
+ " \"login\": \"github\",\n"
+ " \"id\": 872147,\n"
+ " \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n"
+ " \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
+ " \"gravatar_id\": \"\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n"
+ " \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n"
+ " \"type\": \"User\"\n"
+ " },\n"
+ " \"private\": false,\n"
+ " \"html_url\": \"https://github.com/github/HelloWorld\",\n"
+ " \"description\": \"A C implementation of HelloWorld\",\n"
+ " \"fork\": false,\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloWorld\",\n"
+ " \"created_at\": \"2012-01-01T00:31:50Z\",\n"
+ " \"updated_at\": \"2013-01-05T17:58:47Z\",\n"
+ " \"pushed_at\": \"2012-01-01T00:37:02Z\",\n"
+ " \"homepage\": \"\",\n"
+ " \"size\": 524,\n"
+ " \"stargazers_count\": 1,\n"
+ " \"watchers_count\": 1,\n"
+ " \"language\": \"Assembly\",\n"
+ " \"forks_count\": 0,\n"
+ " \"open_issues_count\": 0,\n"
+ " \"master_branch\": \"master\",\n"
+ " \"default_branch\": \"master\",\n"
+ " \"score\": 1.0\n"
+ " }\n"
+ " ]\n"
+ "}";
when(httpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "world+fork:true+org:github", 1, 100)))
.thenReturn(new GithubApplicationHttpClient.GetResponse() {
@Override
public Optional<String> getNextEndPoint() {
return Optional.empty();
}
@Override
public int getCode() {
return 200;
}
@Override
public Optional<String> getContent() {
return Optional.of(responseJson);
}
});
GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", "world", 1, 100);
assertThat(repositories.getTotal()).isEqualTo(2);
assertThat(repositories.getRepositories())
.extracting(GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName)
.containsOnly(tuple("HelloWorld", "github/HelloWorld"));
}
@Test
public void getRepository_returns_empty_when_repository_doesnt_exist() throws IOException {
when(httpClient.get(any(), any(), any()))
.thenReturn(new Response(404, null));
Optional<GithubApplicationClient.Repository> repository = underTest.getRepository(appUrl, new UserAccessToken("temp"), "octocat", "octocat/Hello-World");
assertThat(repository).isEmpty();
}
@Test
public void getRepository_fails_on_failure() throws IOException {
String repositoryKey = "octocat/Hello-World";
String organization = "octocat";
when(httpClient.get(any(), any(), any()))
.thenThrow(new IOException("OOPS"));
UserAccessToken token = new UserAccessToken("temp");
assertThatThrownBy(() -> underTest.getRepository(appUrl, token, organization, repositoryKey))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to get repository '%s' of '%s' accessible by user access token on '%s'", repositoryKey, organization, appUrl);
}
@Test
public void getRepository_returns_repository() throws IOException {
String appUrl = "https://github.sonarsource.com";
AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
String responseJson = "{\n"
+ " \"id\": 1296269,\n"
+ " \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n"
+ " \"name\": \"Hello-World\",\n"
+ " \"full_name\": \"octocat/Hello-World\",\n"
+ " \"owner\": {\n"
+ " \"login\": \"octocat\",\n"
+ " \"id\": 1,\n"
+ " \"node_id\": \"MDQ6VXNlcjE=\",\n"
+ " \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
+ " \"gravatar_id\": \"\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n"
+ " \"html_url\": \"https://github.com/octocat\",\n"
+ " \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n"
+ " \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n"
+ " \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n"
+ " \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n"
+ " \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n"
+ " \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n"
+ " \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n"
+ " \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n"
+ " \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n"
+ " \"type\": \"User\",\n"
+ " \"site_admin\": false\n"
+ " },\n"
+ " \"private\": false,\n"
+ " \"html_url\": \"https://github.com/octocat/Hello-World\",\n"
+ " \"description\": \"This your first repo!\",\n"
+ " \"fork\": false,\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World\",\n"
+ " \"archive_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/{archive_format}{/ref}\",\n"
+ " \"assignees_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/assignees{/user}\",\n"
+ " \"blobs_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/blobs{/sha}\",\n"
+ " \"branches_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/branches{/branch}\",\n"
+ " \"collaborators_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/collaborators{/collaborator}\",\n"
+ " \"comments_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/comments{/number}\",\n"
+ " \"commits_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/commits{/sha}\",\n"
+ " \"compare_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/compare/{base}...{head}\",\n"
+ " \"contents_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/contents/{+path}\",\n"
+ " \"contributors_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/contributors\",\n"
+ " \"deployments_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/deployments\",\n"
+ " \"downloads_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/downloads\",\n"
+ " \"events_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/events\",\n"
+ " \"forks_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/forks\",\n"
+ " \"git_commits_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/commits{/sha}\",\n"
+ " \"git_refs_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/refs{/sha}\",\n"
+ " \"git_tags_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/tags{/sha}\",\n"
+ " \"git_url\": \"git:github.com/octocat/Hello-World.git\",\n"
+ " \"issue_comment_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/issues/comments{/number}\",\n"
+ " \"issue_events_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/issues/events{/number}\",\n"
+ " \"issues_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/issues{/number}\",\n"
+ " \"keys_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/keys{/key_id}\",\n"
+ " \"labels_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/labels{/name}\",\n"
+ " \"languages_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/languages\",\n"
+ " \"merges_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/merges\",\n"
+ " \"milestones_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/milestones{/number}\",\n"
+ " \"notifications_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/notifications{?since,all,participating}\",\n"
+ " \"pulls_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/pulls{/number}\",\n"
+ " \"releases_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/releases{/id}\",\n"
+ " \"ssh_url\": \"git@github.com:octocat/Hello-World.git\",\n"
+ " \"stargazers_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/stargazers\",\n"
+ " \"statuses_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/statuses/{sha}\",\n"
+ " \"subscribers_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/subscribers\",\n"
+ " \"subscription_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/subscription\",\n"
+ " \"tags_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/tags\",\n"
+ " \"teams_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/teams\",\n"
+ " \"trees_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/trees{/sha}\",\n"
+ " \"clone_url\": \"https://github.com/octocat/Hello-World.git\",\n"
+ " \"mirror_url\": \"git:git.example.com/octocat/Hello-World\",\n"
+ " \"hooks_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/hooks\",\n"
+ " \"svn_url\": \"https://svn.github.com/octocat/Hello-World\",\n"
+ " \"homepage\": \"https://github.com\",\n"
+ " \"language\": null,\n"
+ " \"forks_count\": 9,\n"
+ " \"stargazers_count\": 80,\n"
+ " \"watchers_count\": 80,\n"
+ " \"size\": 108,\n"
+ " \"default_branch\": \"master\",\n"
+ " \"open_issues_count\": 0,\n"
+ " \"is_template\": true,\n"
+ " \"topics\": [\n"
+ " \"octocat\",\n"
+ " \"atom\",\n"
+ " \"electron\",\n"
+ " \"api\"\n"
+ " ],\n"
+ " \"has_issues\": true,\n"
+ " \"has_projects\": true,\n"
+ " \"has_wiki\": true,\n"
+ " \"has_pages\": false,\n"
+ " \"has_downloads\": true,\n"
+ " \"archived\": false,\n"
+ " \"disabled\": false,\n"
+ " \"visibility\": \"public\",\n"
+ " \"pushed_at\": \"2011-01-26T19:06:43Z\",\n"
+ " \"created_at\": \"2011-01-26T19:01:12Z\",\n"
+ " \"updated_at\": \"2011-01-26T19:14:43Z\",\n"
+ " \"permissions\": {\n"
+ " \"admin\": false,\n"
+ " \"push\": false,\n"
+ " \"pull\": true\n"
+ " },\n"
+ " \"allow_rebase_merge\": true,\n"
+ " \"template_repository\": null,\n"
+ " \"allow_squash_merge\": true,\n"
+ " \"allow_merge_commit\": true,\n"
+ " \"subscribers_count\": 42,\n"
+ " \"network_count\": 0,\n"
+ " \"anonymous_access_enabled\": false,\n"
+ " \"license\": {\n"
+ " \"key\": \"mit\",\n"
+ " \"name\": \"MIT License\",\n"
+ " \"spdx_id\": \"MIT\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/licenses/mit\",\n"
+ " \"node_id\": \"MDc6TGljZW5zZW1pdA==\"\n"
+ " },\n"
+ " \"organization\": {\n"
+ " \"login\": \"octocat\",\n"
+ " \"id\": 1,\n"
+ " \"node_id\": \"MDQ6VXNlcjE=\",\n"
+ " \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n"
+ " \"gravatar_id\": \"\",\n"
+ " \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n"
+ " \"html_url\": \"https://github.com/octocat\",\n"
+ " \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n"
+ " \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n"
+ " \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n"
+ " \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n"
+ " \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n"
+ " \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n"
+ " \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n"
+ " \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n"
+ " \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n"
+ " \"type\": \"Organization\",\n"
+ " \"site_admin\": false\n"
+ " }"
+ "}";
when(httpClient.get(appUrl, accessToken, "/repos/octocat/Hello-World"))
.thenReturn(new GithubApplicationHttpClient.GetResponse() {
@Override
public Optional<String> getNextEndPoint() {
return Optional.empty();
}
@Override
public int getCode() {
return 200;
}
@Override
public Optional<String> getContent() {
return Optional.of(responseJson);
}
});
Optional<GithubApplicationClient.Repository> repository = underTest.getRepository(appUrl, accessToken, "octocat", "octocat/Hello-World");
assertThat(repository)
.isPresent()
.get()
.extracting(GithubApplicationClient.Repository::getId, GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName,
GithubApplicationClient.Repository::getUrl, GithubApplicationClient.Repository::isPrivate, GithubApplicationClient.Repository::getDefaultBranch)
.containsOnly(1296269L, "Hello-World", "octocat/Hello-World", "https://github.com/octocat/Hello-World", false, "master");
}
private AppToken mockAppToken() {
String jwt = randomAlphanumeric(5);
when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(new AppToken(jwt));
return new AppToken(jwt);
}
private static class OkGetResponse extends Response {
private OkGetResponse(String content) {
super(200, content);
}
}
private static class ErrorGetResponse extends Response {
ErrorGetResponse() {
super(401, null);
}
ErrorGetResponse(int code, String content) {
super(code, content);
}
}
private static class Response implements GithubApplicationHttpClient.GetResponse {
private final int code;
private final String content;
private final String nextEndPoint;
private Response(int code, @Nullable String content) {
this(code, content, null);
}
private Response(int code, @Nullable String content, @Nullable String nextEndPoint) {
this.code = code;
this.content = content;
this.nextEndPoint = nextEndPoint;
}
@Override
public int getCode() {
return code;
}
@Override
public Optional<String> getContent() {
return Optional.ofNullable(content);
}
@Override
public Optional<String> getNextEndPoint() {
return Optional.ofNullable(nextEndPoint);
}
}
}
| 47,132 | 46.705466 | 164 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubApplicationHttpClientImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.IOException;
import java.net.SocketTimeoutException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.event.Level;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.alm.client.github.GithubApplicationHttpClient.GetResponse;
import org.sonar.alm.client.github.GithubApplicationHttpClient.Response;
import org.sonar.alm.client.github.security.AccessToken;
import org.sonar.alm.client.github.security.UserAccessToken;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.lang.String.format;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
@RunWith(DataProviderRunner.class)
public class GithubApplicationHttpClientImplTest {
private static final String GH_API_VERSION_HEADER = "X-GitHub-Api-Version";
private static final String GH_API_VERSION = "2022-11-28";
@Rule
public MockWebServer server = new MockWebServer();
@ClassRule
public static LogTester logTester = new LogTester().setLevel(LoggerLevel.WARN);
private GithubApplicationHttpClientImpl underTest;
private final AccessToken accessToken = new UserAccessToken(randomAlphabetic(10));
private final String randomEndPoint = "/" + randomAlphabetic(10);
private final String randomBody = randomAlphabetic(40);
private String appUrl;
@Before
public void setUp() {
this.appUrl = format("http://%s:%s", server.getHostName(), server.getPort());
this.underTest = new GithubApplicationHttpClientImpl(new ConstantTimeoutConfiguration(500));
logTester.clear();
}
@Test
public void get_fails_if_endpoint_does_not_start_with_slash() throws IOException {
assertThatThrownBy(() -> underTest.get(appUrl, accessToken, "api/foo/bar"))
.hasMessage("endpoint must start with '/' or 'http'")
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void get_fails_if_endpoint_does_not_start_with_http() throws IOException {
assertThatThrownBy(() -> underTest.get(appUrl, accessToken, "ttp://api/foo/bar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("endpoint must start with '/' or 'http'");
}
@Test
public void get_fails_if_github_endpoint_is_invalid() throws IOException {
assertThatThrownBy(() -> underTest.get("invalidUrl", accessToken, "/endpoint"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalidUrl/endpoint is not a valid url");
}
@Test
public void getSilent_no_log_if_code_is_not_200() throws IOException {
server.enqueue(new MockResponse().setResponseCode(403));
GetResponse response = underTest.getSilent(appUrl, accessToken, randomEndPoint);
assertThat(logTester.logs()).isEmpty();
assertThat(response.getContent()).isEmpty();
}
@Test
public void get_log_if_code_is_not_200() throws IOException {
server.enqueue(new MockResponse().setResponseCode(403));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(logTester.logs(Level.WARN)).isNotEmpty();
assertThat(response.getContent()).isEmpty();
}
@Test
public void get_adds_authentication_header_with_Bearer_type_and_Accept_header() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response).isNotNull();
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo("GET");
assertThat(recordedRequest.getPath()).isEqualTo(randomEndPoint);
assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("token " + accessToken.getValue());
assertThat(recordedRequest.getHeader(GH_API_VERSION_HEADER)).isEqualTo(GH_API_VERSION);
}
@Test
public void get_returns_body_as_response_if_code_is_200() throws IOException {
server.enqueue(new MockResponse().setResponseCode(200).setBody(randomBody));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).contains(randomBody);
}
@Test
public void get_timeout() {
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
try {
underTest.get(appUrl, accessToken, randomEndPoint);
fail("Expected timeout");
} catch (Exception e) {
assertThat(e).isInstanceOf(SocketTimeoutException.class);
}
}
@Test
@UseDataProvider("someHttpCodesWithContentBut200")
public void get_empty_response_if_code_is_not_200(int code) throws IOException {
server.enqueue(new MockResponse().setResponseCode(code).setBody(randomBody));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).contains(randomBody);
}
@Test
public void get_returns_empty_endPoint_when_no_link_header() throws IOException {
server.enqueue(new MockResponse().setBody(randomBody));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response.getNextEndPoint()).isEmpty();
}
@Test
public void get_returns_empty_endPoint_when_link_header_does_not_have_next_rel() throws IOException {
server.enqueue(new MockResponse().setBody(randomBody)
.setHeader("link", "<https://api.github.com/installation/repositories?per_page=5&page=4>; rel=\"prev\", " +
"<https://api.github.com/installation/repositories?per_page=5&page=1>; rel=\"first\""));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response.getNextEndPoint()).isEmpty();
}
@Test
@UseDataProvider("linkHeadersWithNextRel")
public void get_returns_endPoint_when_link_header_has_next_rel(String linkHeader) throws IOException {
server.enqueue(new MockResponse().setBody(randomBody)
.setHeader("link", linkHeader));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response.getNextEndPoint()).contains("https://api.github.com/installation/repositories?per_page=5&page=2");
}
@Test
public void get_returns_endPoint_when_link_header_has_next_rel_different_case() throws IOException {
String linkHeader = "<https://api.github.com/installation/repositories?per_page=5&page=2>; rel=\"next\"";
server.enqueue(new MockResponse().setBody(randomBody)
.setHeader("Link", linkHeader));
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
assertThat(response.getNextEndPoint()).contains("https://api.github.com/installation/repositories?per_page=5&page=2");
}
@DataProvider
public static Object[][] linkHeadersWithNextRel() {
String expected = "https://api.github.com/installation/repositories?per_page=5&page=2";
return new Object[][] {
{"<" + expected + ">; rel=\"next\""},
{"<" + expected + ">; rel=\"next\", " +
"<https://api.github.com/installation/repositories?per_page=5&page=1>; rel=\"first\""},
{"<https://api.github.com/installation/repositories?per_page=5&page=1>; rel=\"first\", " +
"<" + expected + ">; rel=\"next\""},
{"<https://api.github.com/installation/repositories?per_page=5&page=1>; rel=\"first\", " +
"<" + expected + ">; rel=\"next\", " +
"<https://api.github.com/installation/repositories?per_page=5&page=5>; rel=\"last\""},
};
}
@DataProvider
public static Object[][] someHttpCodesWithContentBut200() {
return new Object[][] {
{201},
{202},
{203},
{404},
{500}
};
}
@Test
public void post_fails_if_endpoint_does_not_start_with_slash() throws IOException {
assertThatThrownBy(() -> underTest.post(appUrl, accessToken, "api/foo/bar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("endpoint must start with '/' or 'http'");
}
@Test
public void post_fails_if_endpoint_does_not_start_with_http() throws IOException {
assertThatThrownBy(() -> underTest.post(appUrl, accessToken, "ttp://api/foo/bar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("endpoint must start with '/' or 'http'");
}
@Test
public void post_fails_if_github_endpoint_is_invalid() throws IOException {
assertThatThrownBy(() -> underTest.post("invalidUrl", accessToken, "/endpoint"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalidUrl/endpoint is not a valid url");
}
@Test
public void post_adds_authentication_header_with_Bearer_type_and_Accept_header() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
Response response = underTest.post(appUrl, accessToken, randomEndPoint);
assertThat(response).isNotNull();
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo("POST");
assertThat(recordedRequest.getPath()).isEqualTo(randomEndPoint);
assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("token " + accessToken.getValue());
assertThat(recordedRequest.getHeader(GH_API_VERSION_HEADER)).isEqualTo(GH_API_VERSION);
}
@Test
@DataProvider({"200", "201", "202"})
public void post_returns_body_as_response_if_success(int code) throws IOException {
server.enqueue(new MockResponse().setResponseCode(code).setBody(randomBody));
Response response = underTest.post(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).contains(randomBody);
}
@Test
public void post_returns_empty_response_if_code_is_204() throws IOException {
server.enqueue(new MockResponse().setResponseCode(204));
Response response = underTest.post(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).isEmpty();
}
@Test
@UseDataProvider("httpCodesBut200_201And204")
public void post_has_json_error_in_body_if_code_is_neither_200_201_nor_204(int code) throws IOException {
server.enqueue(new MockResponse().setResponseCode(code).setBody(randomBody));
Response response = underTest.post(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).contains(randomBody);
}
@DataProvider
public static Object[][] httpCodesBut200_201And204() {
return new Object[][] {
{202},
{203},
{400},
{401},
{403},
{404},
{500}
};
}
@Test
public void post_with_json_body_adds_json_to_body_request() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
String jsonBody = "{\"foo\": \"bar\"}";
Response response = underTest.post(appUrl, accessToken, randomEndPoint, jsonBody);
assertThat(response).isNotNull();
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getBody().readUtf8()).isEqualTo(jsonBody);
}
@Test
public void patch_with_json_body_adds_json_to_body_request() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
String jsonBody = "{\"foo\": \"bar\"}";
Response response = underTest.patch(appUrl, accessToken, randomEndPoint, jsonBody);
assertThat(response).isNotNull();
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getBody().readUtf8()).isEqualTo(jsonBody);
}
@Test
public void patch_returns_body_as_response_if_code_is_200() throws IOException {
server.enqueue(new MockResponse().setResponseCode(200).setBody(randomBody));
Response response = underTest.patch(appUrl, accessToken, randomEndPoint, "{}");
assertThat(response.getContent()).contains(randomBody);
}
@Test
public void patch_returns_empty_response_if_code_is_204() throws IOException {
server.enqueue(new MockResponse().setResponseCode(204));
Response response = underTest.patch(appUrl, accessToken, randomEndPoint, "{}");
assertThat(response.getContent()).isEmpty();
}
@Test
public void delete_returns_empty_response_if_code_is_204() throws IOException {
server.enqueue(new MockResponse().setResponseCode(204));
Response response = underTest.delete(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).isEmpty();
}
@DataProvider
public static Object[][] httpCodesBut204() {
return new Object[][] {
{200},
{201},
{202},
{203},
{400},
{401},
{403},
{404},
{500}
};
}
@Test
@UseDataProvider("httpCodesBut204")
public void delete_returns_response_if_code_is_not_204(int code) throws IOException {
server.enqueue(new MockResponse().setResponseCode(code).setBody(randomBody));
Response response = underTest.delete(appUrl, accessToken, randomEndPoint);
assertThat(response.getContent()).hasValue(randomBody);
}
@DataProvider
public static Object[][] httpCodesBut200And204() {
return new Object[][] {
{201},
{202},
{203},
{400},
{401},
{403},
{404},
{500}
};
}
@Test
@UseDataProvider("httpCodesBut200And204")
public void patch_has_json_error_in_body_if_code_is_neither_200_nor_204(int code) throws IOException {
server.enqueue(new MockResponse().setResponseCode(code).setBody(randomBody));
Response response = underTest.patch(appUrl, accessToken, randomEndPoint, "{}");
assertThat(response.getContent()).contains(randomBody);
}
}
| 14,867 | 35.352078 | 125 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubGlobalSettingsValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import javax.annotation.Nullable;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.alm.client.github.config.GithubAppConfiguration;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.alm.setting.ALM;
import org.sonar.db.alm.setting.AlmSettingDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GithubGlobalSettingsValidatorTest {
private static final Encryption encryption = mock(Encryption.class);
private static final Settings settings = mock(Settings.class);
private static final String EXAMPLE_APP_ID = "123";
private static final String EXAMPLE_PRIVATE_KEY = "private_key";
private final GithubApplicationClientImpl appClient = mock(GithubApplicationClientImpl.class);
private final GithubGlobalSettingsValidator underTest = new GithubGlobalSettingsValidator(appClient, settings);
@BeforeClass
public static void setUp() {
when(settings.getEncryption()).thenReturn(encryption);
}
@Test
public void github_global_settings_validation() {
AlmSettingDto almSettingDto = createNewGithubDto("clientId", "clientSecret", EXAMPLE_APP_ID, EXAMPLE_PRIVATE_KEY);
when(encryption.isEncrypted(any())).thenReturn(false);
GithubAppConfiguration configuration = underTest.validate(almSettingDto);
ArgumentCaptor<GithubAppConfiguration> configurationArgumentCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
verify(appClient).checkApiEndpoint(configurationArgumentCaptor.capture());
verify(appClient).checkAppPermissions(configurationArgumentCaptor.capture());
assertThat(configuration.getId()).isEqualTo(configurationArgumentCaptor.getAllValues().get(0).getId());
assertThat(configuration.getId()).isEqualTo(configurationArgumentCaptor.getAllValues().get(1).getId());
}
@Test
public void github_global_settings_validation_with_encrypted_key() {
String encryptedKey = "encrypted-key";
String decryptedKey = "decrypted-key";
AlmSettingDto almSettingDto = createNewGithubDto("clientId", "clientSecret", EXAMPLE_APP_ID, encryptedKey);
when(encryption.isEncrypted(encryptedKey)).thenReturn(true);
when(encryption.decrypt(encryptedKey)).thenReturn(decryptedKey);
GithubAppConfiguration configuration = underTest.validate(almSettingDto);
ArgumentCaptor<GithubAppConfiguration> configurationArgumentCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
verify(appClient).checkApiEndpoint(configurationArgumentCaptor.capture());
verify(appClient).checkAppPermissions(configurationArgumentCaptor.capture());
assertThat(configuration.getId()).isEqualTo(configurationArgumentCaptor.getAllValues().get(0).getId());
assertThat(decryptedKey).isEqualTo(configurationArgumentCaptor.getAllValues().get(0).getPrivateKey());
assertThat(configuration.getId()).isEqualTo(configurationArgumentCaptor.getAllValues().get(1).getId());
assertThat(decryptedKey).isEqualTo(configurationArgumentCaptor.getAllValues().get(1).getPrivateKey());
}
@Test
public void github_validation_checks_invalid_appId() {
AlmSettingDto almSettingDto = createNewGithubDto("clientId", "clientSecret", "abc", null);
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid appId; For input string: \"abc\"");
}
@Test
public void github_validation_checks_missing_appId() {
AlmSettingDto almSettingDto = new AlmSettingDto();
almSettingDto.setAppId(null);
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Missing appId");
}
@Test
public void github_validation_checks_missing_clientId() {
AlmSettingDto almSettingDto = createNewGithubDto(null, null, EXAMPLE_APP_ID, null);
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Missing Client Id");
}
@Test
public void github_validation_checks_missing_clientSecret() {
AlmSettingDto almSettingDto = createNewGithubDto("clientId", null, EXAMPLE_APP_ID, null);
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Missing Client Secret");
}
private AlmSettingDto createNewGithubDto(@Nullable String clientId, @Nullable String clientSecret,
@Nullable String appId, @Nullable String privateKey) {
AlmSettingDto dto = new AlmSettingDto();
dto.setAlm(ALM.GITHUB);
dto.setUrl("http://github-example-url.com");
dto.setClientId(clientId);
dto.setClientSecret(clientSecret);
dto.setAppId(appId);
dto.setPrivateKey(privateKey);
return dto;
}
}
| 5,962 | 41.899281 | 127 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/SonarQubeIssueKeyFormatterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github;
import java.util.Optional;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import static java.lang.String.join;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.alm.client.github.SonarQubeIssueKeyFormatter.SONAR_ISSUE_KEY_PREFIX;
import static org.sonar.alm.client.github.SonarQubeIssueKeyFormatter.SONAR_ISSUE_KEY_SUFFIX;
public class SonarQubeIssueKeyFormatterTest {
@Test
public void should_serializeIssueKey() {
String issueKey = RandomStringUtils.randomAlphanumeric(20);
String serialized = SonarQubeIssueKeyFormatter.serialize(issueKey);
String expectedSerializedKey = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, SONAR_ISSUE_KEY_SUFFIX);
assertThat(serialized).isEqualTo(expectedSerializedKey);
}
@Test
public void should_deserializeIssueKey() {
String issueKey = RandomStringUtils.randomAlphanumeric(20);
String message = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, SONAR_ISSUE_KEY_SUFFIX, "a message");
Optional<String> deserialized = SonarQubeIssueKeyFormatter.deserialize(message);
assertThat(deserialized).hasValue(issueKey);
}
@Test
public void should_notDeserializeIssueKey_when_messageHasWrongFormat() {
String issueKey = RandomStringUtils.randomAlphanumeric(20);
String messageWithoutSuffix = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, "a message");
String messageWithoutPrefix = join("", issueKey, SONAR_ISSUE_KEY_SUFFIX, "a message");
String messageWithPrefixSuffixReversed = join("", SONAR_ISSUE_KEY_SUFFIX, issueKey, SONAR_ISSUE_KEY_PREFIX, "a message");
String messageWithNoPrefixSuffix = join("", issueKey, "a message");
assertThat(SonarQubeIssueKeyFormatter.deserialize(messageWithoutSuffix)).isEmpty();
assertThat(SonarQubeIssueKeyFormatter.deserialize(messageWithoutPrefix)).isEmpty();
assertThat(SonarQubeIssueKeyFormatter.deserialize(messageWithPrefixSuffixReversed)).isEmpty();
assertThat(SonarQubeIssueKeyFormatter.deserialize(messageWithNoPrefixSuffix)).isEmpty();
}
}
| 2,931 | 42.761194 | 125 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/config/GithubAppConfigurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.config;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang.ArrayUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class GithubAppConfigurationTest {
@Test
@UseDataProvider("incompleteConfigurationParametersSonarQube")
public void isComplete_returns_false_if_configuration_is_incomplete_on_SonarQube(@Nullable Long applicationId, @Nullable String privateKey, @Nullable String apiEndpoint) {
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
assertThat(underTest.isComplete()).isFalse();
}
@Test
@UseDataProvider("incompleteConfigurationParametersSonarQube")
public void getId_throws_ISE_if_config_is_incomplete(@Nullable Long applicationId, @Nullable String privateKey, @Nullable String apiEndpoint) {
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
assertThatThrownBy(underTest::getId)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Configuration is not complete");
}
@Test
public void getId_returns_applicationId_if_configuration_is_valid() {
long applicationId = new Random().nextLong();
GithubAppConfiguration underTest = newValidConfiguration(applicationId);
assertThat(underTest.getId()).isEqualTo(applicationId);
}
@Test
@UseDataProvider("incompleteConfigurationParametersSonarQube")
public void getPrivateKeyFile_throws_ISE_if_config_is_incomplete(@Nullable Long applicationId, @Nullable String privateKey, @Nullable String apiEndpoint) {
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
assertThatThrownBy(underTest::getPrivateKey)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Configuration is not complete");
}
@DataProvider
public static Object[][] incompleteConfigurationParametersSonarQube() {
long applicationId = new Random().nextLong();
String privateKey = randomAlphabetic(9);
String apiEndpoint = randomAlphabetic(11);
return generateNullCombination(new Object[] {
applicationId,
privateKey,
apiEndpoint
});
}
@Test
public void toString_displays_complete_configuration() {
long id = 34;
String privateKey = randomAlphabetic(3);
String apiEndpoint = randomAlphabetic(7);
GithubAppConfiguration underTest = new GithubAppConfiguration(id, privateKey, apiEndpoint);
assertThat(underTest)
.hasToString(String.format("GithubAppConfiguration{id=%s, privateKey='***(3)***', apiEndpoint='%s'}", id, apiEndpoint));
}
@Test
public void toString_displays_incomplete_configuration() {
GithubAppConfiguration underTest = new GithubAppConfiguration(null, null, null);
assertThat(underTest)
.hasToString("GithubAppConfiguration{id=null, privateKey=null, apiEndpoint=null}");
}
@Test
public void toString_displays_privateKey_as_stars() {
GithubAppConfiguration underTest = new GithubAppConfiguration(null, randomAlphabetic(555), null);
assertThat(underTest)
.hasToString(
"GithubAppConfiguration{id=null, privateKey='***(555)***', apiEndpoint=null}");
}
@Test
public void equals_is_not_implemented() {
long applicationId = new Random().nextLong();
String privateKey = randomAlphabetic(8);
String apiEndpoint = randomAlphabetic(7);
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
assertThat(underTest)
.isEqualTo(underTest)
.isNotEqualTo(new GithubAppConfiguration(applicationId, privateKey, apiEndpoint));
}
@Test
public void hashcode_is_based_on_all_fields() {
long applicationId = new Random().nextLong();
String privateKey = randomAlphabetic(8);
String apiEndpoint = randomAlphabetic(7);
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
assertThat(underTest).hasSameHashCodeAs(underTest);
assertThat(underTest.hashCode()).isNotEqualTo(new GithubAppConfiguration(applicationId, privateKey, apiEndpoint));
}
private GithubAppConfiguration newValidConfiguration(long applicationId) {
return new GithubAppConfiguration(applicationId, randomAlphabetic(6), randomAlphabetic(6));
}
private static Object[][] generateNullCombination(Object[] objects) {
Object[][] firstPossibleValues = new Object[][] {
{null},
{objects[0]}
};
if (objects.length == 1) {
return firstPossibleValues;
}
Object[][] subCombinations = generateNullCombination(ArrayUtils.subarray(objects, 1, objects.length));
return Stream.of(subCombinations)
.flatMap(combination -> Stream.of(firstPossibleValues).map(firstValue -> ArrayUtils.addAll(firstValue, combination)))
.filter(array -> ArrayUtils.contains(array, null))
.toArray(Object[][]::new);
}
}
| 6,294 | 37.619632 | 173 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/config/GithubProvisioningConfigValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.config;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.alm.client.github.GithubApplicationClient;
import org.sonar.alm.client.github.GithubBinding.GsonApp;
import org.sonar.alm.client.github.GithubBinding.Permissions;
import org.sonar.auth.github.GitHubSettings;
import org.sonarqube.ws.client.HttpException;
import static java.lang.Long.parseLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.alm.client.github.config.ConfigCheckResult.ConfigStatus;
import static org.sonar.alm.client.github.config.ConfigCheckResult.InstallationStatus;
@RunWith(MockitoJUnitRunner.class)
public class GithubProvisioningConfigValidatorTest {
private static final String SUCCESS_STATUS = "SUCCESS";
private static final String GITHUB_CALL_FAILED = "Error response from GitHub: GitHub call failed.";
private static final String APP_FETCHING_FAILED = "Exception while fetching the App.";
private static final String INVALID_APP_ID_STATUS = "GitHub App ID must be a number.";
private static final String INCOMPLETE_APP_CONFIG_STATUS = "The GitHub App configuration is not complete.";
private static final String MISSING_EMAIL_PERMISSION = "Missing permissions: Account permissions -> Email addresses";
private static final String MISSING_MEMBERS_PERMISSION = "Missing permissions: Organization permissions -> Members";
private static final String MISSING_EMAILS_AND_MEMBERS_PERMISSION = "Missing permissions: Account permissions -> Email addresses,Organization permissions -> Members";
private static final String NO_INSTALLATIONS_STATUS = "The GitHub App is not installed on any organizations or the organization is not white-listed.";
private static final String SUSPENDED_INSTALLATION = "Installation suspended";
private static final ConfigStatus SUCCESS_CHECK = new ConfigStatus(SUCCESS_STATUS, null);
public static final String APP_ID = "1";
public static final String PRIVATE_KEY = "secret";
public static final String URL = "url";
@Mock
private GithubApplicationClient githubClient;
@Mock
private GitHubSettings gitHubSettings;
@InjectMocks
private GithubProvisioningConfigValidator configValidator;
@Test
public void checkConfig_whenAppIdIsNull_shouldReturnFailedAppCheck() {
when(gitHubSettings.appId()).thenReturn(null);
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(INVALID_APP_ID_STATUS));
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(INVALID_APP_ID_STATUS));
assertThat(checkResult.installations()).isEmpty();
}
@Test
public void checkConfig_whenAppIdNotValid_shouldReturnFailedAppCheck() {
when(gitHubSettings.appId()).thenReturn("not a number");
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(INVALID_APP_ID_STATUS));
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(INVALID_APP_ID_STATUS));
assertThat(checkResult.installations()).isEmpty();
}
@Test
public void checkConfig_whenGithubAppConfigurationNotComplete_shouldReturnFailedAppCheck() {
when(gitHubSettings.appId()).thenReturn(APP_ID);
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(INCOMPLETE_APP_CONFIG_STATUS));
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(INCOMPLETE_APP_CONFIG_STATUS));
assertThat(checkResult.installations()).isEmpty();
}
@Test
public void checkConfig_whenHttpExceptionWhileFetchingTheApp_shouldReturnFailedAppCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
HttpException httpException = mock(HttpException.class);
when(httpException.getMessage()).thenReturn("GitHub call failed.");
when(githubClient.getApp(appConfigurationCaptor.capture())).thenThrow(httpException);
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(GITHUB_CALL_FAILED));
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(GITHUB_CALL_FAILED));
assertThat(checkResult.installations()).isEmpty();
}
@Test
public void checkConfig_whenIllegalArgumentExceptionWhileFetchingTheApp_shouldReturnFailedAppCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
IllegalArgumentException illegalArgumentException = mock(IllegalArgumentException.class);
when(illegalArgumentException.getMessage()).thenReturn("Exception while fetching the App.");
when(githubClient.getApp(appConfigurationCaptor.capture())).thenThrow(illegalArgumentException);
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(APP_FETCHING_FAILED));
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(APP_FETCHING_FAILED));
assertThat(checkResult.installations()).isEmpty();
}
@Test
public void checkConfig_whenAppDoesntHaveEmailsPermissions_shouldReturnFailedAppJitCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
GsonApp githubApp = mockGithubApp(appConfigurationCaptor);
when(githubApp.getPermissions()).thenReturn(new Permissions());
mockOrganizationsWithoutPermissions(appConfigurationCaptor, "org1", "org2");
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(MISSING_EMAILS_AND_MEMBERS_PERMISSION));
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(MISSING_EMAIL_PERMISSION));
assertThat(checkResult.installations()).hasSize(2);
assertThat(checkResult.installations())
.extracting(InstallationStatus::jit, InstallationStatus::autoProvisioning)
.containsExactly(
tuple(ConfigStatus.failed(MISSING_EMAIL_PERMISSION), ConfigStatus.failed(MISSING_MEMBERS_PERMISSION)),
tuple(ConfigStatus.failed(MISSING_EMAIL_PERMISSION), ConfigStatus.failed(MISSING_MEMBERS_PERMISSION)));
verifyAppConfiguration(appConfigurationCaptor.getValue());
}
@Test
public void checkConfig_whenAppDoesntHaveMembersPermissions_shouldReturnFailedAppAutoProvisioningCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
GsonApp githubApp = mockGithubApp(appConfigurationCaptor);
when(githubApp.getPermissions()).thenReturn(new Permissions(null, null, "read", null));
mockOrganizations(appConfigurationCaptor, "org1", "org2");
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.SUCCESS);
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(MISSING_MEMBERS_PERMISSION));
assertThat(checkResult.installations()).hasSize(2);
verifyAppConfiguration(appConfigurationCaptor.getValue());
}
@Test
public void checkConfig_whenNoInstallationsAreReturned_shouldReturnFailedAppAutoProvisioningCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
mockGithubAppWithValidConfig(appConfigurationCaptor);
mockOrganizationsWithoutPermissions(appConfigurationCaptor);
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.failed(NO_INSTALLATIONS_STATUS));
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(NO_INSTALLATIONS_STATUS));
assertThat(checkResult.installations()).isEmpty();
verifyAppConfiguration(appConfigurationCaptor.getValue());
}
@Test
public void checkConfig_whenInstallationsDoesntHaveMembersPermissions_shouldReturnFailedAppAutoProvisioningCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
mockGithubAppWithValidConfig(appConfigurationCaptor);
mockOrganizationsWithoutPermissions(appConfigurationCaptor, "org1");
ConfigCheckResult checkResult = configValidator.checkConfig();
assertSuccessfulAppConfig(checkResult);
assertThat(checkResult.installations())
.extracting(InstallationStatus::organization, InstallationStatus::autoProvisioning)
.containsExactly(tuple("org1", ConfigStatus.failed(MISSING_MEMBERS_PERMISSION)));
verifyAppConfiguration(appConfigurationCaptor.getValue());
}
@Test
public void checkConfig_whenInstallationSuspended_shouldReturnFailedInstallationAutoProvisioningCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
mockGithubAppWithValidConfig(appConfigurationCaptor);
mockSuspendedOrganizations("org1");
ConfigCheckResult checkResult = configValidator.checkConfig();
assertSuccessfulAppConfig(checkResult);
assertThat(checkResult.installations())
.extracting(InstallationStatus::organization, InstallationStatus::autoProvisioning)
.containsExactly(tuple("org1", ConfigStatus.failed(SUSPENDED_INSTALLATION)));
verify(githubClient).getWhitelistedGithubAppInstallations(appConfigurationCaptor.capture());
verifyAppConfiguration(appConfigurationCaptor.getValue());
}
@Test
public void checkConfig_whenAllPermissionsAreCorrect_shouldReturnSuccessfulCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
mockGithubAppWithValidConfig(appConfigurationCaptor);
mockOrganizations(appConfigurationCaptor, "org1", "org2");
ConfigCheckResult checkResult = configValidator.checkConfig();
assertSuccessfulAppConfig(checkResult);
assertThat(checkResult.installations())
.extracting(InstallationStatus::organization, InstallationStatus::autoProvisioning)
.containsExactlyInAnyOrder(
tuple("org1", SUCCESS_CHECK),
tuple("org2", ConfigStatus.failed(MISSING_MEMBERS_PERMISSION)));
verifyAppConfiguration(appConfigurationCaptor.getValue());
}
private void mockGithubConfiguration() {
when(gitHubSettings.appId()).thenReturn(APP_ID);
when(gitHubSettings.privateKey()).thenReturn(PRIVATE_KEY);
when(gitHubSettings.apiURLOrDefault()).thenReturn(URL);
}
private void verifyAppConfiguration(GithubAppConfiguration appConfiguration) {
assertThat(appConfiguration.getId()).isEqualTo(parseLong(APP_ID));
assertThat(appConfiguration.getPrivateKey()).isEqualTo(PRIVATE_KEY);
assertThat(appConfiguration.getApiEndpoint()).isEqualTo(URL);
}
private GsonApp mockGithubApp(ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor) {
GsonApp githubApp = mock(GsonApp.class);
when(githubClient.getApp(appConfigurationCaptor.capture())).thenReturn(githubApp);
return githubApp;
}
private GsonApp mockGithubAppWithValidConfig(ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor) {
GsonApp githubApp = mock(GsonApp.class);
when(githubClient.getApp(appConfigurationCaptor.capture())).thenReturn(githubApp);
when(githubApp.getPermissions()).thenReturn(new Permissions(null, "read", "read", null));
return githubApp;
}
private static void assertSuccessfulAppConfig(ConfigCheckResult checkResult) {
assertThat(checkResult.application().jit()).isEqualTo(ConfigStatus.SUCCESS);
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.SUCCESS);
}
private void mockOrganizationsWithoutPermissions(ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor, String... organizations) {
List<GithubAppInstallation> installations = Arrays.stream(organizations).map(GithubProvisioningConfigValidatorTest::mockInstallation).toList();
when(githubClient.getWhitelistedGithubAppInstallations(appConfigurationCaptor.capture())).thenReturn(installations);
}
private void mockSuspendedOrganizations(String orgName) {
GithubAppInstallation installation = new GithubAppInstallation(null, orgName, null, true);
when(githubClient.getWhitelistedGithubAppInstallations(any())).thenReturn(List.of(installation));
}
private static GithubAppInstallation mockInstallation(String org) {
GithubAppInstallation installation = mock(GithubAppInstallation.class);
when(installation.organizationName()).thenReturn(org);
when(installation.permissions()).thenReturn(mock(Permissions.class));
return installation;
}
private static GithubAppInstallation mockInstallationWithMembersPermission(String org) {
GithubAppInstallation installation = mockInstallation(org);
when(installation.permissions()).thenReturn(new Permissions(null, "read", "read", null));
return installation;
}
private void mockOrganizations(ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor, String orgWithMembersPermission, String orgWithoutMembersPermission) {
List<GithubAppInstallation> installations = List.of(
mockInstallationWithMembersPermission(orgWithMembersPermission),
mockInstallation(orgWithoutMembersPermission));
when(githubClient.getWhitelistedGithubAppInstallations(appConfigurationCaptor.capture())).thenReturn(installations);
}
}
| 15,326 | 47.812102 | 168 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/AppTokenTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class AppTokenTest {
@Test
public void test_value() {
AppToken underTest = new AppToken("foo");
assertThat(underTest.toString())
.isEqualTo(underTest.getValue())
.isEqualTo("foo");
assertThat(underTest.getAuthorizationHeaderPrefix()).isEqualTo("Bearer");
}
@Test
public void test_equals_hashCode() {
AppToken foo = new AppToken("foo");
assertThat(foo)
.isEqualTo(foo)
.isEqualTo(new AppToken("foo"))
.isNotEqualTo(new AppToken("bar"))
.hasSameHashCodeAs(foo)
.hasSameHashCodeAs(new AppToken("foo"));
}
}
| 1,563 | 29.666667 | 77 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.github.security;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import java.io.IOException;
import java.security.spec.InvalidKeySpecException;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.alm.client.github.config.GithubAppConfiguration;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class GithubAppSecurityImplTest {
private Clock clock = Clock.fixed(Instant.ofEpochSecond(132_600_888L), ZoneId.systemDefault());
private GithubAppSecurityImpl underTest = new GithubAppSecurityImpl(clock);
@Test
public void createAppToken_fails_with_IAE_if_privateKey_content_is_garbage() {
String garbage = randomAlphanumeric(555);
GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(garbage);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()))
.isInstanceOf(IllegalArgumentException.class)
.hasRootCauseMessage("Failed to decode Github Application private key");
}
@Test
public void createAppToken_fails_with_IAE_if_privateKey_PKCS8_content_is_missing_end_comment() {
String incompletePrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEowIBAAKCAQEA6C29ZdvrwHOu7Eewv+xvUd4inCnACTzAHukHKTSY4R16+lRI\n" +
"YC5qZ8Xo304J7lLhN4/d4Xnof3lDXZOHthVbJKik4fOuEGbTXTIcuFs3hdJtrJsb\n" +
"antv8SOl5iR4fYRAf2AILMdtZI4iMSicBLIIttR+wVXo6NJYMjpj1OuAU3uN8eET\n" +
"Gge09oJT3QOUBem7N8uaYi/p5uAfsf2/SVNsoMPV624X4kgNcyj/TMa6BosFJ8Y3\n" +
"oeg0Aguk2yuHhAnixDVGoz6N7Go0QjEipVNix2JOOJwpFH4k2iZfM6n+8sJTLilq\n" +
"yzT53JW/XI+M5AXVj4OjBJ/2yMPi3RFMNTdgRwIDAQABAoIBACcYBIsRI7oNAIgi\n" +
"bh1y1y+mwpce5Inpo8PQovcKNy+4gguCg4lGZ34/sb1f64YoiGmNnOOpXj+QkIpC\n" +
"HBjJscYTa2fsWwPB/Jb1qCZWnZu32eW1XEFqtWeaBAYjX/JqgV2xMs8vaTkEQbeb\n" +
"SeH0hEkcsJcnOwdw247hjAu+96WWlyt10ZGgQaWPfXsdtelbaoaturNAVAJHdl9e\n" +
"TIknCIbtLlbz/FtzjtCtdeiWr8gbKdVkshGtA8SKVhXGQwDwENjUkAUtSJ0aXR1t\n" +
"+UjQcTISk7LiiYs0MrJ/CKoJ7mShwx7+YF3hgyqQ0qaqHwt9Yyd7wzWdCgdM5Eha\n" +
"ccioIskCgYEA+EDJmcM5NGu5AYpZ1ogmG6jzsefAlr2NG1PQ/U03twal/B+ygAQb\n" +
"5dholrq+aF+45Hrzfxije3Zrvpb08vxzKAs20lOlJsKftx2zkLR+mNvWTAORuO16\n" +
"lG0c0cgYAKA1ld4R8KB8NmbuNb1w4LYZuyuFIEVmm2B3ca141WNHBwMCgYEA72yK\n" +
"B4+xxomZn6dtbCGQZxziaI9WH/KEfDemKO5cfPlynQjmmMkiDpcyHa7mvdU+PGh3\n" +
"g+OmQxORXMmBkHEnYS1fl3ac3U5sLiHAQBmTKKcLuVQlIU4oDu/K6WEGL9DdPtaK\n" +
"gyOOWtSnfHTbT0bZ4IMm+gzdc4bCuEjvYyUhzG0CgYAEN011MAyTqFSvAwN9kjhb\n" +
"deYVmmL57GQuF6FP+/S7RgChpIQqimdS4vb7wFYlfaKtNq1V9jwoh51S0kt8qO7n\n" +
"ujEHJ2aBnwKJYJbBGV+hBvK/vbvG0TmotaWspmJJ+G6QigHx/Te+0Maw4PO+zTjo\n" +
"pdeP8b3JW70LkC+iKBp3swKBgFL/nm32m1tHEjFtehpVHFkSg05Z+jJDATiKlhh0\n" +
"YS2Vz+yuTDpE54CFW4M8wZKnXNbWJDBdd6KjIu42kKrA/zTJ5Ox92u1BJXFsk9fk\n" +
"xcX++qp5iBGepXZgHEiBMQLcdgY1m3jQl6XXOGSFog0+c4NIE/f1A8PrwI7gAdSt\n" +
"56SVAoGBAJp214Fo0oheMTTYKVtXuGiH/v3JNG1jKFgsmHqndf4wy7U6bbNctEzc\n" +
"ZXNIacuhWmko6YejMrWNhE57sX812MhXGZq6y0sYZGKtp7oDv8G3rWD6bpZywpcV\n" +
"kTtMJxm8J64u6bAkpWG3BocJP9qbXeAbILo1wuXgYqABBrpA9nnc";
GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(incompletePrivateKey);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()))
.isInstanceOf(IllegalArgumentException.class)
.hasRootCauseInstanceOf(IOException.class)
.hasRootCauseMessage("-----END RSA PRIVATE KEY not found");
}
@Test
public void createAppToken_fails_with_IAE_if_privateKey_PKCS8_content_is_corrupted() {
String corruptedPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEowIBAAKCAQEA6C29ZdvrwHOu7Eewv+xvUd4inCnACTzAHukHKTSY4R16+lRI\n" +
"YC5qZ8Xo304J7lLhN4/d4Xnof3lDXZOHthVbJKik4fOuEGbTXTIcuFs3hdJtrJsb\n" +
"antv8SOl5iR4fYRAf2AILMdtZI4iMSicBLIIttR+wVXo6NJYMjpj1OuAU3uN8eET\n" +
"Gge09oJT3QOUBem7N8uaYi/p5uAfsf2/SVNsoMPV624X4kgNcyj/TMa6BosFJ8Y3\n" +
"oeg0Aguk2yuHhAnixDVGoz6N7Go0QjEipVNix2JOOJwpFH4k2iZfM6n+8sJTLilq\n" +
"yzT53JW/XI+M5AXVj4OjBJ/2yMPi3RFMNTdgRwIDAQABAoIBACcYBIsRI7oNAIgi\n" +
"bh1y1y+mwpce5Inpo8PQovcKNy+4gguCg4lGZ34/sb1f64YoiGmNnOOpXj+QkIpC\n" +
"HBjJscYTa2fsWwPB/Jb1qCZWnZu32eW1XEFqtWeaBAYjX/JqgV2xMs8vaTkEQbeb\n" +
// "SeH0hEkcsJcnOwdw247hjAu+96WWlyt10ZGgQaWPfXsdtelbaoaturNAVAJHdl9e\n" +
// "TIknCIbtLlbz/FtzjtCtdeiWr8gbKdVkshGtA8SKVhXGQwDwENjUkAUtSJ0aXR1t\n" +
// "+UjQcTISk7LiiYs0MrJ/CKoJ7mShwx7+YF3hgyqQ0qaqHwt9Yyd7wzWdCgdM5Eha\n" +
// "ccioIskCgYEA+EDJmcM5NGu5AYpZ1ogmG6jzsefAlr2NG1PQ/U03twal/B+ygAQb\n" +
// "5dholrq+aF+45Hrzfxije3Zrvpb08vxzKAs20lOlJsKftx2zkLR+mNvWTAORuO16\n" +
// "lG0c0cgYAKA1ld4R8KB8NmbuNb1w4LYZuyuFIEVmm2B3ca141WNHBwMCgYEA72yK\n" +
// "B4+xxomZn6dtbCGQZxziaI9WH/KEfDemKO5cfPlynQjmmMkiDpcyHa7mvdU+PGh3\n" +
"g+OmQxORXMmBkHEnYS1fl3ac3U5sLiHAQBmTKKcLuVQlIU4oDu/K6WEGL9DdPtaK\n" +
"gyOOWtSnfHTbT0bZ4IMm+gzdc4bCuEjvYyUhzG0CgYAEN011MAyTqFSvAwN9kjhb\n" +
"deYVmmL57GQuF6FP+/S7RgChpIQqimdS4vb7wFYlfaKtNq1V9jwoh51S0kt8qO7n\n" +
"ujEHJ2aBnwKJYJbBGV+hBvK/vbvG0TmotaWspmJJ+G6QigHx/Te+0Maw4PO+zTjo\n" +
"pdeP8b3JW70LkC+iKBp3swKBgFL/nm32m1tHEjFtehpVHFkSg05Z+jJDATiKlhh0\n" +
"YS2Vz+yuTDpE54CFW4M8wZKnXNbWJDBdd6KjIu42kKrA/zTJ5Ox92u1BJXFsk9fk\n" +
"xcX++qp5iBGepXZgHEiBMQLcdgY1m3jQl6XXOGSFog0+c4NIE/f1A8PrwI7gAdSt\n" +
"56SVAoGBAJp214Fo0oheMTTYKVtXuGiH/v3JNG1jKFgsmHqndf4wy7U6bbNctEzc\n" +
"ZXNIacuhWmko6YejMrWNhE57sX812MhXGZq6y0sYZGKtp7oDv8G3rWD6bpZywpcV\n" +
"kTtMJxm8J64u6bAkpWG3BocJP9qbXeAbILo1wuXgYqABBrpA9nnc\n" +
"-----END RSA PRIVATE KEY-----";
GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(corruptedPrivateKey);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()))
.isInstanceOf(IllegalArgumentException.class)
.hasCauseInstanceOf(InvalidKeySpecException.class);
}
@Test
public void getApplicationJWTToken_throws_ISE_if_conf_is_not_complete() {
GithubAppConfiguration githubAppConfiguration = createAppConfiguration(false);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void getApplicationJWTToken_returns_token_if_app_config_and_private_key_are_valid() {
GithubAppConfiguration githubAppConfiguration = createAppConfiguration(true);
assertThat(underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).isNotNull();
}
private GithubAppConfiguration createAppConfiguration(boolean validConfiguration) {
if (validConfiguration) {
return createAppConfiguration();
} else {
return new GithubAppConfiguration(null, null, null);
}
}
private GithubAppConfiguration createAppConfiguration() {
return new GithubAppConfiguration(new Random().nextLong(), REAL_PRIVATE_KEY, randomAlphanumeric(5));
}
private GithubAppConfiguration createAppConfigurationForPrivateKey(String privateKey) {
long applicationId = new Random().nextInt(654);
return new GithubAppConfiguration(applicationId, privateKey, randomAlphabetic(8));
}
private static final String REAL_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEowIBAAKCAQEA6C29ZdvrwHOu7Eewv+xvUd4inCnACTzAHukHKTSY4R16+lRI\n" +
"YC5qZ8Xo304J7lLhN4/d4Xnof3lDXZOHthVbJKik4fOuEGbTXTIcuFs3hdJtrJsb\n" +
"antv8SOl5iR4fYRAf2AILMdtZI4iMSicBLIIttR+wVXo6NJYMjpj1OuAU3uN8eET\n" +
"Gge09oJT3QOUBem7N8uaYi/p5uAfsf2/SVNsoMPV624X4kgNcyj/TMa6BosFJ8Y3\n" +
"oeg0Aguk2yuHhAnixDVGoz6N7Go0QjEipVNix2JOOJwpFH4k2iZfM6n+8sJTLilq\n" +
"yzT53JW/XI+M5AXVj4OjBJ/2yMPi3RFMNTdgRwIDAQABAoIBACcYBIsRI7oNAIgi\n" +
"bh1y1y+mwpce5Inpo8PQovcKNy+4gguCg4lGZ34/sb1f64YoiGmNnOOpXj+QkIpC\n" +
"HBjJscYTa2fsWwPB/Jb1qCZWnZu32eW1XEFqtWeaBAYjX/JqgV2xMs8vaTkEQbeb\n" +
"SeH0hEkcsJcnOwdw247hjAu+96WWlyt10ZGgQaWPfXsdtelbaoaturNAVAJHdl9e\n" +
"TIknCIbtLlbz/FtzjtCtdeiWr8gbKdVkshGtA8SKVhXGQwDwENjUkAUtSJ0aXR1t\n" +
"+UjQcTISk7LiiYs0MrJ/CKoJ7mShwx7+YF3hgyqQ0qaqHwt9Yyd7wzWdCgdM5Eha\n" +
"ccioIskCgYEA+EDJmcM5NGu5AYpZ1ogmG6jzsefAlr2NG1PQ/U03twal/B+ygAQb\n" +
"5dholrq+aF+45Hrzfxije3Zrvpb08vxzKAs20lOlJsKftx2zkLR+mNvWTAORuO16\n" +
"lG0c0cgYAKA1ld4R8KB8NmbuNb1w4LYZuyuFIEVmm2B3ca141WNHBwMCgYEA72yK\n" +
"B4+xxomZn6dtbCGQZxziaI9WH/KEfDemKO5cfPlynQjmmMkiDpcyHa7mvdU+PGh3\n" +
"g+OmQxORXMmBkHEnYS1fl3ac3U5sLiHAQBmTKKcLuVQlIU4oDu/K6WEGL9DdPtaK\n" +
"gyOOWtSnfHTbT0bZ4IMm+gzdc4bCuEjvYyUhzG0CgYAEN011MAyTqFSvAwN9kjhb\n" +
"deYVmmL57GQuF6FP+/S7RgChpIQqimdS4vb7wFYlfaKtNq1V9jwoh51S0kt8qO7n\n" +
"ujEHJ2aBnwKJYJbBGV+hBvK/vbvG0TmotaWspmJJ+G6QigHx/Te+0Maw4PO+zTjo\n" +
"pdeP8b3JW70LkC+iKBp3swKBgFL/nm32m1tHEjFtehpVHFkSg05Z+jJDATiKlhh0\n" +
"YS2Vz+yuTDpE54CFW4M8wZKnXNbWJDBdd6KjIu42kKrA/zTJ5Ox92u1BJXFsk9fk\n" +
"xcX++qp5iBGepXZgHEiBMQLcdgY1m3jQl6XXOGSFog0+c4NIE/f1A8PrwI7gAdSt\n" +
"56SVAoGBAJp214Fo0oheMTTYKVtXuGiH/v3JNG1jKFgsmHqndf4wy7U6bbNctEzc\n" +
"ZXNIacuhWmko6YejMrWNhE57sX812MhXGZq6y0sYZGKtp7oDv8G3rWD6bpZywpcV\n" +
"kTtMJxm8J64u6bAkpWG3BocJP9qbXeAbILo1wuXgYqABBrpA9nnc\n" +
"-----END RSA PRIVATE KEY-----";
}
| 10,572 | 56.151351 | 126 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/gitlab/GitlabGlobalSettingsValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator;
import org.sonar.alm.client.gitlab.GitlabHttpClient;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.alm.setting.AlmSettingDto;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GitlabGlobalSettingsValidatorTest {
private static final Encryption encryption = mock(Encryption.class);
private static final Settings settings = mock(Settings.class);
private final GitlabHttpClient gitlabHttpClient = mock(GitlabHttpClient.class);
private final GitlabGlobalSettingsValidator underTest = new GitlabGlobalSettingsValidator(gitlabHttpClient, settings);
@BeforeClass
public static void setUp() {
when(settings.getEncryption()).thenReturn(encryption);
}
@Test
public void validate_success() {
String token = "personal-access-token";
AlmSettingDto almSettingDto = new AlmSettingDto()
.setUrl("https://gitlab.com/api")
.setPersonalAccessToken("personal-access-token");
when(encryption.isEncrypted(token)).thenReturn(false);
underTest.validate(almSettingDto);
verify(gitlabHttpClient, times(1)).checkUrl(almSettingDto.getUrl());
verify(gitlabHttpClient, times(1)).checkToken(almSettingDto.getUrl(), almSettingDto.getDecryptedPersonalAccessToken(encryption));
verify(gitlabHttpClient, times(1)).checkReadPermission(almSettingDto.getUrl(), almSettingDto.getDecryptedPersonalAccessToken(encryption));
verify(gitlabHttpClient, times(1)).checkWritePermission(almSettingDto.getUrl(), almSettingDto.getDecryptedPersonalAccessToken(encryption));
}
@Test
public void validate_success_with_encrypted_token() {
String encryptedToken = "personal-access-token";
String decryptedToken = "decrypted-token";
AlmSettingDto almSettingDto = new AlmSettingDto()
.setUrl("https://gitlab.com/api")
.setPersonalAccessToken(encryptedToken);
when(encryption.isEncrypted(encryptedToken)).thenReturn(true);
when(encryption.decrypt(encryptedToken)).thenReturn(decryptedToken);
underTest.validate(almSettingDto);
verify(gitlabHttpClient, times(1)).checkUrl(almSettingDto.getUrl());
verify(gitlabHttpClient, times(1)).checkToken(almSettingDto.getUrl(), decryptedToken);
verify(gitlabHttpClient, times(1)).checkReadPermission(almSettingDto.getUrl(), decryptedToken);
verify(gitlabHttpClient, times(1)).checkWritePermission(almSettingDto.getUrl(), decryptedToken);
}
@Test
public void validate_fail_url_not_set() {
AlmSettingDto almSettingDto = new AlmSettingDto()
.setUrl(null)
.setPersonalAccessToken("personal-access-token");
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Your Gitlab global configuration is incomplete.");
}
@Test
public void validate_fail_pat_not_set() {
AlmSettingDto almSettingDto = new AlmSettingDto()
.setUrl("https://gitlab.com/api")
.setPersonalAccessToken(null);
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Your Gitlab global configuration is incomplete.");
}
}
| 4,370 | 40.628571 | 143 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/test/java/org/sonar/alm/client/gitlab/GitlabHttpClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.alm.client.gitlab;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
public class GitlabHttpClientTest {
@Rule
public LogTester logTester = new LogTester();
private final MockWebServer server = new MockWebServer();
private GitlabHttpClient underTest;
private String gitlabUrl;
@Before
public void prepare() throws IOException {
server.start();
String urlWithEndingSlash = server.url("").toString();
gitlabUrl = urlWithEndingSlash.substring(0, urlWithEndingSlash.length() - 1);
TimeoutConfiguration timeoutConfiguration = new ConstantTimeoutConfiguration(10_000);
underTest = new GitlabHttpClient(timeoutConfiguration);
}
@After
public void stopServer() throws IOException {
server.shutdown();
}
@Test
public void should_throw_IllegalArgumentException_when_token_is_revoked() {
MockResponse response = new MockResponse()
.setResponseCode(401)
.setBody("{\"error\":\"invalid_token\",\"error_description\":\"Token was revoked. You have to re-authorize from the user.\"}");
server.enqueue(response);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Your GitLab token was revoked");
}
@Test
public void should_throw_IllegalArgumentException_when_token_insufficient_scope() {
MockResponse response = new MockResponse()
.setResponseCode(403)
.setBody("{\"error\":\"insufficient_scope\"," +
"\"error_description\":\"The request requires higher privileges than provided by the access token.\"," +
"\"scope\":\"api read_api\"}");
server.enqueue(response);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Your GitLab token has insufficient scope");
}
@Test
public void should_throw_IllegalArgumentException_when_invalide_json_in_401_response() {
MockResponse response = new MockResponse()
.setResponseCode(401)
.setBody("error in pat");
server.enqueue(response);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
}
@Test
public void should_throw_IllegalArgumentException_when_redirected() {
MockResponse response = new MockResponse()
.setResponseCode(308);
server.enqueue(response);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Request was redirected, please provide the correct URL");
}
@Test
public void get_project() {
MockResponse response = new MockResponse()
.setResponseCode(200)
.setBody("{\n"
+ " \"id\": 12345,\n"
+ " \"name\": \"SonarQube example 1\",\n"
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 1\",\n"
+ " \"path\": \"sonarqube-example-1\",\n"
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-1\",\n"
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1\"\n"
+ " }");
server.enqueue(response);
assertThat(underTest.getProject(gitlabUrl, "pat", 12345L))
.extracting(Project::getId, Project::getName)
.containsExactly(12345L, "SonarQube example 1");
}
@Test
public void get_project_fail_if_non_json_payload() {
MockResponse response = new MockResponse()
.setResponseCode(200)
.setBody("non json payload");
server.enqueue(response);
assertThatThrownBy(() -> underTest.getProject(gitlabUrl, "pat", 12345L))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not parse GitLab answer to retrieve a project. Got a non-json payload as result.");
}
@Test
public void get_branches() {
MockResponse response = new MockResponse()
.setResponseCode(200)
.setBody("[{\n"
+ " \"name\": \"main\",\n"
+ " \"default\": true\n"
+ "},{\n"
+ " \"name\": \"other\",\n"
+ " \"default\": false\n"
+ "}]");
server.enqueue(response);
assertThat(underTest.getBranches(gitlabUrl, "pat", 12345L))
.extracting(GitLabBranch::getName, GitLabBranch::isDefault)
.containsExactly(
tuple("main", true),
tuple("other", false)
);
}
@Test
public void get_branches_fail_if_non_json_payload() {
MockResponse response = new MockResponse()
.setResponseCode(200)
.setBody("non json payload");
server.enqueue(response);
String instanceUrl = gitlabUrl;
assertThatThrownBy(() -> underTest.getBranches(instanceUrl, "pat", 12345L))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not parse GitLab answer to retrieve project branches. Got a non-json payload as result.");
}
@Test
public void get_branches_fail_if_exception() throws IOException {
server.shutdown();
String instanceUrl = gitlabUrl;
assertThatThrownBy(() -> underTest.getBranches(instanceUrl, "pat", 12345L))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to");
}
@Test
public void search_projects() throws InterruptedException {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[\n"
+ " {\n"
+ " \"id\": 1,\n"
+ " \"name\": \"SonarQube example 1\",\n"
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 1\",\n"
+ " \"path\": \"sonarqube-example-1\",\n"
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-1\",\n"
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": 2,\n"
+ " \"name\": \"SonarQube example 2\",\n"
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 2\",\n"
+ " \"path\": \"sonarqube-example-2\",\n"
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-2\",\n"
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-2\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": 3,\n"
+ " \"name\": \"SonarQube example 3\",\n"
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 3\",\n"
+ " \"path\": \"sonarqube-example-3\",\n"
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-3\",\n"
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-3\"\n"
+ " }\n"
+ "]");
projects.addHeader("X-Page", 1);
projects.addHeader("X-Per-Page", 10);
projects.addHeader("X-Total", 3);
server.enqueue(projects);
ProjectList projectList = underTest.searchProjects(gitlabUrl, "pat", "example", 1, 10);
assertThat(projectList.getPageNumber()).isOne();
assertThat(projectList.getPageSize()).isEqualTo(10);
assertThat(projectList.getTotal()).isEqualTo(3);
assertThat(projectList.getProjects()).hasSize(3);
assertThat(projectList.getProjects()).extracting(
Project::getId, Project::getName, Project::getNameWithNamespace, Project::getPath, Project::getPathWithNamespace, Project::getWebUrl).containsExactly(
tuple(1L, "SonarQube example 1", "SonarSource / SonarQube / SonarQube example 1", "sonarqube-example-1", "sonarsource/sonarqube/sonarqube-example-1",
"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1"),
tuple(2L, "SonarQube example 2", "SonarSource / SonarQube / SonarQube example 2", "sonarqube-example-2", "sonarsource/sonarqube/sonarqube-example-2",
"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-2"),
tuple(3L, "SonarQube example 3", "SonarSource / SonarQube / SonarQube example 3", "sonarqube-example-3", "sonarsource/sonarqube/sonarqube-example-3",
"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-3"));
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(gitlabUrlCall).isEqualTo(server.url("") + "projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=example&page=1&per_page=10");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void search_projects_dont_fail_if_no_x_total() throws InterruptedException {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[\n"
+ " {\n"
+ " \"id\": 1,\n"
+ " \"name\": \"SonarQube example 1\",\n"
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 1\",\n"
+ " \"path\": \"sonarqube-example-1\",\n"
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-1\",\n"
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1\"\n"
+ " }"
+ "]");
projects.addHeader("X-Page", 1);
projects.addHeader("X-Per-Page", 10);
server.enqueue(projects);
ProjectList projectList = underTest.searchProjects(gitlabUrl, "pat", "example", 1, 10);
assertThat(projectList.getPageNumber()).isOne();
assertThat(projectList.getPageSize()).isEqualTo(10);
assertThat(projectList.getTotal()).isNull();
assertThat(projectList.getProjects()).hasSize(1);
assertThat(projectList.getProjects()).extracting(
Project::getId, Project::getName, Project::getNameWithNamespace, Project::getPath, Project::getPathWithNamespace, Project::getWebUrl).containsExactly(
tuple(1L, "SonarQube example 1", "SonarSource / SonarQube / SonarQube example 1", "sonarqube-example-1", "sonarsource/sonarqube/sonarqube-example-1",
"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1"));
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(gitlabUrlCall).isEqualTo(server.url("") + "projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=example&page=1&per_page=10");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void search_projects_with_case_insensitive_pagination_headers() throws InterruptedException {
MockResponse projects1 = new MockResponse()
.setResponseCode(200)
.setBody("[\n"
+ " {\n"
+ " \"id\": 1,\n"
+ " \"name\": \"SonarQube example 1\",\n"
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 1\",\n"
+ " \"path\": \"sonarqube-example-1\",\n"
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-1\",\n"
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1\"\n"
+ " }"
+ "]");
projects1.addHeader("x-page", 1);
projects1.addHeader("x-Per-page", 1);
projects1.addHeader("X-Total", 2);
server.enqueue(projects1);
ProjectList projectList = underTest.searchProjects(gitlabUrl, "pat", "example", 1, 10);
assertThat(projectList.getPageNumber()).isOne();
assertThat(projectList.getPageSize()).isOne();
assertThat(projectList.getTotal()).isEqualTo(2);
assertThat(projectList.getProjects()).hasSize(1);
assertThat(projectList.getProjects()).extracting(
Project::getId, Project::getName, Project::getNameWithNamespace, Project::getPath, Project::getPathWithNamespace, Project::getWebUrl).containsExactly(
tuple(1L, "SonarQube example 1", "SonarSource / SonarQube / SonarQube example 1", "sonarqube-example-1", "sonarsource/sonarqube/sonarqube-example-1",
"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-1"));
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(gitlabUrlCall).isEqualTo(server.url("") + "projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=example&page=1&per_page=10");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void search_projects_projectName_param_should_be_encoded() throws InterruptedException {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[]");
projects.addHeader("X-Page", 1);
projects.addHeader("X-Per-Page", 10);
projects.addHeader("X-Total", 0);
server.enqueue(projects);
ProjectList projectList = underTest.searchProjects(gitlabUrl, "pat", "&page=<script>alert('nasty')</script>", 1, 10);
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(projectList.getProjects()).isEmpty();
assertThat(gitlabUrlCall).isEqualTo(
server.url("")
+ "projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%26page%3D%3Cscript%3Ealert%28%27nasty%27%29%3C%2Fscript%3E&page=1&per_page=10");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void search_projects_projectName_param_null_should_pass_empty_string() throws InterruptedException {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[]");
projects.addHeader("X-Page", 1);
projects.addHeader("X-Per-Page", 10);
projects.addHeader("X-Total", 0);
server.enqueue(projects);
ProjectList projectList = underTest.searchProjects(gitlabUrl, "pat", null, 1, 10);
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(projectList.getProjects()).isEmpty();
assertThat(gitlabUrlCall).isEqualTo(
server.url("") + "projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=&page=1&per_page=10");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void get_project_details() throws InterruptedException {
MockResponse projectResponse = new MockResponse()
.setResponseCode(200)
.setBody("{"
+ " \"id\": 1234,"
+ " \"name\": \"SonarQube example 2\","
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 2\","
+ " \"path\": \"sonarqube-example-2\","
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-2\","
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-2\""
+ "}");
server.enqueue(projectResponse);
Project project = underTest.getProject(gitlabUrl, "pat", 1234L);
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(project).isNotNull();
assertThat(gitlabUrlCall).isEqualTo(
server.url("") + "projects/1234");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void get_reporter_level_access_project() throws InterruptedException {
MockResponse projectResponse = new MockResponse()
.setResponseCode(200)
.setBody("[{"
+ " \"id\": 1234,"
+ " \"name\": \"SonarQube example 2\","
+ " \"name_with_namespace\": \"SonarSource / SonarQube / SonarQube example 2\","
+ " \"path\": \"sonarqube-example-2\","
+ " \"path_with_namespace\": \"sonarsource/sonarqube/sonarqube-example-2\","
+ " \"web_url\": \"https://example.gitlab.com/sonarsource/sonarqube/sonarqube-example-2\""
+ "}]");
server.enqueue(projectResponse);
Optional<Project> project = underTest.getReporterLevelAccessProject(gitlabUrl, "pat", 1234L);
RecordedRequest projectGitlabRequest = server.takeRequest(10, TimeUnit.SECONDS);
String gitlabUrlCall = projectGitlabRequest.getRequestUrl().toString();
assertThat(project).isNotNull();
assertThat(gitlabUrlCall).isEqualTo(
server.url("") + "projects?min_access_level=20&id_after=1233&id_before=1235");
assertThat(projectGitlabRequest.getMethod()).isEqualTo("GET");
}
@Test
public void search_projects_fail_if_could_not_parse_pagination_number() {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[ ]");
projects.addHeader("X-Page", "bad-page-number");
projects.addHeader("X-Per-Page", "bad-per-page-number");
projects.addHeader("X-Total", "bad-total-number");
server.enqueue(projects);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not parse pagination number");
}
@Test
public void search_projects_fail_if_pagination_data_not_returned() {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[ ]");
server.enqueue(projects);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Pagination data from GitLab response is missing");
}
@Test
public void throws_ISE_when_get_projects_not_http_200() {
MockResponse projects = new MockResponse()
.setResponseCode(500)
.setBody("test");
server.enqueue(projects);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not get projects from GitLab instance");
}
@Test
public void fail_check_read_permission_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.checkReadPermission(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab read permission. Got an unexpected answer.");
assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/projects") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
@Test
public void fail_check_token_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.checkToken(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab token. Got an unexpected answer.");
assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("user") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
@Test
public void fail_check_write_permission_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.checkWritePermission(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab write permission. Got an unexpected answer.");
assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/markdown") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
@Test
public void fail_get_project_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.getProject(gitlabUrl, "token", 0L))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to");
assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/projects/0") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
@Test
public void fail_get_branches_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.getBranches(gitlabUrl, "token", 0L))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to " + server.getHostName());
assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/projects/0/repository/branches") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
@Test
public void fail_search_projects_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "token", null, 1, 1))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to");
assertThat(logTester.logs(Level.INFO).get(0))
.contains(
"Gitlab API call to [" + server.url("/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=&page=1&per_page=1")
+ "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
}
| 23,198 | 43.020873 | 174 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/BitbucketIdentityProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.ServiceBuilderOAuth20;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthConstants;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.annotation.CheckForNull;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toSet;
@ServerSide
public class BitbucketIdentityProvider implements OAuth2IdentityProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(BitbucketIdentityProvider.class);
public static final String REQUIRED_SCOPE = "account";
public static final String KEY = "bitbucket";
private final BitbucketSettings settings;
private final UserIdentityFactory userIdentityFactory;
private final BitbucketScribeApi scribeApi;
public BitbucketIdentityProvider(BitbucketSettings settings, UserIdentityFactory userIdentityFactory, BitbucketScribeApi scribeApi) {
this.settings = settings;
this.userIdentityFactory = userIdentityFactory;
this.scribeApi = scribeApi;
}
@Override
public String getKey() {
return KEY;
}
@Override
public String getName() {
return "Bitbucket";
}
@Override
public Display getDisplay() {
return Display.builder()
.setIconPath("/images/alm/bitbucket-white.svg")
.setBackgroundColor("#0052cc")
.build();
}
@Override
public boolean isEnabled() {
return settings.isEnabled();
}
@Override
public boolean allowsUsersToSignUp() {
return settings.allowUsersToSignUp();
}
@Override
public void init(InitContext context) {
String state = context.generateCsrfState();
OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
String url = scribe.getAuthorizationUrl(state);
context.redirectTo(url);
}
private ServiceBuilderOAuth20 newScribeBuilder(OAuth2Context context) {
checkState(isEnabled(), "Bitbucket authentication is disabled");
return new ServiceBuilder(settings.clientId())
.apiSecret(settings.clientSecret())
.callback(context.getCallbackUrl())
.defaultScope(REQUIRED_SCOPE);
}
@Override
public void callback(CallbackContext context) {
try {
onCallback(context);
} catch (IOException | ExecutionException e) {
throw new IllegalStateException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
private void onCallback(CallbackContext context) throws InterruptedException, ExecutionException, IOException {
HttpRequest request = context.getHttpRequest();
OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
String code = request.getParameter(OAuthConstants.CODE);
OAuth2AccessToken accessToken = scribe.getAccessToken(code);
GsonUser gsonUser = requestUser(scribe, accessToken);
GsonEmails gsonEmails = requestEmails(scribe, accessToken);
checkTeamRestriction(scribe, accessToken, gsonUser);
UserIdentity userIdentity = userIdentityFactory.create(gsonUser, gsonEmails);
context.authenticate(userIdentity);
context.redirectToRequestedPage();
}
private GsonUser requestUser(OAuth20Service service, OAuth2AccessToken accessToken) throws InterruptedException, ExecutionException, IOException {
OAuthRequest userRequest = new OAuthRequest(Verb.GET, settings.apiURL() + "2.0/user");
service.signRequest(accessToken, userRequest);
Response userResponse = service.execute(userRequest);
if (!userResponse.isSuccessful()) {
throw new IllegalStateException(format("Can not get Bitbucket user profile. HTTP code: %s, response: %s",
userResponse.getCode(), userResponse.getBody()));
}
String userResponseBody = userResponse.getBody();
return GsonUser.parse(userResponseBody);
}
@CheckForNull
private GsonEmails requestEmails(OAuth20Service service, OAuth2AccessToken accessToken) throws InterruptedException, ExecutionException, IOException {
OAuthRequest userRequest = new OAuthRequest(Verb.GET, settings.apiURL() + "2.0/user/emails");
service.signRequest(accessToken, userRequest);
Response emailsResponse = service.execute(userRequest);
if (emailsResponse.isSuccessful()) {
return GsonEmails.parse(emailsResponse.getBody());
}
return null;
}
private void checkTeamRestriction(OAuth20Service service, OAuth2AccessToken accessToken, GsonUser user) throws InterruptedException, ExecutionException, IOException {
String[] workspaceAllowed = settings.workspaceAllowedList();
if (workspaceAllowed != null && workspaceAllowed.length > 0) {
GsonWorkspaceMemberships userWorkspaces = requestWorkspaces(service, accessToken);
String errorMessage = format("User %s is not part of allowed workspaces list", user.getUsername());
if (userWorkspaces == null || userWorkspaces.getWorkspaces() == null) {
throw new UnauthorizedException(errorMessage);
} else {
Set<String> uniqueUserWorkspaces = new HashSet<>();
uniqueUserWorkspaces.addAll(userWorkspaces.getWorkspaces().stream().map(w -> w.getWorkspace().getName()).collect(toSet()));
uniqueUserWorkspaces.addAll(userWorkspaces.getWorkspaces().stream().map(w -> w.getWorkspace().getSlug()).collect(toSet()));
List<String> workspaceAllowedList = asList(workspaceAllowed);
if (uniqueUserWorkspaces.stream().noneMatch(workspaceAllowedList::contains)) {
throw new UnauthorizedException(errorMessage);
}
}
}
}
@CheckForNull
private GsonWorkspaceMemberships requestWorkspaces(OAuth20Service service, OAuth2AccessToken accessToken) throws InterruptedException, ExecutionException, IOException {
OAuthRequest userRequest = new OAuthRequest(Verb.GET, settings.apiURL() + "2.0/user/permissions/workspaces?q=permission=\"member\"");
service.signRequest(accessToken, userRequest);
Response teamsResponse = service.execute(userRequest);
if (teamsResponse.isSuccessful()) {
return GsonWorkspaceMemberships.parse(teamsResponse.getBody());
}
LOGGER.warn("Fail to retrieve the teams of Bitbucket user: {}", teamsResponse.getBody());
return null;
}
}
| 7,946 | 39.545918 | 170 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/BitbucketModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import java.util.List;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.core.platform.Module;
import static org.sonar.auth.bitbucket.BitbucketSettings.definitions;
public class BitbucketModule extends Module {
@Override
protected void configureModule() {
add(
BitbucketIdentityProvider.class,
BitbucketSettings.class,
UserIdentityFactory.class,
BitbucketScribeApi.class);
List<PropertyDefinition> definitions = definitions();
add(definitions.toArray(Object[]::new));
}
}
| 1,411 | 32.619048 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/BitbucketScribeApi.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.model.Verb;
import org.sonar.api.server.ServerSide;
@ServerSide
public class BitbucketScribeApi extends DefaultApi20 {
private final BitbucketSettings settings;
public BitbucketScribeApi(BitbucketSettings settings) {
this.settings = settings;
}
@Override
public String getAccessTokenEndpoint() {
return settings.webURL() + "site/oauth2/access_token";
}
@Override
public Verb getAccessTokenVerb() {
return Verb.POST;
}
@Override
protected String getAuthorizationBaseUrl() {
return settings.webURL() + "site/oauth2/authorize";
}
}
| 1,547 | 29.96 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/BitbucketSettings.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import javax.annotation.CheckForNull;
import org.sonar.api.PropertyType;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.server.ServerSide;
@ServerSide
public class BitbucketSettings {
private static final Supplier<? extends IllegalStateException> DEFAULT_VALUE_MISSING = () -> new IllegalStateException("Should have a default value");
public static final String CONSUMER_KEY = "sonar.auth.bitbucket.clientId.secured";
public static final String CONSUMER_SECRET = "sonar.auth.bitbucket.clientSecret.secured";
public static final String ENABLED = "sonar.auth.bitbucket.enabled";
public static final String ALLOW_USERS_TO_SIGN_UP = "sonar.auth.bitbucket.allowUsersToSignUp";
public static final String WORKSPACE_ALLOWED_LIST = "sonar.auth.bitbucket.workspaces";
public static final String DEFAULT_API_URL = "https://api.bitbucket.org/";
public static final String DEFAULT_WEB_URL = "https://bitbucket.org/";
public static final String CATEGORY = "authentication";
public static final String SUBCATEGORY = "bitbucket";
private final Configuration config;
public BitbucketSettings(Configuration config) {
this.config = config;
}
@CheckForNull
public String clientId() {
return config.get(CONSUMER_KEY).orElse(null);
}
@CheckForNull
public String clientSecret() {
return config.get(CONSUMER_SECRET).orElse(null);
}
public boolean isEnabled() {
return config.getBoolean(ENABLED).orElseThrow(DEFAULT_VALUE_MISSING) && clientId() != null && clientSecret() != null;
}
public boolean allowUsersToSignUp() {
return config.getBoolean(ALLOW_USERS_TO_SIGN_UP).orElseThrow(DEFAULT_VALUE_MISSING);
}
public String[] workspaceAllowedList() {
return config.getStringArray(WORKSPACE_ALLOWED_LIST);
}
public String webURL() {
return DEFAULT_WEB_URL;
}
public String apiURL() {
return DEFAULT_API_URL;
}
public static List<PropertyDefinition> definitions() {
return Arrays.asList(
PropertyDefinition.builder(ENABLED)
.name("Enabled")
.description("Enable Bitbucket users to login. Value is ignored if consumer key and secret are not defined.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(PropertyType.BOOLEAN)
.defaultValue(String.valueOf(false))
.index(1)
.build(),
PropertyDefinition.builder(CONSUMER_KEY)
.name("OAuth consumer key")
.description("Consumer key provided by Bitbucket when registering the consumer.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.index(2)
.build(),
PropertyDefinition.builder(CONSUMER_SECRET)
.name("OAuth consumer secret")
.description("Consumer secret provided by Bitbucket when registering the consumer.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.index(3)
.build(),
PropertyDefinition.builder(ALLOW_USERS_TO_SIGN_UP)
.name("Allow users to sign up")
.description("Allow new users to authenticate. When set to 'false', only existing users will be able to authenticate.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(PropertyType.BOOLEAN)
.defaultValue(String.valueOf(true))
.index(4)
.build(),
PropertyDefinition.builder(WORKSPACE_ALLOWED_LIST)
.name("Workspaces")
.description("Only members of at least one of these workspace will be able to authenticate. Keep empty to disable workspace restriction. You can use either the workspace name, or the workspace slug (ex: https://bitbucket.org/{workspace-slug}).")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.multiValues(true)
.index(5)
.build()
);
}
}
| 4,789 | 36.716535 | 253 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/GsonEmail.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.google.gson.annotations.SerializedName;
public class GsonEmail {
@SerializedName("is_primary")
private boolean isPrimary;
@SerializedName("email")
private String email;
public GsonEmail() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public boolean isPrimary() {
return isPrimary;
}
public String getEmail() {
return email;
}
}
| 1,352 | 29.066667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/GsonEmails.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import javax.annotation.CheckForNull;
public class GsonEmails {
@SerializedName("values")
private List<GsonEmail> emails;
public GsonEmails() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public List<GsonEmail> getEmails() {
return emails;
}
public static GsonEmails parse(String json) {
Gson gson = new Gson();
return gson.fromJson(json, GsonEmails.class);
}
@CheckForNull
public String extractPrimaryEmail() {
for (GsonEmail gsonEmail : emails) {
if (gsonEmail.isPrimary()) {
return gsonEmail.getEmail();
}
}
return null;
}
}
| 1,683 | 28.54386 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/GsonUser.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/**
* Lite representation of JSON response of GET https://api.bitbucket.org/2.0/user
*/
public class GsonUser {
@SerializedName("username")
private String username;
@SerializedName("display_name")
private String displayName;
@SerializedName("uuid")
private String uuid;
public GsonUser() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
GsonUser(String username, @Nullable String displayName, String uuid) {
this.username = username;
this.displayName = displayName;
this.uuid = uuid;
}
public String getUsername() {
return username;
}
@CheckForNull
public String getDisplayName() {
return displayName;
}
public String getUuid() {
return uuid;
}
public static GsonUser parse(String json) {
Gson gson = new Gson();
return gson.fromJson(json, GsonUser.class);
}
}
| 1,972 | 27.185714 | 81 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/GsonWorkspace.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.google.gson.annotations.SerializedName;
/**
* Lite representation of team https://api.bitbucket.org/2.0/user/permissions/workspaces
*/
public class GsonWorkspace {
@SerializedName("name")
private String name;
@SerializedName("slug")
private String slug;
public GsonWorkspace() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public String getName() {
return name;
}
public String getSlug() {
return slug;
}
}
| 1,435 | 27.72 | 88 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/GsonWorkspaceMembership.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.google.gson.annotations.SerializedName;
/**
* Lite representation of team https://api.bitbucket.org/2.0/user/permissions/workspaces
*/
public class GsonWorkspaceMembership {
@SerializedName("workspace")
private GsonWorkspace workspace;
public GsonWorkspaceMembership() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public GsonWorkspace getWorkspace() {
return workspace;
}
}
| 1,389 | 31.325581 | 88 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/GsonWorkspaceMemberships.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Lite representation of JSON response of GET https://api.bitbucket.org/2.0/user/permissions/workspaces
*/
public class GsonWorkspaceMemberships {
@SerializedName("values")
private List<GsonWorkspaceMembership> values;
public GsonWorkspaceMemberships() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public List<GsonWorkspaceMembership> getWorkspaces() {
return values;
}
public static GsonWorkspaceMemberships parse(String json) {
Gson gson = new Gson();
return gson.fromJson(json, GsonWorkspaceMemberships.class);
}
}
| 1,642 | 31.86 | 104 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/UserIdentityFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import javax.annotation.Nullable;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.authentication.UserIdentity;
@ServerSide
public class UserIdentityFactory {
public UserIdentity create(GsonUser gsonUser, @Nullable GsonEmails gsonEmails) {
UserIdentity.Builder builder = UserIdentity.builder()
.setProviderId(gsonUser.getUuid())
.setProviderLogin(gsonUser.getUsername())
.setName(generateName(gsonUser));
if (gsonEmails != null) {
builder.setEmail(gsonEmails.extractPrimaryEmail());
}
return builder.build();
}
private static String generateName(GsonUser gson) {
String name = gson.getDisplayName();
return name == null || name.isEmpty() ? gson.getUsername() : name;
}
}
| 1,628 | 34.413043 | 82 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/main/java/org/sonar/auth/bitbucket/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.auth.bitbucket;
import javax.annotation.ParametersAreNonnullByDefault;
| 964 | 39.208333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketIdentityProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class BitbucketIdentityProviderTest {
private final MapSettings settings = new MapSettings();
private final BitbucketSettings bitbucketSettings = new BitbucketSettings(settings.asConfig());
private final UserIdentityFactory userIdentityFactory = mock(UserIdentityFactory.class);
private final BitbucketScribeApi scribeApi = new BitbucketScribeApi(bitbucketSettings);
private final BitbucketIdentityProvider underTest = new BitbucketIdentityProvider(bitbucketSettings, userIdentityFactory, scribeApi);
@Test
public void check_fields() {
assertThat(underTest.getKey()).isEqualTo("bitbucket");
assertThat(underTest.getName()).isEqualTo("Bitbucket");
assertThat(underTest.getDisplay().getIconPath()).isEqualTo("/images/alm/bitbucket-white.svg");
assertThat(underTest.getDisplay().getBackgroundColor()).isEqualTo("#0052cc");
}
@Test
public void is_enabled() {
enableBitbucketAuthentication(true);
assertThat(underTest.isEnabled()).isTrue();
settings.setProperty("sonar.auth.bitbucket.enabled", false);
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void init() {
enableBitbucketAuthentication(true);
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
when(context.generateCsrfState()).thenReturn("state");
when(context.getCallbackUrl()).thenReturn("http://localhost/callback");
underTest.init(context);
verify(context).redirectTo("https://bitbucket.org/site/oauth2/authorize?response_type=code&client_id=id&redirect_uri=http%3A%2F%2Flocalhost%2Fcallback&scope=account&state=state");
}
@Test
public void fail_to_init_when_disabled() {
enableBitbucketAuthentication(false);
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
assertThatThrownBy(() -> underTest.init(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Bitbucket authentication is disabled");
}
private void enableBitbucketAuthentication(boolean enabled) {
if (enabled) {
settings.setProperty("sonar.auth.bitbucket.clientId.secured", "id");
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "secret");
settings.setProperty("sonar.auth.bitbucket.enabled", true);
} else {
settings.setProperty("sonar.auth.bitbucket.enabled", false);
}
}
}
| 3,661 | 39.241758 | 183 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class BitbucketModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new BitbucketModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(9);
}
}
| 1,264 | 33.189189 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketSettingsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
public class BitbucketSettingsTest {
private MapSettings settings = new MapSettings();
private BitbucketSettings underTest = new BitbucketSettings(settings.asConfig());
@Test
public void is_enabled() {
settings.setProperty("sonar.auth.bitbucket.clientId.secured", "id");
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "secret");
settings.setProperty("sonar.auth.bitbucket.enabled", true);
assertThat(underTest.isEnabled()).isTrue();
settings.setProperty("sonar.auth.bitbucket.enabled", false);
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void is_enabled_always_return_false_when_client_id_is_null() {
settings.setProperty("sonar.auth.bitbucket.enabled", true);
settings.setProperty("sonar.auth.bitbucket.clientId.secured", (String) null);
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "secret");
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void is_enabled_always_return_false_when_client_secret_is_null() {
settings.setProperty("sonar.auth.bitbucket.enabled", true);
settings.setProperty("sonar.auth.bitbucket.clientId.secured", "id");
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", (String) null);
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void return_client_id() {
settings.setProperty("sonar.auth.bitbucket.clientId.secured", "id");
assertThat(underTest.clientId()).isEqualTo("id");
}
@Test
public void return_client_secret() {
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "secret");
assertThat(underTest.clientSecret()).isEqualTo("secret");
}
@Test
public void allow_users_to_sign_up() {
settings.setProperty("sonar.auth.bitbucket.allowUsersToSignUp", "true");
assertThat(underTest.allowUsersToSignUp()).isTrue();
settings.setProperty("sonar.auth.bitbucket.allowUsersToSignUp", "false");
assertThat(underTest.allowUsersToSignUp()).isFalse();
}
@Test
public void default_apiUrl() {
assertThat(underTest.apiURL()).isEqualTo("https://api.bitbucket.org/");
}
@Test
public void default_webUrl() {
assertThat(underTest.webURL()).isEqualTo("https://bitbucket.org/");
}
@Test
public void definitions() {
assertThat(BitbucketSettings.definitions()).hasSize(5);
}
}
| 3,375 | 32.76 | 85 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/GsonEmailsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GsonEmailsTest {
@Test
public void testParse() {
String json = "{" +
"\"pagelen\": 10," +
"\"values\": [" +
"{" +
"\"is_primary\": true," +
"\"is_confirmed\": true," +
"\"type\": \"email\"," +
"\"email\": \"foo@bar.com\"," +
"\"links\": {" +
"\"self\": {" +
"\"href\": \"https://api.bitbucket.org/2.0/user/emails/foo@bar.com\"" +
"}" +
"}" +
"}" +
"]," +
"\"page\": 1," +
"\"size\": 1" +
"}";
GsonEmails emails = GsonEmails.parse(json);
assertThat(emails.getEmails()).hasSize(1);
assertThat(emails.getEmails().get(0).isPrimary()).isTrue();
assertThat(emails.getEmails().get(0).getEmail()).isEqualTo("foo@bar.com");
}
@Test
public void test_extractPrimaryEmail() {
String json = "{" +
"\"pagelen\": 10," +
"\"values\": [" +
"{" +
"\"is_primary\": false," +
"\"is_confirmed\": true," +
"\"type\": \"email\"," +
"\"email\": \"secondary@bar.com\"," +
"\"links\": {" +
"\"self\": {" +
"\"href\": \"https://api.bitbucket.org/2.0/user/emails/secondary@bar.com\"" +
"}" +
"}" +
"}," +
"{" +
"\"is_primary\": true," +
"\"is_confirmed\": true," +
"\"type\": \"email\"," +
"\"email\": \"primary@bar.com\"," +
"\"links\": {" +
"\"self\": {" +
"\"href\": \"https://api.bitbucket.org/2.0/user/emails/primary@bar.com\"" +
"}" +
"}" +
"}" +
"]," +
"\"page\": 1," +
"\"size\": 2" +
"}";
String email = GsonEmails.parse(json).extractPrimaryEmail();
assertThat(email).isEqualTo("primary@bar.com");
}
@Test
public void test_extractPrimaryEmail_not_found() {
String json = "{" +
"\"pagelen\": 10," +
"\"values\": [" +
"]," +
"\"page\": 1," +
"\"size\": 0" +
"}";
String email = GsonEmails.parse(json).extractPrimaryEmail();
assertThat(email).isNull();
}
}
| 2,980 | 28.22549 | 83 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/GsonUserTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GsonUserTest {
@Test
public void parse_from_json() {
GsonUser underTest = GsonUser.parse("{\"username\":\"john\", \"display_name\":\"John\", \"uuid\":\"ABCD\"}");
assertThat(underTest.getUsername()).isEqualTo("john");
assertThat(underTest.getDisplayName()).isEqualTo("John");
assertThat(underTest.getUuid()).isEqualTo("ABCD");
}
}
| 1,330 | 34.026316 | 113 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/IntegrationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.utils.System2;
import org.sonar.server.http.JavaxHttpRequest;
import static java.lang.String.format;
import static java.net.URLEncoder.encode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class IntegrationTest {
private static final String CALLBACK_URL = "http://localhost/oauth/callback/bitbucket";
@Rule
public MockWebServer bitbucket = new MockWebServer();
// load settings with default values
private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, BitbucketSettings.definitions()));
private final BitbucketSettings bitbucketSettings = spy(new BitbucketSettings(settings.asConfig()));
private final UserIdentityFactory userIdentityFactory = new UserIdentityFactory();
private final BitbucketScribeApi scribeApi = new BitbucketScribeApi(bitbucketSettings);
private final BitbucketIdentityProvider underTest = new BitbucketIdentityProvider(bitbucketSettings, userIdentityFactory, scribeApi);
@Before
public void setUp() {
settings.setProperty("sonar.auth.bitbucket.clientId.secured", "the_id");
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "the_secret");
settings.setProperty("sonar.auth.bitbucket.enabled", true);
when(bitbucketSettings.webURL()).thenReturn(format("http://%s:%d/", bitbucket.getHostName(), bitbucket.getPort()));
when(bitbucketSettings.apiURL()).thenReturn(format("http://%s:%d/", bitbucket.getHostName(), bitbucket.getPort()));
}
/**
* First phase: SonarQube redirects browser to Bitbucket authentication form, requesting the
* minimal access rights ("scope") to get user profile.
*/
@Test
public void redirect_browser_to_bitbucket_authentication_form() throws Exception {
DumbInitContext context = new DumbInitContext("the-csrf-state");
underTest.init(context);
assertThat(context.redirectedTo)
.startsWith(bitbucket.url("site/oauth2/authorize").toString())
.contains("scope=" + encode("account", StandardCharsets.UTF_8.name()));
}
/**
* Second phase: Bitbucket redirects browser to SonarQube at /oauth/callback/bitbucket?code={the verifier code}.
* This SonarQube web service sends three requests to Bitbucket:
* <ul>
* <li>get an access token</li>
* <li>get the profile (login, name) of the authenticated user</li>
* <li>get the emails of the authenticated user</li>
* </ul>
*/
@Test
public void authenticate_successfully() throws Exception {
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
HttpServletRequest request = newRequest("the-verifier-code");
DumbCallbackContext callbackContext = new DumbCallbackContext(request);
underTest.callback(callbackContext);
assertThat(callbackContext.csrfStateVerified.get()).isTrue();
assertThat(callbackContext.userIdentity.getName()).isEqualTo("John");
assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("john@bitbucket.org");
assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue();
// Verify the requests sent to Bitbucket
RecordedRequest accessTokenRequest = bitbucket.takeRequest();
assertThat(accessTokenRequest.getPath()).startsWith("/site/oauth2/access_token");
RecordedRequest userRequest = bitbucket.takeRequest();
assertThat(userRequest.getPath()).startsWith("/2.0/user");
RecordedRequest emailRequest = bitbucket.takeRequest();
assertThat(emailRequest.getPath()).startsWith("/2.0/user/emails");
// do not request user workspaces, workspace restriction is disabled by default
assertThat(bitbucket.getRequestCount()).isEqualTo(3);
}
@Test
public void callback_throws_ISE_if_error_when_requesting_user_profile() {
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
// https://api.bitbucket.org/2.0/user fails
bitbucket.enqueue(new MockResponse().setResponseCode(500).setBody("{error}"));
DumbCallbackContext callbackContext = new DumbCallbackContext(newRequest("the-verifier-code"));
assertThatThrownBy(() -> underTest.callback(callbackContext))
.hasMessage("Can not get Bitbucket user profile. HTTP code: 500, response: {error}")
.isInstanceOf(IllegalStateException.class);
assertThat(callbackContext.csrfStateVerified.get()).isTrue();
assertThat(callbackContext.userIdentity).isNull();
assertThat(callbackContext.redirectedToRequestedPage.get()).isFalse();
}
@Test
public void allow_authentication_if_user_is_member_of_one_restricted_workspace() {
settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
bitbucket.enqueue(newWorkspacesResponse("workspace3", "workspace2"));
HttpServletRequest request = newRequest("the-verifier-code");
DumbCallbackContext callbackContext = new DumbCallbackContext(request);
underTest.callback(callbackContext);
assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("john@bitbucket.org");
assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("john");
assertThat(callbackContext.userIdentity.getProviderId()).isEqualTo("john-uuid");
assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue();
}
@Test
public void forbid_authentication_if_user_is_not_member_of_one_restricted_workspace() {
settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
bitbucket.enqueue(newWorkspacesResponse("workspace3"));
DumbCallbackContext context = new DumbCallbackContext(newRequest("the-verifier-code"));
assertThatThrownBy(() -> underTest.callback(context))
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void forbid_authentication_if_user_is_not_member_of_any_workspace() {
settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
bitbucket.enqueue(newWorkspacesResponse(/* no workspaces */));
DumbCallbackContext context = new DumbCallbackContext(newRequest("the-verifier-code"));
assertThatThrownBy(() -> underTest.callback(context))
.isInstanceOf(UnauthorizedException.class);
}
/**
* Response sent by Bitbucket to SonarQube when generating an access token
*/
private static MockResponse newSuccessfulAccessTokenResponse() {
return new MockResponse().setBody("{\"access_token\":\"e72e16c7e42f292c6912e7710c838347ae178b4a\",\"scope\":\"user\"}");
}
/**
* Response of https://api.bitbucket.org/2.0/user
*/
private static MockResponse newUserResponse(String login, String name, String uuid) {
return new MockResponse().setBody("{\"username\":\"" + login + "\", \"display_name\":\"" + name + "\", \"uuid\":\"" + uuid + "\"}");
}
/**
* Response of https://api.bitbucket.org/2.0/user/permissions/workspaces?q=permission="member"
*/
private static MockResponse newWorkspacesResponse(String... workspaces) {
String s = Arrays.stream(workspaces)
.map(w -> "{\"workspace\":{\"name\":\"" + w + "\",\"slug\":\"" + w + "\"}}")
.collect(Collectors.joining(","));
return new MockResponse().setBody("{\"values\":[" + s + "]}");
}
/**
* Response of https://api.bitbucket.org/2.0/user/emails
*/
private static MockResponse newPrimaryEmailResponse(String email) {
return new MockResponse().setBody("{\"values\":[{\"active\": true,\"email\":\"" + email + "\",\"is_primary\": true}]}");
}
private static HttpServletRequest newRequest(String verifierCode) {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getParameter("code")).thenReturn(verifierCode);
return request;
}
private static class DumbCallbackContext implements OAuth2IdentityProvider.CallbackContext {
final HttpServletRequest request;
final AtomicBoolean csrfStateVerified = new AtomicBoolean(true);
final AtomicBoolean redirectedToRequestedPage = new AtomicBoolean(false);
UserIdentity userIdentity = null;
public DumbCallbackContext(HttpServletRequest request) {
this.request = request;
}
@Override
public void verifyCsrfState() {
this.csrfStateVerified.set(true);
}
@Override
public void verifyCsrfState(String s) {
}
@Override
public void redirectToRequestedPage() {
redirectedToRequestedPage.set(true);
}
@Override
public void authenticate(UserIdentity userIdentity) {
this.userIdentity = userIdentity;
}
@Override
public String getCallbackUrl() {
return CALLBACK_URL;
}
@Override
public HttpRequest getHttpRequest() {
return new JavaxHttpRequest(request);
}
@Override
public HttpResponse getHttpResponse() {
throw new UnsupportedOperationException("not used");
}
@Override
public HttpServletRequest getRequest() {
throw new UnsupportedOperationException("deprecated");
}
@Override
public HttpServletResponse getResponse() {
throw new UnsupportedOperationException("deprecated");
}
}
private static class DumbInitContext implements OAuth2IdentityProvider.InitContext {
String redirectedTo = null;
private final String generatedCsrfState;
public DumbInitContext(String generatedCsrfState) {
this.generatedCsrfState = generatedCsrfState;
}
@Override
public String generateCsrfState() {
return generatedCsrfState;
}
@Override
public void redirectTo(String url) {
this.redirectedTo = url;
}
@Override
public String getCallbackUrl() {
return CALLBACK_URL;
}
@Override
public HttpRequest getHttpRequest() {
return null;
}
@Override
public HttpResponse getHttpResponse() {
return null;
}
@Override
public HttpServletRequest getRequest() {
return null;
}
@Override
public HttpServletResponse getResponse() {
return null;
}
}
}
| 12,558 | 37.762346 | 136 | java |
sonarqube | sonarqube-master/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/UserIdentityFactoryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import org.junit.Test;
import org.sonar.api.server.authentication.UserIdentity;
import static org.assertj.core.api.Assertions.assertThat;
public class UserIdentityFactoryTest {
private UserIdentityFactory underTest = new UserIdentityFactory();
@Test
public void create_login() {
GsonUser gson = new GsonUser("john", "John", "ABCD");
UserIdentity identity = underTest.create(gson, null);
assertThat(identity.getName()).isEqualTo("John");
assertThat(identity.getEmail()).isNull();
assertThat(identity.getProviderId()).isEqualTo("ABCD");
}
@Test
public void empty_name_is_replaced_by_provider_login() {
GsonUser gson = new GsonUser("john", "", "ABCD");
UserIdentity identity = underTest.create(gson, null);
assertThat(identity.getName()).isEqualTo("john");
}
@Test
public void null_name_is_replaced_by_provider_login() {
GsonUser gson = new GsonUser("john", null, "ABCD");
UserIdentity identity = underTest.create(gson, null);
assertThat(identity.getName()).isEqualTo("john");
}
}
| 1,929 | 32.859649 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-common/src/main/java/org/sonar/auth/OAuthRestClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.String.format;
public class OAuthRestClient {
private static final int DEFAULT_PAGE_SIZE = 100;
private static final Pattern NEXT_LINK_PATTERN = Pattern.compile("<([^<]+)>; rel=\"next\"");
private OAuthRestClient() {
// Only static method
}
public static Response executeRequest(String requestUrl, OAuth20Service scribe, OAuth2AccessToken accessToken) throws IOException {
OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl);
scribe.signRequest(accessToken, request);
try {
Response response = scribe.execute(request);
if (!response.isSuccessful()) {
throw unexpectedResponseCode(requestUrl, response);
}
return response;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
} catch (ExecutionException e) {
throw new IllegalStateException(e);
}
}
public static <E> List<E> executePaginatedRequest(String request, OAuth20Service scribe, OAuth2AccessToken accessToken, Function<String, List<E>> function) {
List<E> result = new ArrayList<>();
readPage(result, scribe, accessToken, addPerPageQueryParameter(request, DEFAULT_PAGE_SIZE), function);
return result;
}
public static String addPerPageQueryParameter(String request, int pageSize) {
String separator = request.contains("?") ? "&" : "?";
return request + separator + "per_page=" + pageSize;
}
private static <E> void readPage(List<E> result, OAuth20Service scribe, OAuth2AccessToken accessToken, String endPoint, Function<String, List<E>> function) {
try (Response nextResponse = executeRequest(endPoint, scribe, accessToken)) {
String content = nextResponse.getBody();
if (content == null) {
return;
}
result.addAll(function.apply(content));
readNextEndPoint(nextResponse).ifPresent(newNextEndPoint -> readPage(result, scribe, accessToken, newNextEndPoint, function));
} catch (IOException e) {
throw new IllegalStateException(format("Failed to get %s", endPoint), e);
}
}
private static Optional<String> readNextEndPoint(Response response) {
String link = response.getHeaders().entrySet().stream()
.filter(e -> "Link".equalsIgnoreCase(e.getKey()))
.map(Map.Entry::getValue)
.findAny().orElse("");
Matcher nextLinkMatcher = NEXT_LINK_PATTERN.matcher(link);
if (!nextLinkMatcher.find()) {
return Optional.empty();
}
return Optional.of(nextLinkMatcher.group(1));
}
private static IllegalStateException unexpectedResponseCode(String requestUrl, Response response) throws IOException {
return new IllegalStateException(format("Fail to execute request '%s'. HTTP code: %s, response: %s", requestUrl, response.getCode(), response.getBody()));
}
}
| 4,241 | 38.64486 | 159 | java |
sonarqube | sonarqube-master/server/sonar-auth-common/src/main/java/org/sonar/auth/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.auth;
import javax.annotation.ParametersAreNonnullByDefault;
| 954 | 38.791667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static java.lang.String.format;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.sonar.auth.OAuthRestClient.executePaginatedRequest;
import static org.sonar.auth.OAuthRestClient.executeRequest;
public class OAuthRestClientTest {
@Rule
public MockWebServer mockWebServer = new MockWebServer();
private OAuth2AccessToken auth2AccessToken = mock(OAuth2AccessToken.class);
private String serverUrl;
private OAuth20Service oAuth20Service = new ServiceBuilder("API_KEY")
.apiSecret("API_SECRET")
.callback("CALLBACK")
.build(new TestAPI());
@Before
public void setUp() {
this.serverUrl = format("http://%s:%d", mockWebServer.getHostName(), mockWebServer.getPort());
}
@Test
public void execute_request() throws IOException {
String body = randomAlphanumeric(10);
mockWebServer.enqueue(new MockResponse().setBody(body));
Response response = executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken);
assertThat(response.getBody()).isEqualTo(body);
}
@Test
public void fail_to_execute_request() throws IOException {
mockWebServer.enqueue(new MockResponse().setResponseCode(404).setBody("Error!"));
assertThatThrownBy(() -> executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken))
.isInstanceOf(IllegalStateException.class)
.hasMessage(format("Fail to execute request '%s/test'. HTTP code: 404, response: Error!", serverUrl));
}
@Test
public void execute_paginated_request() {
mockWebServer.enqueue(new MockResponse()
.setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?per_page=100&page=2>; rel=\"last\"")
.setBody("A"));
mockWebServer.enqueue(new MockResponse()
.setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=1>; rel=\"prev\", <" + serverUrl + "/test?per_page=100&page=1>; rel=\"first\"")
.setBody("B"));
List<String> response = executePaginatedRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken, Arrays::asList);
assertThat(response).contains("A", "B");
}
@Test
public void execute_paginated_request_with_query_parameter() throws InterruptedException {
mockWebServer.enqueue(new MockResponse()
.setHeader("Link", "<" + serverUrl + "/test?param=value&per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?param=value&per_page=100&page=2>; rel=\"last\"")
.setBody("A"));
mockWebServer.enqueue(new MockResponse()
.setHeader("Link", "<" + serverUrl + "/test?param=value&per_page=100&page=1>; rel=\"prev\", <" + serverUrl + "/test?param=value&per_page=100&page=1>; rel=\"first\"")
.setBody("B"));
List<String> response = executePaginatedRequest(serverUrl + "/test?param=value", oAuth20Service, auth2AccessToken, Arrays::asList);
assertThat(response).contains("A", "B");
assertThat(mockWebServer.takeRequest().getPath()).isEqualTo("/test?param=value&per_page=100");
assertThat(mockWebServer.takeRequest().getPath()).isEqualTo("/test?param=value&per_page=100&page=2");
}
@Test
public void execute_paginated_request_case_insensitive_headers() {
mockWebServer.enqueue(new MockResponse()
.setHeader("link", "<" + serverUrl + "/test?per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?per_page=100&page=2>; rel=\"last\"")
.setBody("A"));
mockWebServer.enqueue(new MockResponse()
.setHeader("link", "<" + serverUrl + "/test?per_page=100&page=1>; rel=\"prev\", <" + serverUrl + "/test?per_page=100&page=1>; rel=\"first\"")
.setBody("B"));
List<String> response = executePaginatedRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken, Arrays::asList);
assertThat(response).contains("A", "B");
}
@Test
public void fail_to_executed_paginated_request() {
mockWebServer.enqueue(new MockResponse()
.setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?per_page=100&page=2>; rel=\"last\"")
.setBody("A"));
mockWebServer.enqueue(new MockResponse().setResponseCode(404).setBody("Error!"));
assertThatThrownBy(() -> executePaginatedRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken, Arrays::asList))
.isInstanceOf(IllegalStateException.class)
.hasMessage(format("Fail to execute request '%s/test?per_page=100&page=2'. HTTP code: 404, response: Error!", serverUrl));
}
private class TestAPI extends DefaultApi20 {
@Override
public String getAccessTokenEndpoint() {
return serverUrl + "/login/oauth/access_token";
}
@Override
protected String getAuthorizationBaseUrl() {
return serverUrl + "/login/oauth/authorize";
}
}
}
| 6,315 | 40.552632 | 171 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GitHubIdentityProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
public class GitHubIdentityProvider implements OAuth2IdentityProvider {
public static final String KEY = "github";
private final GitHubSettings settings;
private final UserIdentityFactory userIdentityFactory;
private final ScribeGitHubApi scribeApi;
private final GitHubRestClient gitHubRestClient;
public GitHubIdentityProvider(GitHubSettings settings, UserIdentityFactory userIdentityFactory, ScribeGitHubApi scribeApi, GitHubRestClient gitHubRestClient) {
this.settings = settings;
this.userIdentityFactory = userIdentityFactory;
this.scribeApi = scribeApi;
this.gitHubRestClient = gitHubRestClient;
}
@Override
public String getKey() {
return KEY;
}
@Override
public String getName() {
return "GitHub";
}
@Override
public Display getDisplay() {
return Display.builder()
.setIconPath("/images/alm/github-white.svg")
.setBackgroundColor("#444444")
.build();
}
@Override
public boolean isEnabled() {
return settings.isEnabled();
}
@Override
public boolean allowsUsersToSignUp() {
return settings.allowUsersToSignUp();
}
@Override
public void init(InitContext context) {
String state = context.generateCsrfState();
OAuth20Service scribe = newScribeBuilder(context)
.defaultScope(getScope())
.build(scribeApi);
String url = scribe.getAuthorizationUrl(state);
context.redirectTo(url);
}
String getScope() {
return (settings.syncGroups() || isOrganizationMembershipRequired()) ? "user:email,read:org" : "user:email";
}
@Override
public void callback(CallbackContext context) {
try {
onCallback(context);
} catch (IOException | ExecutionException e) {
throw new IllegalStateException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
private void onCallback(CallbackContext context) throws InterruptedException, ExecutionException, IOException {
context.verifyCsrfState();
HttpRequest request = context.getHttpRequest();
OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
String code = request.getParameter("code");
OAuth2AccessToken accessToken = scribe.getAccessToken(code);
GsonUser user = gitHubRestClient.getUser(scribe, accessToken);
check(scribe, accessToken, user);
final String email;
if (user.getEmail() == null) {
// if the user has not specified a public email address in their profile
email = gitHubRestClient.getEmail(scribe, accessToken);
} else {
email = user.getEmail();
}
UserIdentity userIdentity = userIdentityFactory.create(user, email,
settings.syncGroups() ? gitHubRestClient.getTeams(scribe, accessToken) : null);
context.authenticate(userIdentity);
context.redirectToRequestedPage();
}
boolean isOrganizationMembershipRequired() {
return !settings.getOrganizations().isEmpty();
}
private void check(OAuth20Service scribe, OAuth2AccessToken accessToken, GsonUser user) throws InterruptedException, ExecutionException, IOException {
if (isUnauthorized(scribe, accessToken, user.getLogin())) {
throw new UnauthorizedException(format("'%s' must be a member of at least one organization: '%s'", user.getLogin(), String.join("', '", settings.getOrganizations())));
}
}
private boolean isUnauthorized(OAuth20Service scribe, OAuth2AccessToken accessToken, String login) throws IOException, ExecutionException, InterruptedException {
return isOrganizationMembershipRequired() && !isOrganizationsMember(scribe, accessToken, login);
}
private boolean isOrganizationsMember(OAuth20Service scribe, OAuth2AccessToken accessToken, String login) throws IOException, ExecutionException, InterruptedException {
for (String organization : settings.getOrganizations()) {
if (gitHubRestClient.isOrganizationMember(scribe, accessToken, organization, login)) {
return true;
}
}
return false;
}
private ServiceBuilder newScribeBuilder(OAuth2IdentityProvider.OAuth2Context context) {
checkState(isEnabled(), "GitHub authentication is disabled");
return new ServiceBuilder(settings.clientId())
.apiSecret(settings.clientSecret())
.callback(context.getCallbackUrl());
}
}
| 5,850 | 35.117284 | 173 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GitHubModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.List;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.core.platform.Module;
import static org.sonar.auth.github.GitHubSettings.definitions;
public class GitHubModule extends Module {
private static final List<Class<?>> COMPONENT_CLASSES = List.of(
GitHubIdentityProvider.class,
GitHubRestClient.class,
UserIdentityFactoryImpl.class,
ScribeGitHubApi.class
);
@Override
protected void configureModule() {
add(COMPONENT_CLASSES);
List<PropertyDefinition> definitions = definitions();
add(definitions.toArray(new Object[definitions.size()]));
}
}
| 1,493 | 33.744186 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GitHubRestClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static org.sonar.auth.OAuthRestClient.executePaginatedRequest;
import static org.sonar.auth.OAuthRestClient.executeRequest;
public class GitHubRestClient {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubRestClient.class);
private final GitHubSettings settings;
public GitHubRestClient(GitHubSettings settings) {
this.settings = settings;
}
GsonUser getUser(OAuth20Service scribe, OAuth2AccessToken accessToken) throws IOException {
String responseBody = executeRequest(settings.apiURL() + "user", scribe, accessToken).getBody();
LOGGER.trace("User response received : {}", responseBody);
return GsonUser.parse(responseBody);
}
String getEmail(OAuth20Service scribe, OAuth2AccessToken accessToken) throws IOException {
String responseBody = executeRequest(settings.apiURL() + "user/emails", scribe, accessToken).getBody();
LOGGER.trace("Emails response received : {}", responseBody);
List<GsonEmail> emails = GsonEmail.parse(responseBody);
return emails.stream()
.filter(email -> email.isPrimary() && email.isVerified())
.findFirst()
.map(GsonEmail::getEmail)
.orElse(null);
}
List<GsonTeam> getTeams(OAuth20Service scribe, OAuth2AccessToken accessToken) {
return executePaginatedRequest(settings.apiURL() + "user/teams", scribe, accessToken, GsonTeam::parse);
}
/**
* Check to see that login is a member of organization.
*
* A 204 response code indicates organization membership. 302 and 404 codes are not treated as exceptional,
* they indicate various ways in which a login is not a member of the organization.
*
* @see <a href="https://developer.github.com/v3/orgs/members/#response-if-requester-is-an-organization-member-and-user-is-a-member">GitHub members API</a>
*/
boolean isOrganizationMember(OAuth20Service scribe, OAuth2AccessToken accessToken, String organization, String login)
throws IOException, ExecutionException, InterruptedException {
String requestUrl = settings.apiURL() + format("orgs/%s/members/%s", organization, login);
OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl);
scribe.signRequest(accessToken, request);
Response response = scribe.execute(request);
int code = response.getCode();
switch (code) {
case HttpURLConnection.HTTP_MOVED_TEMP, HttpURLConnection.HTTP_NOT_FOUND, HttpURLConnection.HTTP_NO_CONTENT:
LOGGER.trace("Orgs response received : {}", code);
return code == HttpURLConnection.HTTP_NO_CONTENT;
default:
throw unexpectedResponseCode(requestUrl, response);
}
}
private static IllegalStateException unexpectedResponseCode(String requestUrl, Response response) throws IOException {
return new IllegalStateException(format("Fail to execute request '%s'. HTTP code: %s, response: %s", requestUrl, response.getCode(), response.getBody()));
}
}
| 4,287 | 42.755102 | 158 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GitHubSettings.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.google.common.annotations.VisibleForTesting;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.PropertyType;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.property.InternalProperties;
import static java.lang.String.format;
import static java.lang.String.valueOf;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.api.PropertyType.BOOLEAN;
import static org.sonar.api.PropertyType.PASSWORD;
import static org.sonar.api.PropertyType.STRING;
import static org.sonar.api.utils.Preconditions.checkState;
@ServerSide
@ComputeEngineSide
public class GitHubSettings {
public static final String CLIENT_ID = "sonar.auth.github.clientId.secured";
public static final String CLIENT_SECRET = "sonar.auth.github.clientSecret.secured";
public static final String APP_ID = "sonar.auth.github.appId";
public static final String PRIVATE_KEY = "sonar.auth.github.privateKey.secured";
public static final String ENABLED = "sonar.auth.github.enabled";
public static final String ALLOW_USERS_TO_SIGN_UP = "sonar.auth.github.allowUsersToSignUp";
public static final String GROUPS_SYNC = "sonar.auth.github.groupsSync";
public static final String API_URL = "sonar.auth.github.apiUrl";
public static final String DEFAULT_API_URL = "https://api.github.com/";
public static final String WEB_URL = "sonar.auth.github.webUrl";
public static final String DEFAULT_WEB_URL = "https://github.com/";
public static final String ORGANIZATIONS = "sonar.auth.github.organizations";
@VisibleForTesting
static final String PROVISIONING = "provisioning.github.enabled";
private static final String CATEGORY = "authentication";
private static final String SUBCATEGORY = "github";
private final Configuration configuration;
private final InternalProperties internalProperties;
private final DbClient dbClient;
public GitHubSettings(Configuration configuration, InternalProperties internalProperties, DbClient dbClient) {
this.configuration = configuration;
this.internalProperties = internalProperties;
this.dbClient = dbClient;
}
String clientId() {
return configuration.get(CLIENT_ID).orElse("");
}
String clientSecret() {
return configuration.get(CLIENT_SECRET).orElse("");
}
public String appId() {
return configuration.get(APP_ID).orElse("");
}
public String privateKey() {
return configuration.get(PRIVATE_KEY).orElse("");
}
public boolean isEnabled() {
return configuration.getBoolean(ENABLED).orElse(false) && !clientId().isEmpty() && !clientSecret().isEmpty();
}
boolean allowUsersToSignUp() {
return configuration.getBoolean(ALLOW_USERS_TO_SIGN_UP).orElse(false);
}
boolean syncGroups() {
return configuration.getBoolean(GROUPS_SYNC).orElse(false);
}
@CheckForNull
String webURL() {
return urlWithEndingSlash(configuration.get(WEB_URL).orElse(""));
}
@CheckForNull
public String apiURL() {
return urlWithEndingSlash(configuration.get(API_URL).orElse(""));
}
public String apiURLOrDefault() {
return configuration.get(API_URL).map(GitHubSettings::urlWithEndingSlash).orElse(DEFAULT_API_URL);
}
public Set<String> getOrganizations() {
return Set.of(configuration.getStringArray(ORGANIZATIONS));
}
@CheckForNull
private static String urlWithEndingSlash(@Nullable String url) {
if (url != null && !url.endsWith("/")) {
return url + "/";
}
return url;
}
public void setProvisioning(boolean enableProvisioning) {
if (enableProvisioning) {
checkGithubConfigIsCompleteForProvisioning();
} else {
removeExternalGroupsForGithub();
}
internalProperties.write(PROVISIONING, String.valueOf(enableProvisioning));
}
private void removeExternalGroupsForGithub() {
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.externalGroupDao().deleteByExternalIdentityProvider(dbSession, GitHubIdentityProvider.KEY);
dbSession.commit();
}
}
private void checkGithubConfigIsCompleteForProvisioning() {
checkState(isEnabled(), getErrorMessage("GitHub authentication must be enabled"));
checkState(isNotBlank(appId()), getErrorMessage("Application ID must be provided"));
checkState(isNotBlank(privateKey()), getErrorMessage("Private key must be provided"));
}
private static String getErrorMessage(String prefix) {
return format("%s to enable GitHub provisioning.", prefix);
}
public boolean isProvisioningEnabled() {
return isEnabled() && internalProperties.read(PROVISIONING).map(Boolean::parseBoolean).orElse(false);
}
public static List<PropertyDefinition> definitions() {
int index = 1;
return Arrays.asList(
PropertyDefinition.builder(ENABLED)
.name("Enabled")
.description("Enable GitHub users to login. Value is ignored if client ID and secret are not defined.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(BOOLEAN)
.defaultValue(valueOf(false))
.index(index++)
.build(),
PropertyDefinition.builder(CLIENT_ID)
.name("Client ID")
.description("Client ID provided by GitHub when registering the application.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.index(index++)
.build(),
PropertyDefinition.builder(CLIENT_SECRET)
.name("Client Secret")
.description("Client password provided by GitHub when registering the application.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(PASSWORD)
.index(index++)
.build(),
PropertyDefinition.builder(APP_ID)
.name("App ID")
.description("The App ID is found on your GitHub App's page on GitHub at Settings > Developer Settings > GitHub Apps.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(STRING)
.index(index++)
.build(),
PropertyDefinition.builder(PRIVATE_KEY)
.name("Private Key")
.description("""
Your GitHub App's private key. You can generate a .pem file from your GitHub App's page under Private keys.
Copy and paste the whole contents of the file here.""")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(PropertyType.TEXT)
.index(index++)
.build(),
PropertyDefinition.builder(ALLOW_USERS_TO_SIGN_UP)
.name("Allow users to sign up")
.description("Allow new users to authenticate. When set to 'false', only existing users will be able to authenticate to the server.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(BOOLEAN)
.defaultValue(valueOf(true))
.index(index++)
.build(),
PropertyDefinition.builder(GROUPS_SYNC)
.name("Synchronize teams as groups")
.description("For each team they belong to, the user will be associated to a group named 'Organization/Team' (if it exists) in SonarQube.")
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(BOOLEAN)
.defaultValue(valueOf(false))
.index(index++)
.build(),
PropertyDefinition.builder(API_URL)
.name("The API url for a GitHub instance.")
.description(String.format("The API url for a GitHub instance. %s for Github.com, https://github.company.com/api/v3/ when using Github Enterprise", DEFAULT_API_URL))
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(STRING)
.defaultValue(DEFAULT_API_URL)
.index(index++)
.build(),
PropertyDefinition.builder(WEB_URL)
.name("The WEB url for a GitHub instance.")
.description(String.format("The WEB url for a GitHub instance. %s for Github.com, https://github.company.com/ when using GitHub Enterprise.", DEFAULT_WEB_URL))
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.type(STRING)
.defaultValue(DEFAULT_WEB_URL)
.index(index++)
.build(),
PropertyDefinition.builder(ORGANIZATIONS)
.name("Organizations")
.description("Only members of these organizations will be able to authenticate to the server. "
+ "⚠ if not set, users from any organization where the GitHub App is installed will be able to login to this SonarQube instance.")
.multiValues(true)
.category(CATEGORY)
.subCategory(SUBCATEGORY)
.index(index)
.build());
}
}
| 9,685 | 36.984314 | 173 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GithubTeamConverter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GithubTeamConverter {
private static final Pattern TEAM_NAME_PATTERN = Pattern.compile("([^/]+)/(.+)");
private GithubTeamConverter() {
}
public static String toGroupName(GsonTeam team) {
return toGroupName(team.getOrganizationId(), team.getId());
}
public static String toGroupName(String organization, String groupName) {
return organization + "/" + groupName;
}
public static Optional<String> extractOrganizationName(String groupName) {
return extractRegexGroupIfMatches(groupName, 1);
}
public static Optional<String> extractTeamName(String groupName) {
return extractRegexGroupIfMatches(groupName, 2);
}
private static Optional<String> extractRegexGroupIfMatches(String groupName, int regexGroup) {
Matcher matcher = TEAM_NAME_PATTERN.matcher(groupName);
if (!matcher.matches()) {
return Optional.empty();
} else {
return Optional.of(matcher.group(regexGroup));
}
}
}
| 1,930 | 32.293103 | 96 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GsonEmail.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
/**
* Lite representation of JSON response of GET https://api.github.com/user/emails
*/
public class GsonEmail {
private String email;
private boolean verified;
private boolean primary;
public GsonEmail() {
// http://stackoverflow.com/a/18645370/229031
this("", false, false);
}
public GsonEmail(String email, boolean verified, boolean primary) {
this.email = email;
this.verified = verified;
this.primary = primary;
}
public String getEmail() {
return email;
}
public boolean isVerified() {
return verified;
}
public boolean isPrimary() {
return primary;
}
public static List<GsonEmail> parse(String json) {
Type collectionType = new TypeToken<Collection<GsonEmail>>() {
}.getType();
Gson gson = new Gson();
return gson.fromJson(json, collectionType);
}
}
| 1,874 | 26.985075 | 81 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GsonTeam.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
/**
* Lite representation of JSON response of GET https://api.github.com/user/teams
*/
public class GsonTeam {
private String slug;
private GsonOrganization organization;
public GsonTeam() {
// http://stackoverflow.com/a/18645370/229031
this("", new GsonOrganization());
}
public GsonTeam(String slug, GsonOrganization organization) {
this.slug = slug;
this.organization = organization;
}
public String getId() {
return slug;
}
public String getOrganizationId() {
return organization.getLogin();
}
public static List<GsonTeam> parse(String json) {
Type collectionType = new TypeToken<Collection<GsonTeam>>() {
}.getType();
Gson gson = new Gson();
return gson.fromJson(json, collectionType);
}
public static class GsonOrganization {
private String login;
public GsonOrganization() {
// http://stackoverflow.com/a/18645370/229031
this("");
}
public GsonOrganization(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
}
}
| 2,111 | 26.076923 | 80 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/GsonUser.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.google.gson.Gson;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/**
* Lite representation of JSON response of GET https://api.github.com/user
*/
public class GsonUser {
private String id;
private String login;
private String name;
private String email;
public GsonUser() {
// even if empty constructor is not required for Gson, it is strongly
// recommended:
// http://stackoverflow.com/a/18645370/229031
}
public GsonUser(String id, String login, @Nullable String name, @Nullable String email) {
this.id = id;
this.login = login;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public String getLogin() {
return login;
}
/**
* Name is optional at GitHub
*/
@CheckForNull
public String getName() {
return name;
}
/**
* Name is optional at GitHub
*/
@CheckForNull
public String getEmail() {
return email;
}
public static GsonUser parse(String json) {
Gson gson = new Gson();
return gson.fromJson(json, GsonUser.class);
}
}
| 1,981 | 24.74026 | 91 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/ScribeGitHubApi.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import com.github.scribejava.apis.GitHubApi;
public class ScribeGitHubApi extends GitHubApi {
private final GitHubSettings settings;
public ScribeGitHubApi(GitHubSettings settings) {
this.settings = settings;
}
@Override
public String getAccessTokenEndpoint() {
return settings.webURL() + "login/oauth/access_token";
}
@Override
protected String getAuthorizationBaseUrl() {
return settings.webURL() + "login/oauth/authorize";
}
}
| 1,340 | 30.928571 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/UserIdentityFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.server.authentication.UserIdentity;
/**
* Converts GitHub JSON response to {@link UserIdentity}
*/
public interface UserIdentityFactory {
UserIdentity create(GsonUser user, @Nullable String email, @Nullable List<GsonTeam> teams);
}
| 1,191 | 35.121212 | 93 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/UserIdentityFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.server.authentication.UserIdentity;
public class UserIdentityFactoryImpl implements UserIdentityFactory {
@Override
public UserIdentity create(GsonUser user, @Nullable String email, @Nullable List<GsonTeam> teams) {
UserIdentity.Builder builder = UserIdentity.builder()
.setProviderId(user.getId())
.setProviderLogin(user.getLogin())
.setName(generateName(user))
.setEmail(email);
if (teams != null) {
builder.setGroups(teams.stream()
.map(GithubTeamConverter::toGroupName)
.collect(Collectors.toSet()));
}
return builder.build();
}
private static String generateName(GsonUser gson) {
String name = gson.getName();
return name == null || name.isEmpty() ? gson.getLogin() : name;
}
}
| 1,756 | 34.14 | 101 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/main/java/org/sonar/auth/github/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.auth.github;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 39.083333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubIdentityProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.db.DbClient;
import org.sonar.server.property.InternalProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GitHubIdentityProviderTest {
private MapSettings settings = new MapSettings();
private InternalProperties internalProperties = mock(InternalProperties.class);
private GitHubSettings gitHubSettings = new GitHubSettings(settings.asConfig(), internalProperties, mock(DbClient.class));
private UserIdentityFactoryImpl userIdentityFactory = mock(UserIdentityFactoryImpl.class);
private ScribeGitHubApi scribeApi = new ScribeGitHubApi(gitHubSettings);
private GitHubRestClient gitHubRestClient = new GitHubRestClient(gitHubSettings);
private GitHubIdentityProvider underTest = new GitHubIdentityProvider(gitHubSettings, userIdentityFactory, scribeApi, gitHubRestClient);
@Test
public void check_fields() {
assertThat(underTest.getKey()).isEqualTo("github");
assertThat(underTest.getName()).isEqualTo("GitHub");
assertThat(underTest.getDisplay().getIconPath()).isEqualTo("/images/alm/github-white.svg");
assertThat(underTest.getDisplay().getBackgroundColor()).isEqualTo("#444444");
}
@Test
public void is_enabled() {
settings.setProperty("sonar.auth.github.clientId.secured", "id");
settings.setProperty("sonar.auth.github.clientSecret.secured", "secret");
settings.setProperty("sonar.auth.github.enabled", true);
assertThat(underTest.isEnabled()).isTrue();
settings.setProperty("sonar.auth.github.enabled", false);
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void should_allow_users_to_signup() {
assertThat(underTest.allowsUsersToSignUp()).as("default").isFalse();
settings.setProperty("sonar.auth.github.allowUsersToSignUp", true);
assertThat(underTest.allowsUsersToSignUp()).isTrue();
}
@Test
public void init() {
setSettings(true);
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
when(context.generateCsrfState()).thenReturn("state");
when(context.getCallbackUrl()).thenReturn("http://localhost/callback");
settings.setProperty("sonar.auth.github.webUrl", "https://github.com/");
underTest.init(context);
verify(context).redirectTo("https://github.com/login/oauth/authorize" +
"?response_type=code" +
"&client_id=id" +
"&redirect_uri=http%3A%2F%2Flocalhost%2Fcallback&scope=user%3Aemail" +
"&state=state");
}
@Test
public void init_when_group_sync() {
setSettings(true);
settings.setProperty("sonar.auth.github.groupsSync", "true");
settings.setProperty("sonar.auth.github.webUrl", "https://github.com/");
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
when(context.generateCsrfState()).thenReturn("state");
when(context.getCallbackUrl()).thenReturn("http://localhost/callback");
underTest.init(context);
verify(context).redirectTo("https://github.com/login/oauth/authorize" +
"?response_type=code" +
"&client_id=id" +
"&redirect_uri=http%3A%2F%2Flocalhost%2Fcallback&scope=user%3Aemail%2Cread%3Aorg" +
"&state=state");
}
@Test
public void init_when_organizations() {
setSettings(true);
settings.setProperty("sonar.auth.github.organizations", "example");
settings.setProperty("sonar.auth.github.webUrl", "https://github.com/");
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
when(context.generateCsrfState()).thenReturn("state");
when(context.getCallbackUrl()).thenReturn("http://localhost/callback");
underTest.init(context);
verify(context).redirectTo("https://github.com/login/oauth/authorize" +
"?response_type=code" +
"&client_id=id" +
"&redirect_uri=http%3A%2F%2Flocalhost%2Fcallback" +
"&scope=user%3Aemail%2Cread%3Aorg" +
"&state=state");
}
@Test
public void fail_to_init_when_disabled() {
setSettings(false);
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
assertThatThrownBy(() -> underTest.init(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("GitHub authentication is disabled");
}
@Test
public void scope_includes_org_when_necessary() {
setSettings(false);
settings.setProperty("sonar.auth.github.groupsSync", false);
settings.setProperty("sonar.auth.github.organizations", "");
assertThat(underTest.getScope()).isEqualTo("user:email");
settings.setProperty("sonar.auth.github.groupsSync", true);
settings.setProperty("sonar.auth.github.organizations", "");
assertThat(underTest.getScope()).isEqualTo("user:email,read:org");
settings.setProperty("sonar.auth.github.groupsSync", false);
settings.setProperty("sonar.auth.github.organizations", "example");
assertThat(underTest.getScope()).isEqualTo("user:email,read:org");
settings.setProperty("sonar.auth.github.groupsSync", true);
settings.setProperty("sonar.auth.github.organizations", "example");
assertThat(underTest.getScope()).isEqualTo("user:email,read:org");
}
@Test
public void organization_membership_required() {
setSettings(true);
settings.setProperty("sonar.auth.github.organizations", "example");
assertThat(underTest.isOrganizationMembershipRequired()).isTrue();
settings.setProperty("sonar.auth.github.organizations", "example0, example1");
assertThat(underTest.isOrganizationMembershipRequired()).isTrue();
}
@Test
public void organization_membership_not_required() {
setSettings(true);
settings.setProperty("sonar.auth.github.organizations", "");
assertThat(underTest.isOrganizationMembershipRequired()).isFalse();
}
private void setSettings(boolean enabled) {
if (enabled) {
settings.setProperty("sonar.auth.github.clientId.secured", "id");
settings.setProperty("sonar.auth.github.clientSecret.secured", "secret");
settings.setProperty("sonar.auth.github.enabled", true);
} else {
settings.setProperty("sonar.auth.github.enabled", false);
}
}
}
| 7,368 | 39.26776 | 138 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class GitHubModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new GitHubModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(14);
}
}
| 1,256 | 32.972973 | 75 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubSettingsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.Optional;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.server.property.InternalProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GitHubSettingsTest {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, GitHubSettings.definitions()));
private InternalProperties internalProperties = mock(InternalProperties.class);
private GitHubSettings underTest = new GitHubSettings(settings.asConfig(), internalProperties, db.getDbClient());
@Test
public void is_enabled() {
enableGithubAuthentication();
assertThat(underTest.isEnabled()).isTrue();
settings.setProperty("sonar.auth.github.enabled", false);
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void is_enabled_always_return_false_when_client_id_is_null() {
settings.setProperty("sonar.auth.github.enabled", true);
settings.setProperty("sonar.auth.github.clientId.secured", (String) null);
settings.setProperty("sonar.auth.github.clientSecret.secured", "secret");
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void is_enabled_always_return_false_when_client_secret_is_null() {
settings.setProperty("sonar.auth.github.enabled", true);
settings.setProperty("sonar.auth.github.clientId.secured", "id");
settings.setProperty("sonar.auth.github.clientSecret.secured", (String) null);
assertThat(underTest.isEnabled()).isFalse();
}
@Test
public void isProvisioningEnabled_returnsFalseByDefault() {
enableGithubAuthentication();
when(internalProperties.read(GitHubSettings.PROVISIONING)).thenReturn(Optional.empty());
assertThat(underTest.isProvisioningEnabled()).isFalse();
}
@Test
public void isProvisioningEnabled_ifProvisioningEnabledButGithubAuthNotSet_returnsFalse() {
enableGithubAuthentication();
when(internalProperties.read(GitHubSettings.PROVISIONING)).thenReturn(Optional.of(Boolean.FALSE.toString()));
assertThat(underTest.isProvisioningEnabled()).isFalse();
}
@Test
public void isProvisioningEnabled_ifProvisioningEnabledButGithubAuthDisabled_returnsFalse() {
when(internalProperties.read(GitHubSettings.PROVISIONING)).thenReturn(Optional.of(Boolean.TRUE.toString()));
assertThat(underTest.isProvisioningEnabled()).isFalse();
}
@Test
public void isProvisioningEnabled_ifProvisioningEnabledAndGithubAuthEnabled_returnsTrue() {
enableGithubAuthenticationWithGithubApp();
when(internalProperties.read(GitHubSettings.PROVISIONING)).thenReturn(Optional.of(Boolean.TRUE.toString()));
assertThat(underTest.isProvisioningEnabled()).isTrue();
}
@Test
public void setProvisioning_whenGitHubAuthDisabled_shouldThrow() {
assertThatIllegalStateException()
.isThrownBy(() -> underTest.setProvisioning(true))
.withMessage("GitHub authentication must be enabled to enable GitHub provisioning.");
assertThat(underTest.isProvisioningEnabled()).isFalse();
}
@Test
public void setProvisioning_whenPrivateKeyMissing_shouldThrow() {
enableGithubAuthenticationWithGithubApp();
settings.setProperty("sonar.auth.github.privateKey.secured", "");
assertThatIllegalStateException()
.isThrownBy(() -> underTest.setProvisioning(true))
.withMessage("Private key must be provided to enable GitHub provisioning.");
assertThat(underTest.isProvisioningEnabled()).isFalse();
}
@Test
public void setProvisioning_whenAppIdMissing_shouldThrow() {
enableGithubAuthenticationWithGithubApp();
settings.setProperty("sonar.auth.github.appId", "");
assertThatIllegalStateException()
.isThrownBy(() -> underTest.setProvisioning(true))
.withMessage("Application ID must be provided to enable GitHub provisioning.");
assertThat(underTest.isProvisioningEnabled()).isFalse();
}
@Test
public void setProvisioning_whenPassedTrue_delegatesToInternalPropertiesWrite() {
enableGithubAuthenticationWithGithubApp();
underTest.setProvisioning(true);
verify(internalProperties).write(GitHubSettings.PROVISIONING, Boolean.TRUE.toString());
}
@Test
public void setProvisioning_whenPassedFalse_delegatesToInternalPropertiesWriteAndCleansUpExternalGroups() {
GroupDto groupDto = createGithubManagedGroup();
underTest.setProvisioning(false);
verify(internalProperties).write(GitHubSettings.PROVISIONING, Boolean.FALSE.toString());
assertThat(db.getDbClient().externalGroupDao().selectByGroupUuid(db.getSession(), groupDto.getUuid())).isEmpty();
}
private GroupDto createGithubManagedGroup() {
GroupDto groupDto = db.users().insertGroup();
db.users().markGroupAsGithubManaged(groupDto.getUuid());
return groupDto;
}
@Test
public void return_client_id() {
settings.setProperty("sonar.auth.github.clientId.secured", "id");
assertThat(underTest.clientId()).isEqualTo("id");
}
@Test
public void return_client_secret() {
settings.setProperty("sonar.auth.github.clientSecret.secured", "secret");
assertThat(underTest.clientSecret()).isEqualTo("secret");
}
@Test
public void return_app_id() {
settings.setProperty("sonar.auth.github.appId", "secret");
assertThat(underTest.appId()).isEqualTo("secret");
}
@Test
public void return_private_key() {
settings.setProperty("sonar.auth.github.privateKey.secured", "secret");
assertThat(underTest.privateKey()).isEqualTo("secret");
}
@Test
public void allow_users_to_sign_up() {
settings.setProperty("sonar.auth.github.allowUsersToSignUp", "true");
assertThat(underTest.allowUsersToSignUp()).isTrue();
settings.setProperty("sonar.auth.github.allowUsersToSignUp", "false");
assertThat(underTest.allowUsersToSignUp()).isFalse();
// default value
settings.setProperty("sonar.auth.github.allowUsersToSignUp", (String) null);
assertThat(underTest.allowUsersToSignUp()).isTrue();
}
@Test
public void sync_groups() {
settings.setProperty("sonar.auth.github.groupsSync", "true");
assertThat(underTest.syncGroups()).isTrue();
settings.setProperty("sonar.auth.github.groupsSync", "false");
assertThat(underTest.syncGroups()).isFalse();
// default value
settings.setProperty("sonar.auth.github.groupsSync", (String) null);
assertThat(underTest.syncGroups()).isFalse();
}
@Test
public void apiUrl_must_have_ending_slash() {
settings.setProperty("sonar.auth.github.apiUrl", "https://github.com");
assertThat(underTest.apiURL()).isEqualTo("https://github.com/");
settings.setProperty("sonar.auth.github.apiUrl", "https://github.com/");
assertThat(underTest.apiURL()).isEqualTo("https://github.com/");
}
@Test
public void webUrl_must_have_ending_slash() {
settings.setProperty("sonar.auth.github.webUrl", "https://github.com");
assertThat(underTest.webURL()).isEqualTo("https://github.com/");
settings.setProperty("sonar.auth.github.webUrl", "https://github.com/");
assertThat(underTest.webURL()).isEqualTo("https://github.com/");
}
@Test
public void return_organizations_single() {
String setting = "example";
settings.setProperty("sonar.auth.github.organizations", setting);
Set<String> actual = underTest.getOrganizations();
assertThat(actual).containsOnly(setting);
}
@Test
public void return_organizations_multiple() {
String setting = "example0,example1";
settings.setProperty("sonar.auth.github.organizations", setting);
Set<String> actual = underTest.getOrganizations();
assertThat(actual).containsOnly("example0", "example1");
}
@Test
public void return_organizations_empty_list() {
String[] setting = null;
settings.setProperty("sonar.auth.github.organizations", setting);
Set<String> actual = underTest.getOrganizations();
assertThat(actual).isEmpty();
}
@Test
public void definitions() {
assertThat(GitHubSettings.definitions().stream()
.map(PropertyDefinition::name))
.containsExactly(
"Enabled",
"Client ID",
"Client Secret",
"App ID",
"Private Key",
"Allow users to sign up",
"Synchronize teams as groups",
"The API url for a GitHub instance.",
"The WEB url for a GitHub instance.",
"Organizations");
}
private void enableGithubAuthentication() {
settings.setProperty("sonar.auth.github.clientId.secured", "id");
settings.setProperty("sonar.auth.github.clientSecret.secured", "secret");
settings.setProperty("sonar.auth.github.enabled", true);
}
private void enableGithubAuthenticationWithGithubApp() {
enableGithubAuthentication();
settings.setProperty("sonar.auth.github.appId", "id");
settings.setProperty("sonar.auth.github.privateKey.secured", "secret");
}
}
| 10,234 | 35.684588 | 122 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GithubTeamConverterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.Optional;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GithubTeamConverterTest {
@Test
public void toGroupName_withGsonTeam_returnsCorrectGroupName() {
GsonTeam team = new GsonTeam("team-1", new GsonTeam.GsonOrganization("Org1"));
assertThat(GithubTeamConverter.toGroupName(team)).isEqualTo("Org1/team-1");
}
@Test
public void toGroupName_withGroupAndName_returnsCorrectGroupName() {
assertThat(GithubTeamConverter.toGroupName("Org1", "team-1")).isEqualTo("Org1/team-1");
}
@Test
public void extractOrganizationName_whenNameIsCorrect_extractsOrganizationName() {
assertThat(GithubTeamConverter.extractOrganizationName("Org1/team1")).isEqualTo(Optional.of("Org1"));
assertThat(GithubTeamConverter.extractOrganizationName("Org1/team1/team2")).isEqualTo(Optional.of("Org1"));
}
@Test
public void extractOrganizationName_whenNameIsIncorrect_returnEmpty() {
assertThat(GithubTeamConverter.extractOrganizationName("Org1")).isEmpty();
assertThat(GithubTeamConverter.extractOrganizationName("Org1/")).isEmpty();
}
@Test
public void extractTeamName_whenNameIsCorrect_extractsTeamName() {
assertThat(GithubTeamConverter.extractTeamName("Org1/team1")).isEqualTo(Optional.of("team1"));
assertThat(GithubTeamConverter.extractTeamName("Org1/team1/team2")).isEqualTo(Optional.of("team1/team2"));
}
@Test
public void extractTeamName_whenNameIsIncorrect_returnEmpty() {
assertThat(GithubTeamConverter.extractTeamName("Org1")).isEmpty();
assertThat(GithubTeamConverter.extractTeamName("Org1/")).isEmpty();
}
}
| 2,522 | 37.815385 | 111 | java |
sonarqube | sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GsonEmailTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.github;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GsonEmailTest {
@Test
public void parse() {
List<GsonEmail> underTest = GsonEmail.parse(
"[\n" +
" {\n" +
" \"email\": \"octocat@github.com\",\n" +
" \"verified\": true,\n" +
" \"primary\": true\n" +
" },\n" +
" {\n" +
" \"email\": \"support@github.com\",\n" +
" \"verified\": false,\n" +
" \"primary\": false\n" +
" }\n" +
"]");
assertThat(underTest).hasSize(2);
assertThat(underTest.get(0).getEmail()).isEqualTo("octocat@github.com");
assertThat(underTest.get(0).isVerified()).isTrue();
assertThat(underTest.get(0).isPrimary()).isTrue();
assertThat(underTest.get(1).getEmail()).isEqualTo("support@github.com");
assertThat(underTest.get(1).isVerified()).isFalse();
assertThat(underTest.get(1).isPrimary()).isFalse();
}
@Test
public void should_have_no_arg_constructor() {
assertThat(new GsonEmail().getEmail()).isEmpty();
}
}
| 1,990 | 31.639344 | 76 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.