diff --git a/deploy-service/common/src/main/java/com/pinterest/deployservice/dao/BuildDAO.java b/deploy-service/common/src/main/java/com/pinterest/deployservice/dao/BuildDAO.java index 3169c9e089..a3f308d723 100644 --- a/deploy-service/common/src/main/java/com/pinterest/deployservice/dao/BuildDAO.java +++ b/deploy-service/common/src/main/java/com/pinterest/deployservice/dao/BuildDAO.java @@ -27,6 +27,14 @@ public interface BuildDAO { BuildBean getById(String buildId) throws Exception; + /** + * Returns whether a retained build names this complete SCM alias and repository. Case matching + * follows the selected SCM configuration rather than the database's default collation. + */ + boolean hasBuildForRepository( + String scm, String repo, boolean caseInsensitiveScm, boolean caseInsensitiveRepository) + throws Exception; + // commit in short version List getByCommit7(String scmCommit7, String buildName, int pageIndex, int pageSize) throws Exception; diff --git a/deploy-service/common/src/main/java/com/pinterest/deployservice/db/DBBuildDAOImpl.java b/deploy-service/common/src/main/java/com/pinterest/deployservice/db/DBBuildDAOImpl.java index abf0fb82e7..94dca34a94 100644 --- a/deploy-service/common/src/main/java/com/pinterest/deployservice/db/DBBuildDAOImpl.java +++ b/deploy-service/common/src/main/java/com/pinterest/deployservice/db/DBBuildDAOImpl.java @@ -37,6 +37,20 @@ public class DBBuildDAOImpl implements BuildDAO { private static final String INSERT_BUILD_TEMPLATE = "INSERT INTO builds SET %s"; private static final String DELETE_BUILD = "DELETE FROM builds WHERE build_id=?"; private static final String GET_BUILD_BY_ID = "SELECT * FROM builds WHERE build_id=?"; + private static final String[][] HAS_BUILD_FOR_REPOSITORY = { + { + "SELECT 1 FROM builds WHERE CAST(scm AS BINARY)=CAST(? AS BINARY) " + + "AND CAST(scm_repo AS BINARY)=CAST(? AS BINARY) LIMIT 1", + "SELECT 1 FROM builds WHERE CAST(scm AS BINARY)=CAST(? AS BINARY) " + + "AND CAST(LOWER(scm_repo) AS BINARY)=CAST(LOWER(?) AS BINARY) LIMIT 1" + }, + { + "SELECT 1 FROM builds WHERE CAST(LOWER(scm) AS BINARY)=CAST(LOWER(?) AS BINARY) " + + "AND CAST(scm_repo AS BINARY)=CAST(? AS BINARY) LIMIT 1", + "SELECT 1 FROM builds WHERE CAST(LOWER(scm) AS BINARY)=CAST(LOWER(?) AS BINARY) " + + "AND CAST(LOWER(scm_repo) AS BINARY)=CAST(LOWER(?) AS BINARY) LIMIT 1" + } + }; private static final String GET_BUILDS_BY_COMMIT_7 = "SELECT * FROM builds WHERE scm_commit_7=? ORDER BY publish_date DESC LIMIT ?,?"; private static final String GET_BUILDS_BY_COMMIT_7_AND_NAME = @@ -119,6 +133,21 @@ public BuildBean getById(String buildId) throws Exception { return new QueryRunner(dataSource).query(GET_BUILD_BY_ID, h, buildId); } + @Override + public boolean hasBuildForRepository( + String scm, String repo, boolean caseInsensitiveScm, boolean caseInsensitiveRepository) + throws Exception { + if (StringUtils.isEmpty(scm) || StringUtils.isEmpty(repo)) { + return false; + } + // Binary comparison preserves accents, trailing spaces, and complete identities even + // when the table's collation treats those values as equivalent. No prefix or LIKE match. + String query = + HAS_BUILD_FOR_REPOSITORY[caseInsensitiveScm ? 1 : 0][ + caseInsensitiveRepository ? 1 : 0]; + return new QueryRunner(dataSource).query(query, result -> result.next(), scm, repo); + } + @Override public List getByCommit7( String scmCommit7, String buildName, int pageIndex, int pageSize) throws Exception { diff --git a/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/GithubManager.java b/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/GithubManager.java index d44dd4dc8e..0d35748e0e 100644 --- a/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/GithubManager.java +++ b/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/GithubManager.java @@ -27,8 +27,11 @@ import java.util.LinkedList; import java.util.Map; import java.util.Queue; +import java.util.regex.Pattern; +import javax.ws.rs.BadRequestException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; +import okhttp3.HttpUrl; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormatter; @@ -44,6 +47,10 @@ public class GithubManager extends BaseManager { private static final Logger LOG = LoggerFactory.getLogger(GithubManager.class); private static final String UNKNOWN_LOGIN = "UNKNOWN"; private static final long TOKEN_TTL_MILLIS = 600000; // token expires after 10 minutes + private static final Pattern OWNER = + Pattern.compile("[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"); + private static final Pattern REPOSITORY = Pattern.compile("[A-Za-z0-9_.-]+"); + private static final Pattern UNSAFE_COMMIT_REFERENCE = Pattern.compile("[\\p{Cntrl} \\\\]"); private final String apiPrefix; private final String urlPrefix; private final String githubAppId; @@ -181,7 +188,10 @@ public String getUrlPrefix() { @Override public CommitBean getCommit(String repo, String sha) throws Exception { - String url = String.format("%s/repos/%s/commits/%s", apiPrefix, repo, sha); + HttpUrl.Builder urlBuilder = commitsUrl(repo); + validateCommitReference(sha); + // Encode the complete ref once: slashes and literal percent escapes stay inside this ref. + String url = urlBuilder.addPathSegment(sha).build().toString(); // TODO: Do not RETRY since it will timeout the thrift caller, need to revisit String jsonPayload; @@ -208,7 +218,7 @@ public CommitBean getCommit(String repo, String sha) throws Exception { @Override public Queue getCommits(String repo, String startSha, boolean keepHead, String path) throws Exception { - String url = String.format("%s/repos/%s/commits", apiPrefix, repo); + String url = commitsUrl(repo).build().toString(); // TODO: Do not RETRY since it will timeout the thrift caller, need to revisit Map params = new HashMap<>(); @@ -233,4 +243,40 @@ public Queue getCommits(String repo, String startSha, boolean keepHe } return CommitBeans; } + + public static void validateRepository(String repo) { + String[] repository = repo == null ? new String[0] : repo.split("/", -1); + if (repository.length != 2 + || !OWNER.matcher(repository[0]).matches() + || !REPOSITORY.matcher(repository[1]).matches() + || isDotSegment(repository[1])) { + throw new BadRequestException("GitHub repository must be an owner/repository name"); + } + } + + private HttpUrl.Builder commitsUrl(String repo) { + validateRepository(repo); + String[] repository = repo.split("/", -1); + return HttpUrl.parse(apiPrefix) + .newBuilder() + .addPathSegment("repos") + .addPathSegment(repository[0]) + .addPathSegment(repository[1]) + .addPathSegment("commits"); + } + + private static void validateCommitReference(String sha) { + if (sha == null || sha.isEmpty() || UNSAFE_COMMIT_REFERENCE.matcher(sha).find()) { + throw new BadRequestException("Invalid GitHub commit reference"); + } + for (String segment : sha.split("/", -1)) { + if (segment.isEmpty() || isDotSegment(segment)) { + throw new BadRequestException("Invalid GitHub commit reference"); + } + } + } + + private static boolean isDotSegment(String value) { + return ".".equals(value) || "..".equals(value); + } } diff --git a/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/PhabricatorManager.java b/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/PhabricatorManager.java index fbad5a4754..2ba78c39c7 100644 --- a/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/PhabricatorManager.java +++ b/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/PhabricatorManager.java @@ -38,10 +38,6 @@ public class PhabricatorManager extends BaseManager { private static final Logger LOG = LoggerFactory.getLogger(PhabricatorManager.class); - private static final String QUERY_COMMITS_HISTORY_PARAMETER = - "{\"commit\":\"%s\", \"limit\":%d, \"repository\":\"%s\"}"; - private static final String QUERY_COMMITS_HISTORY_PARAMETER_WITH_PATH = - "{\"commit\":\"%s\", \"limit\":%d, \"repository\":\"%s\", \"path\":\"%s\"}"; private static final int DEFAULT_SIZE = 30; private static final String DEFAULT_PATH = "*"; private static final String ARC_OUTPUT_NOTICE = "Waiting for JSON parameters on stdin..."; @@ -61,6 +57,17 @@ public PhabricatorManager( this.arcrcLocation = arcrcLocation; } + static String serializeHistoryParameters(String repo, String commit, int limit, String path) { + Map parameters = new HashMap<>(); + parameters.put("repository", repo); + parameters.put("commit", commit); + parameters.put("limit", limit); + if (path != null) { + parameters.put("path", path); + } + return new GsonBuilder().create().toJson(parameters); + } + private Map queryCLI(String input) throws Exception { ProcessBuilder builder; if (StringUtils.isEmpty(arcrcLocation)) { @@ -184,7 +191,7 @@ public String getUrlPrefix() { @Override public CommitBean getCommit(String repo, String sha) throws Exception { - String input = String.format(QUERY_COMMITS_HISTORY_PARAMETER, sha, 1, repo); + String input = serializeHistoryParameters(repo, sha, 1, null); Map json = queryCLI(input); try { @SuppressWarnings("unchecked") @@ -206,13 +213,7 @@ public CommitBean getCommit(String repo, String sha) throws Exception { @Override public Queue getCommits(String repo, String startSha, boolean keepHead, String path) throws Exception { - String input = - String.format( - QUERY_COMMITS_HISTORY_PARAMETER_WITH_PATH, - startSha, - DEFAULT_SIZE, - repo, - path); + String input = serializeHistoryParameters(repo, startSha, DEFAULT_SIZE, path); Map json = queryCLI(input); @SuppressWarnings("unchecked") Map commitsJson = (Map) json.get("response"); diff --git a/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/SourceControlManagerProxy.java b/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/SourceControlManagerProxy.java index 7a121c424d..80335e3710 100644 --- a/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/SourceControlManagerProxy.java +++ b/deploy-service/common/src/main/java/com/pinterest/deployservice/scm/SourceControlManagerProxy.java @@ -17,8 +17,12 @@ import com.pinterest.deployservice.bean.CommitBean; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.SortedMap; +import javax.ws.rs.BadRequestException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,6 +65,39 @@ public String getDefaultTypeName() { return defaultScmTypeName; } + /** Resolves the default and caller casing to the actual configured SCM key. */ + @SuppressWarnings("unchecked") + public String resolveScmTypeName(String scmType) { + String resolved = StringUtils.isEmpty(scmType) ? defaultScmTypeName : scmType; + if (managers.get(resolved) == null) { + throw new BadRequestException("Unsupported SCM type: " + resolved); + } + if (managers instanceof SortedMap) { + return ((SortedMap) managers) + .tailMap(resolved) + .firstKey(); + } + return resolved; + } + + /** Whether build metadata may use different casing for this configured SCM key. */ + @SuppressWarnings("unchecked") + public boolean isScmTypeCaseInsensitive(String scmType) { + if (!(managers instanceof SortedMap)) { + return false; + } + Comparator comparator = + ((SortedMap) managers).comparator(); + return comparator != null + && comparator.compare( + scmType.toLowerCase(Locale.ROOT), scmType.toUpperCase(Locale.ROOT)) + == 0; + } + + public boolean isGithub(String scmType) throws Exception { + return getSourceControlManager(scmType) instanceof GithubManager; + } + public String getCommitLinkTemplate(String scmType) throws Exception { return getSourceControlManager(scmType).getCommitLinkTemplate(); } diff --git a/deploy-service/common/src/test/java/com/pinterest/deployservice/db/DBDAOTest.java b/deploy-service/common/src/test/java/com/pinterest/deployservice/db/DBDAOTest.java index eb126dcc06..99e93759ed 100644 --- a/deploy-service/common/src/test/java/com/pinterest/deployservice/db/DBDAOTest.java +++ b/deploy-service/common/src/test/java/com/pinterest/deployservice/db/DBDAOTest.java @@ -87,6 +87,7 @@ import java.util.List; import java.util.Set; import org.apache.commons.dbcp.BasicDataSource; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.joda.time.DateTime; import org.joda.time.Interval; @@ -365,6 +366,80 @@ public void testBuildDAO() throws Exception { assertEquals(buildDAO.getById("b-1"), null); } + @Test + public void testBuildRepositoryLookupUsesConfiguredCaseRules() throws Exception { + insertRepositoryBuild("repository-build", "GitHub", "Owner/Repo"); + + assertTrue(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", false, false)); + assertFalse(buildDAO.hasBuildForRepository("github", "Owner/Repo", false, false)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "owner/repo", false, false)); + assertTrue(buildDAO.hasBuildForRepository("github", "Owner/Repo", true, false)); + assertFalse(buildDAO.hasBuildForRepository("github", "owner/repo", true, false)); + assertTrue(buildDAO.hasBuildForRepository("GitHub", "owner/repo", false, true)); + assertFalse(buildDAO.hasBuildForRepository("github", "Owner/Repo", false, true)); + assertTrue(buildDAO.hasBuildForRepository("github", "owner/repo", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub-Mirror", "Owner/Repo", true, true)); + + // An exact-case manager map can assign case-distinct aliases to different SCM hosts. + insertRepositoryBuild("other-host-build", "github", "Private/Other"); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Private/Other", false, true)); + assertTrue(buildDAO.hasBuildForRepository("github", "private/other", false, true)); + } + + @Test + public void testBuildRepositoryLookupDoesNotFoldOtherCharactersOrMatchPatterns() + throws Exception { + insertRepositoryBuild("literal-build", "GitHub", "Owner/Repo_Name"); + insertRepositoryBuild("percent-build", "Phabricator", "Repo%Literal"); + String longRepo = "owner/" + StringUtils.repeat('r', 58); + insertRepositoryBuild("long-repository-build", "GitHub", longRepo); + + assertTrue(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo_Name", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/RepoXName", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/%", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", true, true)); + assertTrue(buildDAO.hasBuildForRepository("Phabricator", "Repo%Literal", true, false)); + assertFalse(buildDAO.hasBuildForRepository("Phabricator", "repo%literal", true, false)); + assertFalse(buildDAO.hasBuildForRepository("Phabricator", "RepoXLiteral", true, false)); + assertFalse(buildDAO.hasBuildForRepository("Git%", "Owner/Repo_Name", true, true)); + assertFalse(buildDAO.hasBuildForRepository("Git_ub", "Owner/Repo_Name", true, true)); + assertFalse(buildDAO.hasBuildForRepository("Githúb", "Owner/Repo_Name", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/Répo_Name", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub ", "Owner/Repo_Name", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo_Name ", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "' OR 1=1 --", true, true)); + assertEquals(64, longRepo.length()); + assertTrue(buildDAO.hasBuildForRepository("GitHub", longRepo, true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", longRepo + "x", true, true)); + } + + @Test + public void testBuildRepositoryLookupRequiresARetainedMatchingBuild() throws Exception { + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", true, true)); + insertRepositoryBuild("unattributed-build", null, "Owner/Repo"); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", true, true)); + insertRepositoryBuild("first-retained-build", "GitHub", "Owner/Repo"); + insertRepositoryBuild("second-retained-build", "GitHub", "Owner/Repo"); + + assertFalse(buildDAO.hasBuildForRepository(null, "Owner/Repo", true, true)); + assertFalse(buildDAO.hasBuildForRepository("", "Owner/Repo", true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", null, true, true)); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "", true, true)); + assertTrue(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", true, true)); + buildDAO.delete("first-retained-build"); + assertTrue(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", true, true)); + buildDAO.delete("second-retained-build"); + assertFalse(buildDAO.hasBuildForRepository("GitHub", "Owner/Repo", true, true)); + } + + private void insertRepositoryBuild(String id, String scm, String repo) throws Exception { + BuildBean build = + genDefaultBuildInfoBean(id, "repository-builds", "abc123", "artifact", 1000L); + build.setScm(scm); + build.setScm_repo(repo); + buildDAO.insert(build); + } + @Test public void testDeployAcceptedDelayed() throws Exception { long sucDate = System.currentTimeMillis(); diff --git a/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/GithubManagerTest.java b/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/GithubManagerTest.java index b03f0b19d8..0e8b9a965a 100644 --- a/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/GithubManagerTest.java +++ b/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/GithubManagerTest.java @@ -16,60 +16,234 @@ package com.pinterest.deployservice.scm; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.pinterest.deployservice.bean.CommitBean; import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.ws.rs.BadRequestException; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; -/* To run this test only: - * update the github configuration in setUp() before running. uncomment the ignore - * $ mvn -Dtest=GithubManagerTest -DfailIfNoTests=false test - */ class GithubManagerTest { - GithubManager manager; + private MockWebServer server; + private GithubManager manager; @BeforeEach - void setUp() { - String typeName = "Github"; - String apiPrefix = "https://api.github.com"; - String urlPrefix = "https://github.com"; - String appId = "yourAppId"; - String appPrivateKeyKnox = ""; - String appOrgnization = "yourOrg"; - String token = ""; // github personal token - - this.manager = - new GithubManager( - token, - appId, - appPrivateKeyKnox, - appOrgnization, - typeName, - apiPrefix, - urlPrefix); - assertEquals(this.manager.getUrlPrefix(), urlPrefix); + void setUp() throws Exception { + server = new MockWebServer(); + server.start(); + manager = createManager("test-token", "/api/v3"); + } + + @AfterEach + void tearDown() throws Exception { + server.shutdown(); + } + + private GithubManager createManager(String token, String apiPath) { + return new GithubManager( + token, + "unused-app-id", + "", + "unused-organization", + "Github", + server.url(apiPath).toString(), + "https://github.com"); } @Test - @Disabled("Github manager is not ready for test") void testGetCommit() throws Exception { - CommitBean commit = - this.manager.getCommit( - "pinterest/teletraan", "0caa0c0dc877920811e0eb695f1ed0dfd498f586"); - System.out.println(commit); + server.enqueue( + new MockResponse() + .setBody( + "{\"sha\":\"abc123\",\"author\":{\"login\":\"author\"}," + + "\"commit\":{\"committer\":{\"date\":\"2024-06-01T12:00:00Z\"}," + + "\"message\":\"Title\\nBody\"}}")); + + CommitBean commit = manager.getCommit("Pinterest/Teletraan.v2", "abc123"); + + RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); + assertNotNull(request); + assertEquals("/api/v3/repos/Pinterest/Teletraan.v2/commits/abc123", request.getPath()); + assertEquals("Token test-token", request.getHeader("Authorization")); + assertEquals("abc123", commit.getSha()); + assertEquals("author", commit.getAuthor()); + assertEquals("Title", commit.getTitle()); + assertEquals("Body", commit.getMessage()); + assertEquals("https://github.com/Pinterest/Teletraan.v2/commit/abc123", commit.getInfo()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "pinterest/teletraan", + "Pinterest-Org/Repo_1.2-3", + "pinterest/.github", + "pinterest/..config" + }) + void testValidRepositoryAndEncodedQueryParameters(String repo) throws Exception { + server.enqueue(new MockResponse().setBody("[]")); + String startSha = "feature/test?sha=other#fragment"; + String path = "src/test file?path=other#fragment"; + + assertEquals(0, manager.getCommits(repo, startSha, true, path).size()); + + RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); + assertNotNull(request); + assertEquals("/api/v3/repos/" + repo + "/commits", request.getRequestUrl().encodedPath()); + assertEquals(startSha, request.getRequestUrl().queryParameter("sha")); + assertEquals(path, request.getRequestUrl().queryParameter("path")); + assertEquals(2, request.getRequestUrl().querySize()); + } + + @Test + void testEnterpriseApiPrefixWithTrailingSlash() throws Exception { + server.enqueue(new MockResponse().setBody("[]")); + + createManager("test-token", "/api/v3/").getCommits("pinterest/teletraan", "main", true, ""); + + RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); + assertNotNull(request); assertEquals( - "https://github.com/pinterest/teletraan/commit/0caa0c0dc877920811e0eb695f1ed0dfd498f586", - commit.getInfo()); + "/api/v3/repos/pinterest/teletraan/commits", request.getRequestUrl().encodedPath()); + } + + @ParameterizedTest + @CsvSource({ + "release/2026,release%2F2026", + "release+prod,release+prod", + "release@prod,release@prod", + "release#prod,release%23prod", + "release%prod,release%25prod", + "%2e%2e,%252e%252e", + "release/%2e%2e/other,release%2F%252e%252e%2Fother", + "%252e%252e%252fother,%25252e%25252e%25252fother", + "release?prod,release%3Fprod", + "release\u2003prod,release%E2%80%83prod", + "refs/heads/release/2026,refs%2Fheads%2Frelease%2F2026", + "rélèase,r%C3%A9l%C3%A8ase" + }) + void testRangeAcceptsAndEncodesEndReference(String endSha, String encodedEndSha) + throws Exception { + server.enqueue(new MockResponse().setBody(commitJson("abc123", "2024-06-01T12:00:00Z"))); + server.enqueue( + new MockResponse() + .setBody("[" + commitJson("def456", "2024-06-02T12:00:00Z") + "]")); List commits = - this.manager.getCommits( - "pinterest/teletraan", - "a220f1808b38f27314b4f5b89270216de7fb84bc", - "7fa731d99b9c98c29ce500dfef64ea32c3641786", - 100); - System.out.println(commits); - System.out.println("size = " + commits.size()); + manager.getCommits("pinterest/teletraan", "feature/new+work", endSha, 1); + + assertEquals(1, commits.size()); + assertEquals("def456", commits.get(0).getSha()); + RecordedRequest referenceRequest = server.takeRequest(1, TimeUnit.SECONDS); + assertNotNull(referenceRequest); + assertEquals( + "/api/v3/repos/pinterest/teletraan/commits/" + encodedEndSha, + referenceRequest.getPath()); + assertEquals(7, referenceRequest.getRequestUrl().pathSegments().size()); + assertEquals(endSha, referenceRequest.getRequestUrl().pathSegments().get(6)); + assertEquals("Token test-token", referenceRequest.getHeader("Authorization")); + RecordedRequest historyRequest = server.takeRequest(1, TimeUnit.SECONDS); + assertNotNull(historyRequest); + assertEquals( + "/api/v3/repos/pinterest/teletraan/commits", + historyRequest.getRequestUrl().encodedPath()); + assertEquals("feature/new+work", historyRequest.getRequestUrl().queryParameter("sha")); + assertEquals(2, server.getRequestCount()); + } + + private static String commitJson(String sha, String date) { + return String.format( + "{\"sha\":\"%s\",\"author\":{\"login\":\"author\"}," + + "\"commit\":{\"committer\":{\"date\":\"%s\"},\"message\":\"Title\"}}", + sha, date); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + "pinterest", + "pinterest/", + "/teletraan", + "/pinterest/teletraan", + "pinterest/teletraan/", + "pinterest/teletraan/extra", + "pinterest//teletraan", + "./teletraan", + "../teletraan", + "pinterest/.", + "pinterest/..", + "pinterest/../../../app/installations", + "victim/x/../../other", + "x/../../orgs/VICTIMORG/repos", + "pinterest/%2e%2e", + "pinterest%2fother/teletraan", + "pinterest/teletraan%2fextra", + "pinterest/teletraan?per_page=100#", + "pinterest/teletraan#fragment", + "pinterest\\other/teletraan", + "pinterest/teletraan\\extra", + "pinterest/tele traan", + " pinterest/teletraan", + "pinterest/teletraan\n", + "https://github.com/pinterest/teletraan" + }) + void testInvalidRepositoryRejectedBeforeCredentialsOrHttp(String repo) { + // With no token or private key, reaching credential retrieval would fail differently. + GithubManager unauthenticatedManager = createManager("", "/api/v3"); + + assertThrows( + BadRequestException.class, () -> unauthenticatedManager.getCommit(repo, "abc123")); + assertThrows( + BadRequestException.class, + () -> unauthenticatedManager.getCommits(repo, "main", true, "")); + assertEquals(0, server.getRequestCount()); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + ".", + "..", + "../other", + "release/../other", + "release/./other", + "/release/2026", + "release/2026/", + "release//2026", + "abc123\\extra", + "abc123 def", + "abc123\n" + }) + void testInvalidCommitReferenceRejectedBeforeCredentialsOrHttp(String sha) { + GithubManager unauthenticatedManager = createManager("", "/api/v3"); + + assertThrows( + BadRequestException.class, + () -> unauthenticatedManager.getCommit("pinterest/teletraan", sha)); + assertEquals(0, server.getRequestCount()); + } + + @ParameterizedTest + @ValueSource(strings = {"release/../../other", "release/../other", "release/./other"}) + void testTraversalEndReferenceRejectedBeforeCredentialsOrHttp(String endSha) { + GithubManager unauthenticatedManager = createManager("", "/api/v3"); + + assertThrows( + BadRequestException.class, + () -> unauthenticatedManager.getCommits("pinterest/teletraan", "main", endSha, 1)); + assertEquals(0, server.getRequestCount()); } } diff --git a/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/PhabricatorManagerTest.java b/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/PhabricatorManagerTest.java new file mode 100644 index 0000000000..f38069b710 --- /dev/null +++ b/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/PhabricatorManagerTest.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2026 Pinterest, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.pinterest.deployservice.scm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class PhabricatorManagerTest { + @Test + void singleCommitRequestPreservesParametersWithoutAPathFilter() { + JsonObject parameters = + JsonParser.parseString( + PhabricatorManager.serializeHistoryParameters( + "ALLOWED", "abc123", 1, null)) + .getAsJsonObject(); + + assertEquals("ALLOWED", parameters.get("repository").getAsString()); + assertEquals("abc123", parameters.get("commit").getAsString()); + assertEquals(1, parameters.get("limit").getAsInt()); + assertFalse(parameters.has("path")); + assertEquals(3, parameters.size()); + } + + @Test + void historyRequestPreservesAnEmptyPathFilter() { + JsonObject parameters = + JsonParser.parseString( + PhabricatorManager.serializeHistoryParameters( + "ALLOWED", "main", 30, "")) + .getAsJsonObject(); + + assertEquals("ALLOWED", parameters.get("repository").getAsString()); + assertEquals("main", parameters.get("commit").getAsString()); + assertEquals(30, parameters.get("limit").getAsInt()); + assertEquals("", parameters.get("path").getAsString()); + assertEquals(4, parameters.size()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "\",\"repository\":\"secret", + "\",\"limit\":1000,\"repository\":\"secret", + "quoted\"value\\with\ncontrol\tcharacters", + "\"},\"unexpected\":{\"repository\":\"secret\"}" + }) + void commitAndPathCannotOverrideTheAllowedRepository(String hostileValue) { + JsonObject parameters = + JsonParser.parseString( + PhabricatorManager.serializeHistoryParameters( + "ALLOWED", hostileValue, 30, hostileValue)) + .getAsJsonObject(); + + assertEquals("ALLOWED", parameters.get("repository").getAsString()); + assertEquals(hostileValue, parameters.get("commit").getAsString()); + assertEquals(hostileValue, parameters.get("path").getAsString()); + assertEquals(30, parameters.get("limit").getAsInt()); + assertEquals(4, parameters.size()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "ALLOWED\",\"repository\":\"secret", + "ALLOWED\",\"commit\":\"other", + "ALLOWED\",\"limit\":1000,\"unused\":\"value", + "quoted\"repository\\with\ncontrol\tcharacters" + }) + void repositoryIsSerializedAsTheExactCheckedValue(String repository) { + JsonObject parameters = + JsonParser.parseString( + PhabricatorManager.serializeHistoryParameters( + repository, "abc123", 1, null)) + .getAsJsonObject(); + + assertEquals(repository, parameters.get("repository").getAsString()); + assertEquals("abc123", parameters.get("commit").getAsString()); + assertEquals(1, parameters.get("limit").getAsInt()); + assertFalse(parameters.has("path")); + assertEquals(3, parameters.size()); + } +} diff --git a/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/SourceControlManagerProxyTest.java b/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/SourceControlManagerProxyTest.java new file mode 100644 index 0000000000..8fd309dfed --- /dev/null +++ b/deploy-service/common/src/test/java/com/pinterest/deployservice/scm/SourceControlManagerProxyTest.java @@ -0,0 +1,85 @@ +/** + * Copyright (c) 2026 Pinterest, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.pinterest.deployservice.scm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import javax.ws.rs.BadRequestException; +import org.junit.jupiter.api.Test; + +class SourceControlManagerProxyTest { + @Test + void resolvesConfiguredCasingAndDefaultWithoutConflatingAliases() throws Exception { + SourceControlManager github = mock(GithubManager.class); + Map managers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + managers.put("GitHub", github); + managers.put("Enterprise", github); + SourceControlManagerProxy proxy = new SourceControlManagerProxy(managers, "gItHuB"); + + assertEquals("GitHub", proxy.resolveScmTypeName("GITHUB")); + assertEquals("GitHub", proxy.resolveScmTypeName("")); + assertEquals("GitHub", proxy.resolveScmTypeName(null)); + assertEquals("Enterprise", proxy.resolveScmTypeName("ENTERPRISE")); + assertTrue(proxy.isScmTypeCaseInsensitive("GitHub")); + assertTrue(proxy.isScmTypeCaseInsensitive("Enterprise")); + assertTrue(proxy.isGithub("Enterprise")); + } + + @Test + void preservesCaseDistinctAliasesInExactMap() throws Exception { + Map managers = new HashMap<>(); + managers.put("GitHub", mock(GithubManager.class)); + managers.put("github", mock(PhabricatorManager.class)); + SourceControlManagerProxy proxy = new SourceControlManagerProxy(managers, "github"); + + assertEquals("GitHub", proxy.resolveScmTypeName("GitHub")); + assertEquals("github", proxy.resolveScmTypeName("github")); + assertEquals("github", proxy.resolveScmTypeName("")); + assertFalse(proxy.isScmTypeCaseInsensitive("GitHub")); + assertFalse(proxy.isScmTypeCaseInsensitive("github")); + assertTrue(proxy.isGithub("GitHub")); + assertFalse(proxy.isGithub("github")); + assertThrows(BadRequestException.class, () -> proxy.resolveScmTypeName("GITHUB")); + } + + @Test + void doesNotCaseFoldNaturallySortedMap() { + Map managers = new TreeMap<>(); + managers.put("GitHub", mock(GithubManager.class)); + SourceControlManagerProxy proxy = new SourceControlManagerProxy(managers, "GitHub"); + + assertEquals("GitHub", proxy.resolveScmTypeName("")); + assertFalse(proxy.isScmTypeCaseInsensitive("GitHub")); + assertThrows(BadRequestException.class, () -> proxy.resolveScmTypeName("github")); + } + + @Test + void rejectsUnsupportedAliasAndMissingDefault() { + Map managers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + managers.put("GitHub", mock(GithubManager.class)); + SourceControlManagerProxy proxy = new SourceControlManagerProxy(managers, "missing"); + + assertThrows(BadRequestException.class, () -> proxy.resolveScmTypeName("unknown")); + assertThrows(BadRequestException.class, () -> proxy.resolveScmTypeName("")); + } +} diff --git a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Commits.java b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Commits.java index 7769036ff1..11409c0f46 100644 --- a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Commits.java +++ b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Commits.java @@ -18,6 +18,8 @@ import com.google.common.base.Optional; import com.pinterest.deployservice.bean.CommitBean; import com.pinterest.deployservice.bean.TeletraanPrincipalRole; +import com.pinterest.deployservice.dao.BuildDAO; +import com.pinterest.deployservice.scm.GithubManager; import com.pinterest.deployservice.scm.SourceControlManagerProxy; import com.pinterest.teletraan.TeletraanServiceContext; import io.micrometer.core.annotation.Counted; @@ -28,6 +30,8 @@ import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; @RolesAllowed(TeletraanPrincipalRole.Names.READ) @Path("/v1/commits") @@ -42,26 +46,31 @@ public class Commits { private static final String DEFAULT_PATH = ""; private static final int DEFAULT_SIZE = 100; private final SourceControlManagerProxy sourceControlManagerProxy; + private final BuildDAO buildDAO; public Commits(@Context TeletraanServiceContext context) throws Exception { sourceControlManagerProxy = context.getSourceControlManagerProxy(); + buildDAO = context.getBuildDAO(); } @GET @Timed @Counted - @Path("{scm : [a-zA-Z0-9\\-_]+}/{repo : [a-zA-Z0-9\\-_/%]+}/{sha : [a-zA-Z0-9\\-_]+}") + @Path("{scm : [a-zA-Z0-9\\-_]+}/{repo : [a-zA-Z0-9\\-._/%]+}/{sha : [a-zA-Z0-9\\-_]+}") @ApiOperation( value = "Get commit infos", notes = "Returns a commit object given a repo and commit sha", response = CommitBean.class) public CommitBean getCommit( + @Context UriInfo uriInfo, @ApiParam(value = "Commit's scm type, either github or phabricator") @PathParam("scm") String scm, @ApiParam(value = "Commit's repo", required = true) @PathParam("repo") String repo, @ApiParam(value = "Commit SHA", required = true) @PathParam("sha") String sha) throws Exception { + requireSingleRepositoryParameters(uriInfo.getPathParameters()); repo = repo.replace("%2F", "/"); + scm = requireRepositoryBuild(scm, repo); return sourceControlManagerProxy.getCommit(scm, repo, sha); } @@ -79,6 +88,7 @@ public CommitBean getCommit( @Timed @Counted public List getCommits( + @Context UriInfo uriInfo, @QueryParam("scm") Optional scm, @QueryParam("repo") String repo, @QueryParam("startSha") String startSha, @@ -86,7 +96,38 @@ public List getCommits( @QueryParam("size") Optional size, @QueryParam("path") Optional path) throws Exception { + requireSingleRepositoryParameters(uriInfo.getQueryParameters()); + String resolvedScm = requireRepositoryBuild(scm.or(""), repo); return sourceControlManagerProxy.getCommits( - scm.or(""), repo, startSha, endSha, size.or(DEFAULT_SIZE), path.or(DEFAULT_PATH)); + resolvedScm, repo, startSha, endSha, size.or(DEFAULT_SIZE), path.or(DEFAULT_PATH)); + } + + private String requireRepositoryBuild(String scm, String repo) throws Exception { + String resolvedScm = sourceControlManagerProxy.resolveScmTypeName(scm); + if (repo == null || repo.isEmpty()) { + throw new BadRequestException("A repository is required"); + } + boolean github = sourceControlManagerProxy.isGithub(resolvedScm); + if (github) { + GithubManager.validateRepository(repo); + } + // Published builds define which repositories may use the service's SCM credential. + if (!buildDAO.hasBuildForRepository( + resolvedScm, + repo, + sourceControlManagerProxy.isScmTypeCaseInsensitive(resolvedScm), + github)) { + throw new ForbiddenException("Repository has no published builds in this SCM"); + } + return resolvedScm; + } + + private static void requireSingleRepositoryParameters( + MultivaluedMap parameters) { + for (String name : new String[] {"scm", "repo"}) { + if (parameters.containsKey(name) && parameters.get(name).size() != 1) { + throw new BadRequestException("Expected a single " + name + " parameter"); + } + } } } diff --git a/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/CommitsAuthorizationTest.java b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/CommitsAuthorizationTest.java new file mode 100644 index 0000000000..74a33ee27e --- /dev/null +++ b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/CommitsAuthorizationTest.java @@ -0,0 +1,253 @@ +/** + * Copyright (c) 2026 Pinterest, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.pinterest.teletraan.resource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import com.pinterest.deployservice.bean.CommitBean; +import com.pinterest.deployservice.bean.TeletraanPrincipalRole; +import com.pinterest.deployservice.bean.TokenRolesBean; +import com.pinterest.deployservice.dao.BuildDAO; +import com.pinterest.deployservice.dao.TokenRolesDAO; +import com.pinterest.deployservice.scm.GithubManager; +import com.pinterest.deployservice.scm.SourceControlManager; +import com.pinterest.deployservice.scm.SourceControlManagerProxy; +import com.pinterest.teletraan.TeletraanServiceContext; +import com.pinterest.teletraan.config.RoleAuthorizationFactory; +import com.pinterest.teletraan.security.TeletraanScriptTokenProvider; +import com.pinterest.teletraan.universal.security.AuthZResourceExtractor; +import com.pinterest.teletraan.universal.security.ResourceAuthZInfoFeature; +import com.pinterest.teletraan.universal.security.ScriptTokenAuthenticator; +import com.pinterest.teletraan.universal.security.bean.AuthZResource; +import com.pinterest.teletraan.universal.security.bean.ScriptTokenPrincipal; +import com.pinterest.teletraan.universal.security.bean.ValueBasedRole; +import io.dropwizard.auth.AuthDynamicFeature; +import io.dropwizard.auth.Authorizer; +import io.dropwizard.auth.oauth.OAuthCredentialAuthFilter; +import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; +import io.dropwizard.testing.junit5.ResourceExtension; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; +import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@ExtendWith(DropwizardExtensionsSupport.class) +class CommitsAuthorizationTest { + private static final GithubManager MANAGER = mock(GithubManager.class); + private static final BuildDAO BUILD_DAO = mock(BuildDAO.class); + private static final TokenRolesDAO TOKEN_DAO = mock(TokenRolesDAO.class); + private static final ResourceExtension EXT = createExtension(); + + @SuppressWarnings("unchecked") + private static ResourceExtension createExtension() { + TeletraanServiceContext context = new TeletraanServiceContext(); + context.setBuildDAO(BUILD_DAO); + context.setTokenRolesDAO(TOKEN_DAO); + Map managers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + managers.put("Github", MANAGER); + managers.put("Github-Mirror", MANAGER); + context.setSourceControlManagerProxy(new SourceControlManagerProxy(managers, "Github")); + context.setAuthZResourceExtractorFactory(mock(AuthZResourceExtractor.Factory.class)); + Authorizer> authorizer = + (Authorizer>) + (Authorizer) + new RoleAuthorizationFactory() + .create(context, ScriptTokenPrincipal.class); + try { + return ResourceExtension.builder() + .addProvider( + new AuthDynamicFeature( + new OAuthCredentialAuthFilter.Builder< + ScriptTokenPrincipal>() + .setAuthenticator( + new ScriptTokenAuthenticator<>( + new TeletraanScriptTokenProvider( + context, false))) + .setAuthorizer(authorizer) + .setPrefix("token") + .buildAuthFilter())) + .addProvider(RolesAllowedDynamicFeature.class) + .addResource(ResourceAuthZInfoFeature.class) + .addResource(new Commits(context)) + .build(); + } catch (Exception e) { + throw new ExceptionInInitializerError(e); + } + } + + @BeforeEach + void resetFixtures() throws Exception { + reset(MANAGER, BUILD_DAO, TOKEN_DAO); + when(MANAGER.getCommit(anyString(), anyString())).thenReturn(new CommitBean()); + when(MANAGER.getCommits(anyString(), any(), any(), anyInt(), anyString())) + .thenReturn(Collections.emptyList()); + when(BUILD_DAO.hasBuildForRepository(anyString(), anyString(), eq(true), eq(true))) + .thenAnswer( + invocation -> + "Github".equals(invocation.getArgument(0)) + && "acme/repo.name" + .equalsIgnoreCase(invocation.getArgument(1))); + Map tokens = new HashMap<>(); + tokens.put("read", token(TeletraanPrincipalRole.READ, AuthZResource.Type.SYSTEM, "*")); + tokens.put("reader", token(TeletraanPrincipalRole.READER, AuthZResource.Type.SYSTEM, "*")); + tokens.put( + "publisher", + token(TeletraanPrincipalRole.PUBLISHER, AuthZResource.Type.SYSTEM, "*")); + tokens.put( + "operator", token(TeletraanPrincipalRole.OPERATOR, AuthZResource.Type.SYSTEM, "*")); + tokens.put( + "env-admin", + token(TeletraanPrincipalRole.ADMIN, AuthZResource.Type.ENV, "owned-env")); + tokens.put( + "system-admin", + token(TeletraanPrincipalRole.ADMIN, AuthZResource.Type.SYSTEM, "*")); + when(TOKEN_DAO.getByToken(anyString())) + .thenAnswer(invocation -> tokens.get(invocation.getArgument(0))); + } + + private static TokenRolesBean token( + TeletraanPrincipalRole role, AuthZResource.Type type, String resourceId) { + TokenRolesBean bean = new TokenRolesBean(); + bean.setScript_name("test"); + bean.setRole(role); + bean.setResource_type(type); + bean.setResource_id(resourceId); + return bean; + } + + private WebTarget commits(String repo) { + return EXT.target("/v1/commits") + .queryParam("repo", repo.replace("%", "%25")) + .queryParam("startSha", "deadbeef"); + } + + private WebTarget commit(String scm, String repo, String ref) { + return EXT.target("/v1/commits/" + scm + "/" + repo + "/" + ref); + } + + private void assertStatus(WebTarget target, String token, int status) { + try (Response response = target.request().header("Authorization", "token " + token).get()) { + assertEquals(status, response.getStatus()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"read", "reader", "publisher", "operator", "env-admin", "system-admin"}) + void existingReadRolesCanReadRepositoriesWithBuilds(String token) throws Exception { + assertStatus(commits("acme/repo.name"), token, 200); + assertStatus(commit("Github", "acme/repo.name", "deadbeef"), token, 200); + verify(MANAGER).getCommits("acme/repo.name", "deadbeef", null, 100, ""); + verify(MANAGER).getCommit("acme/repo.name", "deadbeef"); + } + + @ParameterizedTest + @ValueSource(strings = {"read", "system-admin"}) + void repositoryWithoutBuildsIsDeniedEvenToSystemAdministrators(String token) { + assertStatus(commits("victim-private-org/secret-repo"), token, 403); + assertStatus(commit("Github", "victim-private-org/secret-repo", "deadbeef"), token, 403); + verifyNoInteractions(MANAGER); + } + + @ParameterizedTest + @ValueSource(strings = {"Github", "github", "gItHuB"}) + void scmAndGithubRepositoryCasingResolveToTheSameBuiltRepository(String scm) { + assertStatus(commits("ACME/REPO.NAME").queryParam("scm", scm), "read", 200); + assertStatus(commit(scm, "ACME/REPO.NAME", "deadbeef"), "read", 200); + } + + @Test + void emptyScmUsesTheConfiguredDefault() { + assertStatus(commits("acme/repo.name").queryParam("scm", ""), "read", 200); + } + + @Test + void configuredAliasNeedsItsOwnStoredBuildEvenWithTheSameManager() throws Exception { + assertStatus(commits("acme/repo.name").queryParam("scm", "gItHuB-mIrRoR"), "read", 403); + assertStatus(commit("GITHUB-MIRROR", "acme/repo.name", "deadbeef"), "read", 403); + verifyNoInteractions(MANAGER); + when(BUILD_DAO.hasBuildForRepository("Github-Mirror", "acme/repo.name", true, true)) + .thenReturn(true); + assertStatus(commits("acme/repo.name").queryParam("scm", "gItHuB-mIrRoR"), "read", 200); + assertStatus(commit("GITHUB-MIRROR", "acme/repo.name", "deadbeef"), "read", 200); + } + + @Test + void builtRepositoryCanReadBranchRefsAndCommitsWithoutTheirOwnBuilds() throws Exception { + assertStatus( + EXT.target("/v1/commits") + .queryParam("repo", "acme/repo.name") + .queryParam("startSha", "feature/hotfix.ref") + .queryParam("endSha", "refs/tags/v1.2"), + "read", + 200); + assertStatus(commit("Github", "acme/repo.name", "main"), "read", 200); + verify(MANAGER) + .getCommits("acme/repo.name", "feature/hotfix.ref", "refs/tags/v1.2", 100, ""); + verify(MANAGER).getCommit("acme/repo.name", "main"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "victim/x/../../other", + "x/../../orgs/VICTIMORG/repos", + "acme/repo.name?per_page=100", + "acme/repo.name#fragment", + "acme%2Frepo.name", + "acme/..", + "acme/repo.name/extra", + "" + }) + void malformedRepositoryIsRejectedBeforeScmCall(String repo) { + assertStatus(commits(repo), "read", 400); + verifyNoInteractions(MANAGER); + } + + @Test + void missingAmbiguousOrUnknownRepositoryIdentityIsRejected() { + assertStatus(EXT.target("/v1/commits"), "read", 400); + assertStatus(commits("acme/repo.name").queryParam("repo", "acme/other"), "read", 400); + assertStatus( + commits("acme/repo.name").queryParam("scm", "Github", "Github-Mirror"), + "read", + 400); + assertStatus(commits("acme/repo.name").queryParam("scm", "unknown"), "read", 400); + verifyNoInteractions(MANAGER); + } + + @Test + void anonymousAndUnknownTokensCannotReadCommits() { + WebTarget[] targets = { + commits("acme/repo.name"), commit("Github", "acme/repo.name", "deadbeef") + }; + for (WebTarget target : targets) { + try (Response response = target.request().get()) { + assertEquals(401, response.getStatus()); + } + assertStatus(target, "unknown", 401); + } + verifyNoInteractions(BUILD_DAO, MANAGER); + } +} diff --git a/docs/api/Commits.md b/docs/api/Commits.md index b9a8c623e6..c7237428ae 100644 --- a/docs/api/Commits.md +++ b/docs/api/Commits.md @@ -1,6 +1,25 @@ ### Commits Commit info APIs +Both endpoints require the existing `READ` permission. Before requesting SCM data, +Teletraan checks that at least one retained build records the requested repository +in the selected configured SCM. Repositories without a matching build return +HTTP 403 before any SCM request, including for administrators. Missing, ambiguous +or malformed GitHub repository parameters return HTTP 400. + +The check is independent of the requested branch or commit: comparisons, pagination +and hotfix cherry-picking can read new commits once the repository has a build. +SCM defaults and configured case matching are honored; distinct configured SCM +aliases remain separate. GitHub repository names match case-insensitively. + +Published build metadata defines this allowlist. Any authenticated reader can read +commits for a repository with a build; publishers can add repositories by publishing +build metadata. This workaround does not enforce per-user repository ownership. +Deleting the last build for a repository removes its commit access. + +Deploy the service update directly. No database migration, new repository grants, +token provisioning, or changes to the GitHub App credential are required. + #### GET /v1/commits @@ -11,7 +30,7 @@ Commit info APIs |---|---|---| |**Query**|**endSha**
*optional*|string| |**Query**|**path**
*optional*|string| -|**Query**|**repo**
*optional*|string| +|**Query**|**repo**
*required*|string| |**Query**|**scm**
*optional*|string| |**Query**|**size**
*optional*|integer (int32)| |**Query**|**startSha**
*optional*|string|