diff --git a/api/src/main/java/io/terrakube/api/plugin/scheduler/module/ModuleRefreshTransactions.java b/api/src/main/java/io/terrakube/api/plugin/scheduler/module/ModuleRefreshTransactions.java index b66d0e0894..6e940440d2 100644 --- a/api/src/main/java/io/terrakube/api/plugin/scheduler/module/ModuleRefreshTransactions.java +++ b/api/src/main/java/io/terrakube/api/plugin/scheduler/module/ModuleRefreshTransactions.java @@ -36,10 +36,9 @@ public class ModuleRefreshTransactions { static final int MAX_ERROR_LENGTH = 1024; - // The connections whose shared repository webhook the API can register (RepoWebhookService). Bitbucket has - // none, so its modules rely on polling. + // The connections whose shared repository webhook the API can register (RepoWebhookService). public static final Set WEBHOOK_VCS_TYPES = - Set.of(VcsType.GITHUB, VcsType.GITLAB, VcsType.AZURE_DEVOPS, VcsType.AZURE_SP_MI); + Set.of(VcsType.GITHUB, VcsType.GITLAB, VcsType.AZURE_DEVOPS, VcsType.AZURE_SP_MI, VcsType.BITBUCKET); // scheme://user:secret@host: JGit messages quote the remote URL, which can carry credentials. private static final Pattern URL_USER_INFO = Pattern.compile("([a-zA-Z][a-zA-Z0-9+.-]*://)[^/@\\s]+@"); diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/RepoWebhookService.java b/api/src/main/java/io/terrakube/api/plugin/vcs/RepoWebhookService.java index 2575fdc692..9267dbb446 100644 --- a/api/src/main/java/io/terrakube/api/plugin/vcs/RepoWebhookService.java +++ b/api/src/main/java/io/terrakube/api/plugin/vcs/RepoWebhookService.java @@ -30,6 +30,7 @@ import io.terrakube.api.plugin.scheduler.module.ModuleRefreshTransactions; import io.terrakube.api.plugin.security.audit.AuditActorContext; import io.terrakube.api.plugin.vcs.provider.azdevops.AzDevOpsWebhookService; +import io.terrakube.api.plugin.vcs.provider.bitbucket.BitBucketWebhookService; import io.terrakube.api.plugin.vcs.provider.github.GitHubWebhookService; import io.terrakube.api.plugin.vcs.provider.gitlab.GitLabWebhookService; import io.terrakube.api.repository.JobRepository; @@ -63,6 +64,7 @@ public class RepoWebhookService { GitHubWebhookService gitHubWebhookService; GitLabWebhookService gitLabWebhookService; AzDevOpsWebhookService azDevOpsWebhookService; + BitBucketWebhookService bitBucketWebhookService; JobRepository jobRepository; ScheduleJobService scheduleJobService; PrCommentService prCommentService; @@ -95,6 +97,14 @@ private boolean isAzureDevOps(Workspace workspace) { || workspace.getVcs().getVcsType() == VcsType.AZURE_DEVOPS); } + private boolean isBitBucket(RepoWebhook repoWebhook) { + return repoWebhook.getVcs() != null && repoWebhook.getVcs().getVcsType() == VcsType.BITBUCKET; + } + + private boolean isBitBucket(Workspace workspace) { + return workspace.getVcs() != null && workspace.getVcs().getVcsType() == VcsType.BITBUCKET; + } + // Callers reach this exclusively through RepoWebhookSyncJob, which is // @DisallowConcurrentExecution and keyed by a hash of the normalized // repository URL — Quartz (cluster mode, JDBC job store) guarantees at @@ -161,6 +171,9 @@ public void createOrUpdateSharedWebhook(RepoWebhook repoWebhook) { } else if (isGitLab(repoWebhook)) { remoteHookId = gitLabWebhookService.createOrUpdateRepoWebhook(repoWebhook, eventTypes, hasPrWorkflow, tagEvents); + } else if (isBitBucket(repoWebhook)) { + remoteHookId = bitBucketWebhookService.createOrUpdateRepoWebhook(repoWebhook, eventTypes, hasPrWorkflow, + tagEvents); } else { remoteHookId = gitHubWebhookService.createOrUpdateRepoWebhook(repoWebhook, eventTypes, hasPrWorkflow, tagEvents); @@ -179,6 +192,8 @@ public void cleanupIfOrphan(RepoWebhook repoWebhook) { azDevOpsWebhookService.deleteRepoWebhook(repoWebhook); } else if (isGitLab(repoWebhook)) { gitLabWebhookService.deleteRepoWebhook(repoWebhook); + } else if (isBitBucket(repoWebhook)) { + bitBucketWebhookService.deleteRepoWebhook(repoWebhook); } else { gitHubWebhookService.deleteRepoWebhook(repoWebhook); } @@ -213,6 +228,7 @@ public UUID acceptV2Webhook(String repoWebhookId, String jsonPayload, Map prFiles = gitlab - ? gitLabWebhookService.fetchPrFileChanges(repoWebhook.getVcs(), normalizedUrl, - webhookResult.getPrFilesUrl()) - : gitHubWebhookService.fetchPrFileChanges(repoWebhook.getVcs(), normalizedUrl, - webhookResult.getPrFilesUrl()); + List prFiles; + if (gitlab) { + prFiles = gitLabWebhookService.fetchPrFileChanges(repoWebhook.getVcs(), normalizedUrl, + webhookResult.getPrFilesUrl()); + } else if (bitbucket) { + prFiles = bitBucketWebhookService.fetchDiffFileChanges(repoWebhook.getVcs(), + webhookResult.getPrFilesUrl()); + } else { + prFiles = gitHubWebhookService.fetchPrFileChanges(repoWebhook.getVcs(), normalizedUrl, + webhookResult.getPrFilesUrl()); + } webhookResult.setFileChanges(prFiles); } @@ -399,11 +429,17 @@ private void processWorkspaceWebhook(Workspace workspace, WebhookResult webhookR // the repo-level credential lacking access while this workspace's own credential works, // so it's still worth this workspace trying with its own Vcs. if (workspace.getVcs() != null) { - List prFiles = isGitLab(workspace) - ? gitLabWebhookService.fetchPrFileChanges( - workspace.getVcs(), workspace.getSource(), webhookResult.getPrFilesUrl()) - : gitHubWebhookService.fetchPrFileChanges( - workspace.getVcs(), workspace.getSource(), webhookResult.getPrFilesUrl()); + List prFiles; + if (isGitLab(workspace)) { + prFiles = gitLabWebhookService.fetchPrFileChanges( + workspace.getVcs(), workspace.getSource(), webhookResult.getPrFilesUrl()); + } else if (isBitBucket(workspace)) { + prFiles = bitBucketWebhookService.fetchDiffFileChanges( + workspace.getVcs(), webhookResult.getPrFilesUrl()); + } else { + prFiles = gitHubWebhookService.fetchPrFileChanges( + workspace.getVcs(), workspace.getSource(), webhookResult.getPrFilesUrl()); + } webhookResult.setFileChanges(prFiles); } else { log.warn("Workspace {} has no VCS, cannot fetch PR file changes", workspace.getName()); @@ -558,7 +594,7 @@ private void saveAndScheduleJob(Workspace workspace, WebhookResult webhookResult azDevOpsWebhookService.sendCommitStatus(savedJob, JobStatus.pending, null); } else if (isGitLab(workspace)) { gitLabWebhookService.sendCommitStatus(savedJob, JobStatus.pending, null); - } else { + } else if (!isBitBucket(workspace)) { gitHubWebhookService.sendCommitStatus(savedJob, JobStatus.pending, null); } } @@ -576,11 +612,11 @@ private boolean verifyGitlabToken(Map headers, String secret) { secret.getBytes(StandardCharsets.UTF_8)); } - private boolean verifyHmacSignature(Map headers, String secret, String payload) { + private boolean verifyHmacSignature(Map headers, String headerName, String secret, String payload) { try { - String signatureHeader = headers.get("x-hub-signature-256"); + String signatureHeader = headers.get(headerName); if (signatureHeader == null) { - log.error("x-hub-signature-256 header is missing!"); + log.error("{} header is missing!", headerName); return false; } Mac mac = Mac.getInstance("HmacSHA256"); diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookService.java b/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookService.java index 173c2cb684..245ad05ea9 100644 --- a/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookService.java +++ b/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookService.java @@ -441,7 +441,8 @@ private static boolean isSharedWebhookProvider(io.terrakube.api.rs.vcs.VcsType v return vcsType == io.terrakube.api.rs.vcs.VcsType.GITHUB || vcsType == io.terrakube.api.rs.vcs.VcsType.GITLAB || vcsType == io.terrakube.api.rs.vcs.VcsType.AZURE_SP_MI - || vcsType == io.terrakube.api.rs.vcs.VcsType.AZURE_DEVOPS; + || vcsType == io.terrakube.api.rs.vcs.VcsType.AZURE_DEVOPS + || vcsType == io.terrakube.api.rs.vcs.VcsType.BITBUCKET; } private void sendCommitStatus(Job job) { diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookServiceBase.java b/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookServiceBase.java index 8cb0c335da..5bcefb4c03 100644 --- a/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookServiceBase.java +++ b/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookServiceBase.java @@ -144,6 +144,19 @@ protected ResponseEntity makeApiRequest(HttpHeaders headers, String body } } + protected ResponseEntity makeApiRequest(HttpHeaders headers, String body, URI apiUri, HttpMethod method) { + if (body != null && !body.isEmpty() && headers.getContentType() == null) { + headers.setContentType(MediaType.APPLICATION_JSON); + } + HttpEntity entity = new HttpEntity<>(body, headers); + try { + return webhookRestTemplate.exchange(apiUri, method, entity, String.class); + } catch (org.springframework.web.client.ResourceAccessException e) { + webhookTimeoutCounter.increment(); + throw e; + } + } + protected String parseTerrakubeCommand(String commentBody) { if (commentBody == null) return null; String lower = commentBody.trim().toLowerCase(); diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookService.java b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookService.java index fce5834a0c..2848f2f193 100644 --- a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookService.java +++ b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookService.java @@ -1,12 +1,13 @@ package io.terrakube.api.plugin.vcs.provider.bitbucket; -import com.fasterxml.jackson.core.JsonProcessingException; import io.terrakube.api.plugin.http.ReactorNettyWebClientFactory; import io.terrakube.api.plugin.vcs.VcsApiUrlValidator; import io.terrakube.api.rs.job.Job; import io.terrakube.api.rs.job.JobVia; import io.terrakube.api.rs.vcs.Vcs; +import io.terrakube.api.rs.webhook.RepoWebhook; import io.terrakube.api.rs.webhook.Webhook; +import io.terrakube.api.rs.webhook.WebhookEventType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; @@ -14,6 +15,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.reactive.function.client.WebClient; import io.terrakube.api.plugin.vcs.WebhookResult; import io.terrakube.api.plugin.vcs.WebhookServiceBase; @@ -34,6 +36,7 @@ import java.time.Duration; import java.time.Instant; import java.util.*; +import java.util.stream.Collectors; @Service @Slf4j @@ -69,19 +72,33 @@ public WebhookResult processWebhook(String jsonPayload, Map head return handleWebhook(jsonPayload, headers, token, "x-hub-signature", JobVia.BITBUCKET.getValue(), this::handleEvent); } + public WebhookResult parseBitBucketPayload(String jsonPayload, Map headers) { + WebhookResult result = new WebhookResult(); + result.setBranch(""); + result.setVia(JobVia.BITBUCKET.getValue()); + result.setValid(true); + try { + result = handleEvent(jsonPayload, result, headers); + } catch (Exception e) { + log.error("Error processing Bitbucket webhook payload", e); + result.setValid(false); + } + return result; + } + public WebhookResult handleEvent(String jsonPayload, WebhookResult result, Map headers) { // Extract event String event = headers.get("x-event-key"); log.info("Bitbucket event: {}", event); - if (event.equals("repo:push")) { + if ("repo:push".equals(event)) { return handlePushEvent(jsonPayload, result); - } else if (event.equals("pullrequest:created") || event.equals("pullrequest:updated")) { + } else if ("pullrequest:created".equals(event) || "pullrequest:updated".equals(event)) { return handlePullRequestEvent(jsonPayload, result); - } else if (event.equals("pullrequest:comment_created")) { + } else if ("pullrequest:comment_created".equals(event)) { return handlePullRequestCommentEvent(jsonPayload, result); } else { - log.error("Unsupported Bitbucket event: {}", result.getEvent()); + log.error("Unsupported Bitbucket event: {}", event); result.setValid(false); } @@ -91,24 +108,43 @@ public WebhookResult handleEvent(String jsonPayload, WebhookResult result, Map")); - result.setCreatedBy(author); - - BitbucketTokenModel bitbucketTokenModel = new ObjectMapper().readValue(jsonPayload, - BitbucketTokenModel.class); - if (bitbucketTokenModel.getPush().getChanges().size() == 1) { - log.info("Bitbucket commit: {}", - bitbucketTokenModel.getPush().getChanges().get(0).getNewCommit().getTarget().getHash()); - log.info("Bitbucket diff file: {}", - bitbucketTokenModel.getPush().getChanges().get(0).getLinks().getDiff().getHref()); - result.setCommit( - bitbucketTokenModel.getPush().getChanges().get(0).getNewCommit().getTarget().getHash()); - result.setFileChanges(getFileChanges( - bitbucketTokenModel.getPush().getChanges().get(0).getLinks().getDiff().getHref(), - result.getWorkspaceId())); - } else { - log.error("Bitbucket webhook with more than 1 changes is not supported"); + JsonNode targetNode = changesNode.path("new").path("target"); + result.setCreatedBy(extractAuthorEmail(targetNode, "Unknown")); + + String commit = targetNode.path("hash").asText(""); + if (!commit.isBlank()) { + log.info("Bitbucket commit: {}", commit); + result.setCommit(commit); + } + + String diffUrl = resolvePushDiffUrl(rootNode, changesNode, commit); + if (diffUrl != null) { + log.info("Bitbucket diff file: {}", diffUrl); + result.setPrFilesUrl(diffUrl); + if (result.getWorkspaceId() != null && !result.getWorkspaceId().isBlank()) { + result.setFileChanges(getFileChanges(diffUrl, result.getWorkspaceId())); + } } return result; } + private String resolvePushDiffUrl(JsonNode rootNode, JsonNode changesNode, String commit) { + String changeDiff = changesNode.path("links").path("diff").path("href").asText(""); + if (!changeDiff.isBlank()) { + return changeDiff; + } + String targetDiff = changesNode.path("new").path("target").path("links").path("diff").path("href").asText(""); + if (!targetDiff.isBlank()) { + return targetDiff; + } + if (commit != null && !commit.isBlank()) { + String repoSelfHref = rootNode.path("repository").path("links").path("self").path("href").asText(""); + if (!repoSelfHref.isBlank()) { + return repoSelfHref.replaceAll("/+$", "") + "/diff/" + commit; + } + } + return null; + } + + private String extractAuthorEmail(JsonNode targetNode, String defaultValue) { + JsonNode authorNode = targetNode.path("author"); + if (!authorNode.has("raw")) { + return defaultValue; + } + String author = authorNode.path("raw").asText(""); + int start = author.indexOf("<"); + int end = author.indexOf(">", start + 1); + if (start >= 0 && end > start) { + return author.substring(start + 1, end); + } + return author.isBlank() ? defaultValue : author; + } + private WebhookResult handlePullRequestEvent(String jsonPayload, WebhookResult result) { result.setEvent("pull_request"); try { @@ -166,7 +231,10 @@ private WebhookResult handlePullRequestEvent(String jsonPayload, WebhookResult r JsonNode linksNode = pullRequestNode.path("links"); if (linksNode.has("diff")) { String diffUrl = linksNode.path("diff").path("href").asText(); - result.setFileChanges(getFileChanges(diffUrl, result.getWorkspaceId())); + result.setPrFilesUrl(diffUrl); + if (result.getWorkspaceId() != null && !result.getWorkspaceId().isBlank()) { + result.setFileChanges(getFileChanges(diffUrl, result.getWorkspaceId())); + } } log.info("Bitbucket pull request event processed for branch: {}", sourceBranch); @@ -178,11 +246,9 @@ private WebhookResult handlePullRequestEvent(String jsonPayload, WebhookResult r return result; } - private WebhookResult handleTagCreationEvent(String jsonPayload, WebhookResult result) { + private WebhookResult handleTagCreationEvent(JsonNode changesNode, WebhookResult result) { result.setEvent("release"); try { - JsonNode rootNode = objectMapper.readTree(jsonPayload); - JsonNode changesNode = rootNode.path("push").path("changes").get(0); JsonNode newNode = changesNode.path("new"); String tagName = newNode.path("name").asText(); @@ -196,15 +262,7 @@ private WebhookResult handleTagCreationEvent(String jsonPayload, WebhookResult r result.setCommit(commit); } - JsonNode authorNode = targetNode.path("author"); - if (authorNode.has("raw")) { - String author = authorNode.path("raw").asText(); - author = author.substring(author.indexOf("<") + 1, author.indexOf(">")); //extract email only - result.setCreatedBy(author); - } else { - result.setCreatedBy("Unknown"); - } - + result.setCreatedBy(extractAuthorEmail(targetNode, "Unknown")); result.setValid(true); log.info("Bitbucket tag creation event processed for tag: {}", tagName); @@ -242,7 +300,10 @@ private WebhookResult handlePullRequestCommentEvent(String jsonPayload, WebhookR JsonNode linksNode = pullRequestNode.path("links"); if (linksNode.has("diff")) { String diffUrl = linksNode.path("diff").path("href").asText(); - result.setFileChanges(getFileChanges(diffUrl, result.getWorkspaceId())); + result.setPrFilesUrl(diffUrl); + if (result.getWorkspaceId() != null && !result.getWorkspaceId().isBlank()) { + result.setFileChanges(getFileChanges(diffUrl, result.getWorkspaceId())); + } } log.info("Bitbucket PR comment event processed for PR #{}", pullRequestNode.path("id").asInt()); @@ -300,18 +361,30 @@ private record DiffFetchResult(String body, String redirectLocation) { } private List getFileChanges(String diffFile, String workspaceId) { - List fileChanges = new ArrayList<>(); if (diffFile == null || diffFile.isBlank() || workspaceId == null || workspaceId.isBlank()) { - return fileChanges; + return new ArrayList<>(); } try { Workspace workspace = workspaceRepository.findById(UUID.fromString(workspaceId)).orElse(null); if (workspace == null || workspace.getVcs() == null) { log.warn("Workspace {} or its VCS is missing, cannot fetch Bitbucket diff", workspaceId); - return fileChanges; + return new ArrayList<>(); } - Vcs vcs = workspace.getVcs(); + return fetchDiffFileChanges(workspace.getVcs(), diffFile); + } catch (Exception e) { + log.error(e.getMessage()); + return new ArrayList<>(); + } + } + + public List fetchDiffFileChanges(Vcs vcs, String diffFile) { + List fileChanges = new ArrayList<>(); + if (vcs == null || diffFile == null || diffFile.isBlank()) { + return fileChanges; + } + + try { if (!VcsApiUrlValidator.isAllowedForVcs(vcs, diffFile)) { log.warn("Blocked Bitbucket diff request to URL outside configured VCS API origin"); return fileChanges; @@ -472,11 +545,105 @@ public void deleteWebhook(Workspace workspace, String webhookRemoteId) { } } + /** + * Creates or updates the single shared Bitbucket webhook for a repository, mirroring + * {@code GitHubWebhookService#createOrUpdateRepoWebhook}. + */ + public String createOrUpdateRepoWebhook(RepoWebhook repoWebhook, Set eventTypes, + boolean hasPrWorkflow, boolean tagEvents) { + String remoteHookId = repoWebhook.getRemoteHookId(); + Vcs vcs = repoWebhook.getVcs(); + String[] ownerAndRepo = extractOwnerAndRepo(repoWebhook.getRepositoryUrl()); + String webhookUrl = String.format("%s/webhook/v2/%s", apiBaseUrl, repoWebhook.getId().toString()); + + Set eventNames = new LinkedHashSet<>(); + if (eventTypes.contains(WebhookEventType.PUSH) || eventTypes.contains(WebhookEventType.RELEASE) || tagEvents) { + eventNames.add("repo:push"); + } + if (eventTypes.contains(WebhookEventType.PULL_REQUEST)) { + eventNames.add("pullrequest:created"); + eventNames.add("pullrequest:updated"); + } + if (hasPrWorkflow) { + eventNames.add("pullrequest:comment_created"); + } + + String eventsJson = eventNames.stream().map(e -> "\"" + e + "\"").collect(Collectors.joining(",")); + String body = "{\"description\":\"Terrakube\",\"url\":\"" + webhookUrl + + "\",\"active\":true,\"events\":[" + eventsJson + + "],\"secret\":\"" + repoWebhook.getWebhookSecret() + "\"}"; + + String hooksUrl = vcs.getApiUrl() + "/repositories/" + String.join("/", ownerAndRepo) + "/hooks"; + + if (remoteHookId != null && !remoteHookId.isEmpty()) { + String updateUrl = remoteHookId.startsWith("http") ? remoteHookId : hooksUrl + "/" + remoteHookId; + if (remoteHookId.startsWith("http") && !VcsApiUrlValidator.isAllowedForVcs(vcs, updateUrl)) { + throw new IllegalStateException("Blocked Bitbucket webhook update to URL outside configured VCS API origin"); + } + try { + callBitBucketApi(vcs.getAccessToken(), body, updateUrl, HttpMethod.PUT); + log.info("Bitbucket repo webhook {} updated", remoteHookId); + return remoteHookId; + } catch (HttpClientErrorException.NotFound _) { + log.warn("Bitbucket repo webhook {} of {} no longer exists, creating it again", + remoteHookId, repoWebhook.getRepositoryUrl()); + remoteHookId = null; + } + } + + ResponseEntity response = callBitBucketApi(vcs.getAccessToken(), body, hooksUrl, HttpMethod.POST); + if (response != null && (response.getStatusCode().value() == 201 || response.getStatusCode().value() == 200)) { + try { + remoteHookId = objectMapper.readTree(response.getBody()).path("uuid").asText(); + } catch (Exception e) { + log.error("Error parsing JSON response", e); + } + log.info("Bitbucket repo webhook created successfully with id {}", remoteHookId); + } + if (remoteHookId == null || remoteHookId.isBlank()) { + throw new IllegalStateException("The Bitbucket repository webhook of " + repoWebhook.getRepositoryUrl() + + " was not created (" + (response == null ? "no response" : "no id returned") + ")"); + } + + return remoteHookId; + } + + /** + * Deletes the shared Bitbucket webhook of an orphaned repository. + */ + public void deleteRepoWebhook(RepoWebhook repoWebhook) { + String remoteHookId = repoWebhook.getRemoteHookId(); + if (remoteHookId == null || remoteHookId.isEmpty()) { + log.warn("No remote hook id found for repo webhook {}, skipping deletion", repoWebhook.getId()); + return; + } + Vcs vcs = repoWebhook.getVcs(); + String ownerAndRepo = String.join("/", extractOwnerAndRepo(repoWebhook.getRepositoryUrl())); + String apiUrl = remoteHookId.startsWith("http") + ? remoteHookId + : vcs.getApiUrl() + "/repositories/" + ownerAndRepo + "/hooks/" + remoteHookId; + if (remoteHookId.startsWith("http") && !VcsApiUrlValidator.isAllowedForVcs(vcs, apiUrl)) { + log.warn("Blocked Bitbucket repo webhook deletion to URL outside configured VCS API origin"); + return; + } + + ResponseEntity response = callBitBucketApi(vcs.getAccessToken(), "", apiUrl, HttpMethod.DELETE); + if (response != null && response.getStatusCode().value() == 204) { + log.info("Repo webhook with remote hook id {} on repository {} deleted successfully", remoteHookId, + ownerAndRepo); + } else { + log.warn("Failed to delete repo webhook with remote hook id {} on repository {}, message {}", remoteHookId, + ownerAndRepo, response != null ? response.getBody() : "no response"); + } + } + private ResponseEntity callBitBucketApi(String token, String body, String apiUrl, HttpMethod httpMethod) { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); headers.set("Authorization", "Bearer " + token); - return makeApiRequest(headers, body, apiUrl, httpMethod); + // Bitbucket webhook UUIDs contain '{...}', which RestTemplate's String overload interprets as URI template variables. + URI encodedUri = URI.create(apiUrl.replace("{", "%7B").replace("}", "%7D")); + return makeApiRequest(headers, body, encodedUri, httpMethod); } } \ No newline at end of file diff --git a/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHook.java b/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHook.java index 8f40bd39b2..dd95b55906 100644 --- a/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHook.java +++ b/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHook.java @@ -63,6 +63,10 @@ private boolean isSharedWebhookProvider(Webhook webhook) { VcsType vcsType = webhook.getWorkspace().getVcs() == null ? null : webhook.getWorkspace().getVcs().getVcsType(); - return vcsType == VcsType.GITHUB || vcsType == VcsType.GITLAB || vcsType == VcsType.AZURE_SP_MI || vcsType == VcsType.AZURE_DEVOPS; + return vcsType == VcsType.GITHUB + || vcsType == VcsType.GITLAB + || vcsType == VcsType.AZURE_SP_MI + || vcsType == VcsType.AZURE_DEVOPS + || vcsType == VcsType.BITBUCKET; } } diff --git a/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHook.java b/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHook.java index 3d3805896b..f29abdb4d4 100644 --- a/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHook.java +++ b/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHook.java @@ -9,6 +9,7 @@ import io.terrakube.api.plugin.vcs.RepoUrlNormalizer; import io.terrakube.api.plugin.vcs.WebhookService; import io.terrakube.api.plugin.vcs.provider.azdevops.AzDevOpsWebhookService; +import io.terrakube.api.plugin.vcs.provider.bitbucket.BitBucketWebhookService; import io.terrakube.api.plugin.vcs.provider.github.GitHubWebhookService; import io.terrakube.api.plugin.vcs.provider.gitlab.GitLabWebhookService; import io.terrakube.api.rs.vcs.VcsType; @@ -37,6 +38,9 @@ public class WebhookManageHook implements LifeCycleHook { @Autowired AzDevOpsWebhookService azDevOpsWebhookService; + @Autowired + BitBucketWebhookService bitBucketWebhookService; + @Autowired RepoWebhookSyncScheduler repoWebhookSyncScheduler; @@ -123,12 +127,16 @@ private boolean isMigratedV2Shared(Webhook elideEntity) { return elideEntity.isMigratedV2() && isSharedWebhookProvider(elideEntity); } - // GitHub, GitLab and Azure DevOps (AZURE_SP_MI / AZURE_DEVOPS) participate in the shared, + // GitHub, GitLab, Azure DevOps (AZURE_SP_MI / AZURE_DEVOPS), and Bitbucket participate in the shared, // repository-level (v2) webhook flow reconciled asynchronously by // RepoWebhookSyncJob. private boolean isSharedWebhookProvider(Webhook elideEntity) { VcsType vcsType = vcsType(elideEntity); - return vcsType == VcsType.GITHUB || vcsType == VcsType.GITLAB || vcsType == VcsType.AZURE_SP_MI || vcsType == VcsType.AZURE_DEVOPS; + return vcsType == VcsType.GITHUB + || vcsType == VcsType.GITLAB + || vcsType == VcsType.AZURE_SP_MI + || vcsType == VcsType.AZURE_DEVOPS + || vcsType == VcsType.BITBUCKET; } private VcsType vcsType(Webhook elideEntity) { @@ -143,6 +151,8 @@ private void deleteWorkspaceHook(Webhook elideEntity) { gitLabWebhookService.deleteWebhook(elideEntity.getWorkspace(), elideEntity.getRemoteHookId()); } else if (type == VcsType.AZURE_SP_MI || type == VcsType.AZURE_DEVOPS) { azDevOpsWebhookService.deleteWebhook(elideEntity.getWorkspace(), elideEntity.getRemoteHookId()); + } else if (type == VcsType.BITBUCKET) { + bitBucketWebhookService.deleteWebhook(elideEntity.getWorkspace(), elideEntity.getRemoteHookId()); } else { gitHubWebhookService.deleteWebhook(elideEntity.getWorkspace(), elideEntity.getRemoteHookId()); } diff --git a/api/src/test/java/io/terrakube/api/ModuleRefreshTransactionsIntegrationTest.java b/api/src/test/java/io/terrakube/api/ModuleRefreshTransactionsIntegrationTest.java index f0dd600e32..ac16c14756 100644 --- a/api/src/test/java/io/terrakube/api/ModuleRefreshTransactionsIntegrationTest.java +++ b/api/src/test/java/io/terrakube/api/ModuleRefreshTransactionsIntegrationTest.java @@ -328,9 +328,9 @@ void webhookEligibleModulesHaveAConnectionThatCanRegisterIt() { Module github = seedSource(repo + ".git", null, null); github.setVcs(vcs(organization, VcsType.GITHUB)); moduleRepository.save(github); - Module bitbucket = seedSource(repo, null, null); - bitbucket.setVcs(vcs(organization, VcsType.BITBUCKET)); - moduleRepository.save(bitbucket); + Module pub = seedSource(repo, null, null); + pub.setVcs(vcs(organization, VcsType.PUBLIC)); + moduleRepository.save(pub); seedSource(repo, null, null); assertThat(transactions.findWebhookEligibleBySource(repo)).extracting(Module::getId) diff --git a/api/src/test/java/io/terrakube/api/RepoWebhookJobAuditIntegrationTest.java b/api/src/test/java/io/terrakube/api/RepoWebhookJobAuditIntegrationTest.java index 9ca711484d..5da613f1b5 100644 --- a/api/src/test/java/io/terrakube/api/RepoWebhookJobAuditIntegrationTest.java +++ b/api/src/test/java/io/terrakube/api/RepoWebhookJobAuditIntegrationTest.java @@ -35,6 +35,7 @@ import io.terrakube.api.plugin.vcs.WebhookProperties; import io.terrakube.api.plugin.vcs.WebhookResult; import io.terrakube.api.plugin.vcs.provider.azdevops.AzDevOpsWebhookService; +import io.terrakube.api.plugin.vcs.provider.bitbucket.BitBucketWebhookService; import io.terrakube.api.plugin.vcs.provider.github.GitHubWebhookService; import io.terrakube.api.plugin.vcs.provider.gitlab.GitLabWebhookService; import io.terrakube.api.repository.RepoWebhookRepository; @@ -146,8 +147,9 @@ private void assertWebhookActor(String eventName, String actor, String expected) try (var worker = Executors.newSingleThreadExecutor()) { RepoWebhookService service = new RepoWebhookService(mock(RepoWebhookRepository.class), workspaceLookup, events, gitHub, mock(GitLabWebhookService.class), mock(AzDevOpsWebhookService.class), - jobRepository, scheduling, mock(PrCommentService.class), mock(RepoWebhookDeliveryTransactions.class), - new ObjectMapper(), worker, mock(WorkspaceBranchPolicy.class), new WebhookProperties(), + mock(BitBucketWebhookService.class), jobRepository, scheduling, mock(PrCommentService.class), + mock(RepoWebhookDeliveryTransactions.class), new ObjectMapper(), worker, + mock(WorkspaceBranchPolicy.class), new WebhookProperties(), mock(ModuleRefreshTransactions.class), new ModuleRefreshProperties(), mock(PrApplyAuthorizationService.class)); service.processClaimedDelivery(repoWebhook, "payload", Map.of()); diff --git a/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java b/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java index e665de0728..c8124f4c0e 100644 --- a/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java +++ b/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java @@ -111,7 +111,7 @@ void missingWebhookUuidReturnsUniformOkWithoutOracle() { } @Test - void bitbucketWorkspaceWithMigratedV2StillProcessesV1AndBlocksAttackerDiff() throws Exception { + void bitbucketMigratedV2WorkspaceReturnsUniformOkAndNeverContactsAttackerOrVcs() throws Exception { Fixture fixture = createWorkspaceWithWebhook(VcsType.BITBUCKET, "https://bitbucket.org/acme/repo.git", true); Map payloadMap = new LinkedHashMap<>(); @@ -134,6 +134,7 @@ void bitbucketWorkspaceWithMigratedV2StillProcessesV1AndBlocksAttackerDiff() thr .statusCode(HttpStatus.OK.value()); assertThat(attackerServer.getAllServeEvents()).isEmpty(); + assertThat(wireMockServer.getAllServeEvents()).isEmpty(); } @Test diff --git a/api/src/test/java/io/terrakube/api/plugin/vcs/RepoWebhookServiceTest.java b/api/src/test/java/io/terrakube/api/plugin/vcs/RepoWebhookServiceTest.java index ba98f29bdb..fde0d79b5b 100644 --- a/api/src/test/java/io/terrakube/api/plugin/vcs/RepoWebhookServiceTest.java +++ b/api/src/test/java/io/terrakube/api/plugin/vcs/RepoWebhookServiceTest.java @@ -43,6 +43,7 @@ import io.terrakube.api.plugin.scheduler.module.ModuleRefreshProperties; import io.terrakube.api.plugin.scheduler.module.ModuleRefreshTransactions; import io.terrakube.api.plugin.vcs.provider.azdevops.AzDevOpsWebhookService; +import io.terrakube.api.plugin.vcs.provider.bitbucket.BitBucketWebhookService; import io.terrakube.api.plugin.vcs.provider.github.GitHubWebhookService; import io.terrakube.api.plugin.vcs.provider.gitlab.GitLabWebhookService; import io.terrakube.api.repository.JobRepository; @@ -72,6 +73,7 @@ class RepoWebhookServiceTest { GitHubWebhookService gitHubWebhookService; GitLabWebhookService gitLabWebhookService; AzDevOpsWebhookService azDevOpsWebhookService; + BitBucketWebhookService bitBucketWebhookService; JobRepository jobRepository; ScheduleJobService scheduleJobService; PrCommentService prCommentService; @@ -93,6 +95,7 @@ void setup() { gitHubWebhookService = mock(GitHubWebhookService.class); gitLabWebhookService = mock(GitLabWebhookService.class); azDevOpsWebhookService = mock(AzDevOpsWebhookService.class); + bitBucketWebhookService = mock(BitBucketWebhookService.class); jobRepository = mock(JobRepository.class); scheduleJobService = mock(ScheduleJobService.class); prCommentService = mock(PrCommentService.class); @@ -112,6 +115,7 @@ void setup() { gitHubWebhookService, gitLabWebhookService, azDevOpsWebhookService, + bitBucketWebhookService, jobRepository, scheduleJobService, prCommentService, @@ -2348,6 +2352,7 @@ void v2WebhookFanoutConcurrencyIsolatesCopiesAcrossWorkspaces() throws Exception gitHubWebhookService, gitLabWebhookService, azDevOpsWebhookService, + bitBucketWebhookService, jobRepository, scheduleJobService, prCommentService, @@ -2665,4 +2670,130 @@ void v2WebhookPullRequestSkipsMismatchedWorkspaceEvenWhenTriggerUsesWildcardBran assertThat(devJob.getTemplateReference()).isEqualTo("dev-plan"); } } + + @Nested + class BitbucketV2 { + + private RepoWebhook bitbucketRepoWebhook(String url, String secret) { + RepoWebhook rw = repoWebhookWith(url, secret); + rw.getVcs().setVcsType(VcsType.BITBUCKET); + return rw; + } + + private Workspace bitbucketWorkspace(String url) { + Workspace ws = workspaceWithSource(url); + ws.getVcs().setVcsType(VcsType.BITBUCKET); + return ws; + } + + @Test + void createOrUpdateSharedWebhookDelegatesToBitbucket() { + String repoUrl = "https://bitbucket.org/owner/repo"; + RepoWebhook rw = bitbucketRepoWebhook(repoUrl, "bb-secret"); + + Workspace ws = bitbucketWorkspace(repoUrl); + Webhook wh = new Webhook(); + WebhookEvent ev = new WebhookEvent(); + ev.setEvent(WebhookEventType.PUSH); + ev.setPrWorkflowEnabled(true); + wh.setEvents(List.of(ev)); + ws.setWebhook(wh); + + when(workspaceRepository.findByNormalizedSourceWithMigratedWebhook(repoUrl)).thenReturn(List.of(ws)); + when(bitBucketWebhookService.createOrUpdateRepoWebhook(rw, Set.of(WebhookEventType.PUSH), true, false)) + .thenReturn("{bb-hook-id}"); + + subject.createOrUpdateSharedWebhook(rw); + + assertThat(rw.getRemoteHookId()).isEqualTo("{bb-hook-id}"); + verify(repoWebhookRepository).save(rw); + verify(gitHubWebhookService, never()).createOrUpdateRepoWebhook(any(), any(), anyBoolean(), anyBoolean()); + } + + @Test + void cleanupIfOrphanDeletesBitbucketRepoWebhook() { + String repoUrl = "https://bitbucket.org/owner/repo"; + RepoWebhook rw = bitbucketRepoWebhook(repoUrl, "bb-secret"); + rw.setRemoteHookId("{bb-hook-id}"); + when(workspaceRepository.findByNormalizedSourceWithMigratedWebhook(repoUrl)).thenReturn(List.of()); + + subject.cleanupIfOrphan(rw); + + verify(bitBucketWebhookService).deleteRepoWebhook(rw); + verify(repoWebhookRepository).delete(rw); + verify(gitHubWebhookService, never()).deleteRepoWebhook(any()); + } + + @Test + void acceptV2WebhookVerifiesBitbucketHmacSignatureHeader() throws Exception { + RepoWebhook rw = bitbucketRepoWebhook("https://bitbucket.org/owner/repo", "bb-secret"); + String payload = "{\"push\":{\"changes\":[]}}"; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec("bb-secret".getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + byte[] digest = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder("sha256="); + for (byte b : digest) { + hex.append(String.format("%02x", b)); + } + UUID deliveryId = UUID.randomUUID(); + when(repoWebhookRepository.findById(rw.getId())).thenReturn(Optional.of(rw)); + when(repoWebhookDeliveryTransactions.enqueue(eq(rw), eq(payload), anyString())).thenReturn(deliveryId); + + UUID accepted = subject.acceptV2Webhook( + rw.getId().toString(), payload, Map.of("X-Hub-Signature", hex.toString())); + assertThat(accepted).isEqualTo(deliveryId); + + assertThatThrownBy(() -> subject.acceptV2Webhook( + rw.getId().toString(), payload, Map.of("X-Hub-Signature", "sha256=wrong"))) + .isInstanceOf(SecurityException.class); + } + + @Test + void processClaimedDeliveryFansOutBitbucketPushAndSkipsCommitStatus() throws Exception { + String repoUrl = "https://bitbucket.org/owner/repo"; + String payload = "{\"push\":{}}"; + RepoWebhook rw = bitbucketRepoWebhook(repoUrl, "bb-secret"); + + Workspace ws = bitbucketWorkspace(repoUrl); + Webhook wh = new Webhook(); + wh.setMigratedV2(true); + WebhookEvent ev = new WebhookEvent(); + ev.setEvent(WebhookEventType.PUSH); + ev.setBranch("main"); + ev.setPath("infra/**"); + ev.setPathType(WebhookEventPathType.PATTERN); + ev.setTemplateId("plan-template"); + wh.setEvents(List.of(ev)); + ws.setWebhook(wh); + + WebhookResult result = new WebhookResult(); + result.setValid(true); + result.setEvent("push"); + result.setBranch("main"); + result.setCommit("deadbeef"); + result.setVia(JobVia.BITBUCKET.getValue()); + result.setPrFilesUrl("https://api.bitbucket.org/2.0/repositories/owner/repo/diff/deadbeef"); + + when(bitBucketWebhookService.parseBitBucketPayload(eq(payload), any())).thenReturn(result); + when(bitBucketWebhookService.fetchDiffFileChanges(rw.getVcs(), result.getPrFilesUrl())) + .thenReturn(List.of("infra/main.tf")); + when(workspaceRepository.findByNormalizedSourceWithMigratedWebhook(repoUrl)).thenReturn(List.of(ws)); + when(webhookEventRepository.findByWebhookAndEventOrderByPriorityAsc(wh, WebhookEventType.PUSH)) + .thenReturn(List.of(ev)); + when(jobRepository.save(any(Job.class))).thenAnswer(inv -> { + Job j = inv.getArgument(0); + j.setId(200); + return j; + }); + + subject.processClaimedDelivery(rw, payload, Map.of("x-event-key", "repo:push")); + + verify(bitBucketWebhookService, times(1)).fetchDiffFileChanges(rw.getVcs(), result.getPrFilesUrl()); + verify(jobRepository, times(1)).save(any(Job.class)); + verify(scheduleJobService, times(1)).createJobContext(any(Job.class)); + verify(gitHubWebhookService, never()).sendCommitStatus(any(), any(), any()); + verify(gitLabWebhookService, never()).sendCommitStatus(any(), any(), any()); + verify(azDevOpsWebhookService, never()).sendCommitStatus(any(), any(), any()); + } + } } diff --git a/api/src/test/java/io/terrakube/api/plugin/vcs/WebhookServiceTest.java b/api/src/test/java/io/terrakube/api/plugin/vcs/WebhookServiceTest.java index 632cd91f52..03c2616240 100644 --- a/api/src/test/java/io/terrakube/api/plugin/vcs/WebhookServiceTest.java +++ b/api/src/test/java/io/terrakube/api/plugin/vcs/WebhookServiceTest.java @@ -690,19 +690,15 @@ public void processWebhookIgnoresMigratedV2WebhookForSharedProvider() { } @Test - public void processWebhookStillProcessesBitbucketWhenMigratedV2FlagIsSet() { + public void processWebhookIgnoresMigratedV2WebhookForBitbucket() { UUID webhookId = UUID.randomUUID(); workspace.setId(UUID.randomUUID()); workspace.getVcs().setVcsType(VcsType.BITBUCKET); webhook.setMigratedV2(true); doReturn(Optional.of(webhook)).when(webhookRepository).findById(webhookId); - WebhookResult bbResult = new WebhookResult(); - bbResult.setValid(false); - doReturn(bbResult).when(bitBucketWebhookService).processWebhook(any(), any(), any()); - assertEquals("", subject.processWebhook(webhookId.toString(), "{}", Map.of())); - verify(bitBucketWebhookService, times(1)).processWebhook(any(), any(), any()); + verify(bitBucketWebhookService, never()).processWebhook(any(), any(), any()); } } diff --git a/api/src/test/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookServiceTest.java b/api/src/test/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookServiceTest.java index d9c19e3fcb..aecf923073 100644 --- a/api/src/test/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookServiceTest.java +++ b/api/src/test/java/io/terrakube/api/plugin/vcs/provider/bitbucket/BitBucketWebhookServiceTest.java @@ -1,14 +1,24 @@ package io.terrakube.api.plugin.vcs.provider.bitbucket; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; 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 java.util.List; import java.util.Map; +import java.util.Set; +import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -18,6 +28,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @@ -25,11 +36,13 @@ import io.terrakube.api.plugin.vcs.WebhookResult; import io.terrakube.api.rs.job.Job; +import io.terrakube.api.rs.job.JobVia; import io.terrakube.api.rs.vcs.Vcs; +import io.terrakube.api.rs.vcs.VcsType; +import io.terrakube.api.rs.webhook.RepoWebhook; +import io.terrakube.api.rs.webhook.WebhookEventType; import io.terrakube.api.rs.workspace.Workspace; -import java.util.Map; - class BitBucketWebhookServiceTest { private WireMockServer server; @@ -42,6 +55,7 @@ void setUp() { server.start(); subject = new BitBucketWebhookService(null, new ObjectMapper()); subject.setWebhookRestTemplate(new RestTemplate(new HttpComponentsClientHttpRequestFactory())); + ReflectionTestUtils.setField(subject, "apiBaseUrl", "https://terrakube.example.com"); Vcs vcs = new Vcs(); vcs.setApiUrl("http://localhost:" + server.port()); @@ -153,6 +167,306 @@ void pullRequestCommentParsesSourceAndDestinationBranches() { assertEquals("develop", result.getBaseBranch()); } + @Test + void parseBitBucketPayloadSupportsPushAndStoresDiffUrl() { + String payload = """ + { + "push": { + "changes": [ + { + "new": { + "type": "branch", + "name": "main", + "target": { + "type": "commit", + "hash": "deadbeef", + "author": {"raw": "Dev "} + } + }, + "links": { + "diff": {"href": "http://localhost:%d/repositories/owner/repo/diff/deadbeef"} + } + } + ] + } + } + """.formatted(server.port()); + + WebhookResult result = subject.parseBitBucketPayload(payload, Map.of("x-event-key", "repo:push")); + + assertTrue(result.isValid()); + assertEquals("push", result.getEvent()); + assertEquals("main", result.getBranch()); + assertEquals("deadbeef", result.getCommit()); + assertEquals("dev@example.com", result.getCreatedBy()); + assertEquals(JobVia.BITBUCKET.getValue(), result.getVia()); + assertEquals("http://localhost:" + server.port() + "/repositories/owner/repo/diff/deadbeef", + result.getPrFilesUrl()); + } + + @Test + void parseBitBucketPayloadRejectsMissingOrUnsupportedEvent() { + WebhookResult missing = subject.parseBitBucketPayload("{}", Map.of()); + WebhookResult unknown = subject.parseBitBucketPayload("{}", Map.of("x-event-key", "repo:fork")); + + assertFalse(missing.isValid()); + assertFalse(unknown.isValid()); + } + + @Test + void fetchDiffFileChangesParsesSameOriginDiffAndBlocksCrossOrigin() { + server.stubFor(get(urlEqualTo("/repositories/owner/repo/diff/123")) + .willReturn(aResponse().withStatus(200) + .withBody("diff --git a/infra/main.tf b/infra/main.tf\n--- a/infra/main.tf\n"))); + + Vcs vcs = job.getWorkspace().getVcs(); + List files = subject.fetchDiffFileChanges(vcs, + "http://localhost:" + server.port() + "/repositories/owner/repo/diff/123"); + List blocked = subject.fetchDiffFileChanges(vcs, "https://attacker.example.com/diff"); + + assertEquals(List.of("infra/main.tf"), files); + assertTrue(blocked.isEmpty()); + } + + @Test + void createOrUpdateRepoWebhookCreatesSharedV2HookAndUpdatesExisting() throws Exception { + RepoWebhook repoWebhook = new RepoWebhook(); + repoWebhook.setId(UUID.fromString("11111111-1111-1111-1111-111111111111")); + repoWebhook.setRepositoryUrl("https://bitbucket.org/owner/repo"); + repoWebhook.setWebhookSecret("bb-secret"); + repoWebhook.setVcs(job.getWorkspace().getVcs()); + + server.stubFor(post(urlEqualTo("/repositories/owner/repo/hooks")) + .willReturn(aResponse().withStatus(201) + .withHeader("Content-Type", "application/json") + .withBody("{\"uuid\":\"{bb-hook-uuid}\"}"))); + + String createdId = subject.createOrUpdateRepoWebhook( + repoWebhook, Set.of(WebhookEventType.PUSH, WebhookEventType.PULL_REQUEST), true, false); + assertEquals("{bb-hook-uuid}", createdId); + + var postBody = new ObjectMapper().readTree(server.getAllServeEvents().getFirst().getRequest().getBody()); + assertEquals("https://terrakube.example.com/webhook/v2/11111111-1111-1111-1111-111111111111", + postBody.path("url").asText()); + assertEquals("bb-secret", postBody.path("secret").asText()); + + repoWebhook.setRemoteHookId("{bb-hook-uuid}"); + server.stubFor(put(urlEqualTo("/repositories/owner/repo/hooks/%7Bbb-hook-uuid%7D")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"uuid\":\"{bb-hook-uuid}\"}"))); + + String updatedId = subject.createOrUpdateRepoWebhook( + repoWebhook, Set.of(WebhookEventType.PUSH), false, true); + assertEquals("{bb-hook-uuid}", updatedId); + server.verify(putRequestedFor(urlEqualTo("/repositories/owner/repo/hooks/%7Bbb-hook-uuid%7D"))); + } + + @Test + void createOrUpdateRepoWebhookRecreatesWhenRemoteHookReturns404AndFailsWhenBlankId() { + RepoWebhook repoWebhook = new RepoWebhook(); + repoWebhook.setId(UUID.randomUUID()); + repoWebhook.setRepositoryUrl("https://bitbucket.org/owner/repo"); + repoWebhook.setWebhookSecret("bb-secret"); + repoWebhook.setRemoteHookId("stale-hook-id"); + Vcs vcs = job.getWorkspace().getVcs(); + vcs.setVcsType(VcsType.BITBUCKET); + repoWebhook.setVcs(vcs); + + server.stubFor(put(urlEqualTo("/repositories/owner/repo/hooks/stale-hook-id")) + .willReturn(aResponse().withStatus(404))); + server.stubFor(post(urlEqualTo("/repositories/owner/repo/hooks")) + .willReturn(aResponse().withStatus(201) + .withHeader("Content-Type", "application/json") + .withBody("{\"uuid\":\"new-hook-id\"}"))); + + String recreatedId = subject.createOrUpdateRepoWebhook(repoWebhook, Set.of(WebhookEventType.PUSH), false, false); + assertEquals("new-hook-id", recreatedId); + server.verify(postRequestedFor(urlEqualTo("/repositories/owner/repo/hooks"))); + + repoWebhook.setRemoteHookId(null); + server.stubFor(post(urlEqualTo("/repositories/owner/repo/hooks")) + .willReturn(aResponse().withStatus(201) + .withHeader("Content-Type", "application/json") + .withBody("{}"))); + assertThrows(IllegalStateException.class, + () -> subject.createOrUpdateRepoWebhook(repoWebhook, Set.of(WebhookEventType.PUSH), false, false)); + } + + @Test + void deleteRepoWebhookDeletesRemoteHookWhenPresent() { + server.stubFor(delete(urlEqualTo("/repositories/owner/repo/hooks/%7Bbb-hook-uuid%7D")) + .willReturn(aResponse().withStatus(204))); + + RepoWebhook repoWebhook = new RepoWebhook(); + repoWebhook.setId(UUID.randomUUID()); + repoWebhook.setRepositoryUrl("https://bitbucket.org/owner/repo"); + repoWebhook.setRemoteHookId("{bb-hook-uuid}"); + repoWebhook.setVcs(job.getWorkspace().getVcs()); + + subject.deleteRepoWebhook(repoWebhook); + + server.verify(deleteRequestedFor(urlEqualTo("/repositories/owner/repo/hooks/%7Bbb-hook-uuid%7D"))); + } + + @Test + void parseBitBucketPayloadHandlesMultiChangePushWithFollowTags() { + String payload = """ + { + "push": { + "changes": [ + { + "new": { + "type": "branch", + "name": "main", + "target": { + "type": "commit", + "hash": "deadbeef", + "author": {"raw": "Dev "} + } + }, + "links": { + "diff": {"href": "http://localhost:%d/repositories/owner/repo/diff/deadbeef"} + } + }, + { + "new": { + "type": "tag", + "name": "v2.1.0", + "target": { + "type": "commit", + "hash": "deadbeef", + "author": {"raw": "Dev "} + } + } + } + ] + } + } + """.formatted(server.port()); + + WebhookResult result = subject.parseBitBucketPayload(payload, Map.of("x-event-key", "repo:push")); + + assertTrue(result.isValid()); + assertEquals("push", result.getEvent()); + assertEquals("main", result.getBranch()); + assertEquals("deadbeef", result.getCommit()); + assertEquals("v2.1.0", result.getTag()); + assertFalse(result.isRelease()); + assertEquals("http://localhost:" + server.port() + "/repositories/owner/repo/diff/deadbeef", + result.getPrFilesUrl()); + } + + @Test + void parseBitBucketPayloadHandlesMultiBranchPush() { + String payload = """ + { + "push": { + "changes": [ + { + "new": { + "type": "branch", + "name": "feature-a", + "target": { + "type": "commit", + "hash": "aaa111", + "author": {"raw": "Dev "} + } + }, + "links": { + "diff": {"href": "http://localhost:%d/repositories/owner/repo/diff/aaa111"} + } + }, + { + "new": { + "type": "branch", + "name": "feature-b", + "target": { + "type": "commit", + "hash": "bbb222", + "author": {"raw": "Dev "} + } + }, + "links": { + "diff": {"href": "http://localhost:%d/repositories/owner/repo/diff/bbb222"} + } + } + ] + } + } + """.formatted(server.port(), server.port()); + + WebhookResult result = subject.parseBitBucketPayload(payload, Map.of("x-event-key", "repo:push")); + + assertTrue(result.isValid()); + assertEquals("push", result.getEvent()); + assertEquals("feature-a", result.getBranch()); + assertEquals("aaa111", result.getCommit()); + assertEquals("http://localhost:" + server.port() + "/repositories/owner/repo/diff/aaa111", + result.getPrFilesUrl()); + } + + @Test + void parseBitBucketPayloadFallsBackToCommitDiffOnNewBranchPush() { + String targetDiffPayload = """ + { + "push": { + "changes": [ + { + "old": null, + "new": { + "type": "branch", + "name": "new-branch", + "target": { + "type": "commit", + "hash": "ccc333", + "author": {"raw": "Dev "}, + "links": { + "diff": {"href": "http://localhost:%d/repositories/owner/repo/diff/ccc333"} + } + } + } + } + ] + } + } + """.formatted(server.port()); + + WebhookResult targetResult = subject.parseBitBucketPayload(targetDiffPayload, Map.of("x-event-key", "repo:push")); + assertEquals("http://localhost:" + server.port() + "/repositories/owner/repo/diff/ccc333", + targetResult.getPrFilesUrl()); + + String repoSelfPayload = """ + { + "repository": { + "links": { + "self": {"href": "http://localhost:%d/repositories/owner/repo/"} + } + }, + "push": { + "changes": [ + { + "old": null, + "new": { + "type": "branch", + "name": "new-branch", + "target": { + "type": "commit", + "hash": "ddd444", + "author": {"raw": "Dev "} + } + } + } + ] + } + } + """.formatted(server.port()); + + WebhookResult selfResult = subject.parseBitBucketPayload(repoSelfPayload, Map.of("x-event-key", "repo:push")); + assertEquals("http://localhost:" + server.port() + "/repositories/owner/repo/diff/ddd444", + selfResult.getPrFilesUrl()); + } + private void assertUtf8JsonBody(String markdown) throws Exception { assertEquals(1, server.getAllServeEvents().size()); var request = server.getAllServeEvents().getFirst().getRequest(); diff --git a/api/src/test/java/io/terrakube/api/rs/hooks/module/ModuleManageHookTest.java b/api/src/test/java/io/terrakube/api/rs/hooks/module/ModuleManageHookTest.java index 91ad86d506..a215217164 100644 --- a/api/src/test/java/io/terrakube/api/rs/hooks/module/ModuleManageHookTest.java +++ b/api/src/test/java/io/terrakube/api/rs/hooks/module/ModuleManageHookTest.java @@ -78,7 +78,7 @@ void createSyncsTheRepositoryWebhookWhenEnabled() { void modulesWithoutASupportedConnectionKeepPolling() { properties.getWebhook().setEnabled(true); - hook.execute(Operation.CREATE, TransactionPhase.POSTCOMMIT, module(VcsType.BITBUCKET), null, Optional.empty()); + hook.execute(Operation.CREATE, TransactionPhase.POSTCOMMIT, module(VcsType.PUBLIC), null, Optional.empty()); hook.execute(Operation.CREATE, TransactionPhase.POSTCOMMIT, module(null), null, Optional.empty()); verify(repoWebhookSyncScheduler, never()).scheduleSync(anyString(), any()); diff --git a/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHookTest.java b/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHookTest.java index c9b2fdb1e0..bb99d5fa6f 100644 --- a/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHookTest.java +++ b/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookEventManageHookTest.java @@ -61,13 +61,23 @@ void execute_v2AzureSpMiEventChangeSchedulesSync() { "https://dev.azure.com/org/proj/repo", "11111111-1111-1111-1111-111111111111"); } + @Test + void execute_v2BitbucketEventChangeSchedulesSync() { + WebhookEvent event = eventFor(VcsType.BITBUCKET, true, "https://bitbucket.org/owner/repo.git"); + + subject.execute(Operation.CREATE, TransactionPhase.POSTCOMMIT, event, null, Optional.empty()); + + verify(repoWebhookSyncScheduler).scheduleSync( + "https://bitbucket.org/owner/repo", "11111111-1111-1111-1111-111111111111"); + } + @Test void execute_nonV2OrNonSharedEventChangeDoesNotScheduleSync() { WebhookEvent v1Event = eventFor(VcsType.GITHUB, false, "https://github.com/owner/repo"); - WebhookEvent bitbucketEvent = eventFor(VcsType.BITBUCKET, true, "https://bitbucket.org/owner/repo"); + WebhookEvent publicEvent = eventFor(VcsType.PUBLIC, true, "https://github.com/owner/repo"); subject.execute(Operation.UPDATE, TransactionPhase.POSTCOMMIT, v1Event, null, Optional.empty()); - subject.execute(Operation.UPDATE, TransactionPhase.POSTCOMMIT, bitbucketEvent, null, Optional.empty()); + subject.execute(Operation.UPDATE, TransactionPhase.POSTCOMMIT, publicEvent, null, Optional.empty()); verifyNoInteractions(repoWebhookSyncScheduler); } diff --git a/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHookTest.java b/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHookTest.java index 6a43e9a9bc..a7956de96b 100644 --- a/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHookTest.java +++ b/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHookTest.java @@ -3,6 +3,7 @@ import io.terrakube.api.plugin.scheduler.webhook.RepoWebhookSyncScheduler; import io.terrakube.api.plugin.vcs.WebhookService; import io.terrakube.api.plugin.vcs.provider.azdevops.AzDevOpsWebhookService; +import io.terrakube.api.plugin.vcs.provider.bitbucket.BitBucketWebhookService; import io.terrakube.api.plugin.vcs.provider.github.GitHubWebhookService; import io.terrakube.api.plugin.vcs.provider.gitlab.GitLabWebhookService; import io.terrakube.api.rs.vcs.Vcs; @@ -47,6 +48,9 @@ class WebhookManageHookTest { @Mock AzDevOpsWebhookService azDevOpsWebhookService; + @Mock + BitBucketWebhookService bitBucketWebhookService; + @Mock RepoWebhookSyncScheduler repoWebhookSyncScheduler; @@ -132,9 +136,9 @@ void execute_revertFromMigratedV2_postcommitStillSchedulesSync() { @Test void execute_nonSharedProvider_postcommitDoesNotScheduleSync() { Workspace workspace = new Workspace(); - workspace.setSource("https://bitbucket.org/owner/repo"); + workspace.setSource("https://github.com/owner/repo"); Vcs vcs = new Vcs(); - vcs.setVcsType(VcsType.BITBUCKET); + vcs.setVcsType(VcsType.PUBLIC); workspace.setVcs(vcs); Webhook webhook = new Webhook(); @@ -146,6 +150,30 @@ void execute_nonSharedProvider_postcommitDoesNotScheduleSync() { verifyNoInteractions(repoWebhookSyncScheduler); } + @Test + void execute_bitbucket_migrationV2_precommitDeletesV1HookAndPostcommitSchedulesSync() { + Workspace workspace = new Workspace(); + workspace.setId(java.util.UUID.fromString("55555555-5555-5555-5555-555555555555")); + workspace.setSource("https://bitbucket.org/owner/repo"); + Vcs vcs = new Vcs(); + vcs.setVcsType(VcsType.BITBUCKET); + workspace.setVcs(vcs); + + Webhook webhook = new Webhook(); + webhook.setWorkspace(workspace); + webhook.setMigratedV2(true); + webhook.setRemoteHookId("bb-v1-hook-id"); + + subject.execute(Operation.UPDATE, TransactionPhase.PRECOMMIT, webhook, requestScope, Optional.empty()); + verify(bitBucketWebhookService).deleteWebhook(workspace, "bb-v1-hook-id"); + assertNull(webhook.getRemoteHookId()); + verifyNoInteractions(repoWebhookSyncScheduler); + + subject.execute(Operation.UPDATE, TransactionPhase.POSTCOMMIT, webhook, requestScope, Optional.empty()); + verify(repoWebhookSyncScheduler).scheduleSync( + "https://bitbucket.org/owner/repo", "55555555-5555-5555-5555-555555555555"); + } + @Test void execute_gitlab_postcommitSchedulesSync() { Workspace workspace = new Workspace(); diff --git a/ui/src/domain/Workspaces/Settings/Webhook.tsx b/ui/src/domain/Workspaces/Settings/Webhook.tsx index 796847eae9..fc50d4d90a 100644 --- a/ui/src/domain/Workspaces/Settings/Webhook.tsx +++ b/ui/src/domain/Workspaces/Settings/Webhook.tsx @@ -88,7 +88,13 @@ const toAttributes = (trigger: Trigger, position: number) => ({ }); const EVENT_LABELS: Record = { push: "Push", pull_request: "Pull request", release: "Release" }; -const SHARED_WEBHOOK_VCS = [VcsType.GITHUB, VcsType.GITLAB, VcsType.AZURE_SP_MI, VcsType.AZURE_DEVOPS]; +const SHARED_WEBHOOK_VCS = [ + VcsType.GITHUB, + VcsType.GITLAB, + VcsType.AZURE_SP_MI, + VcsType.AZURE_DEVOPS, + VcsType.BITBUCKET, +]; // Explicitly drop Content-Type: Elide's Spring routing maps DELETE requests carrying // "application/vnd.api+json" to its relationship-delete handler, which then rejects them. const deleteHeaders = { headers: { "Content-Type": undefined } }; diff --git a/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx b/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx index ddcac6cc89..a7aa29a1ad 100644 --- a/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx +++ b/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx @@ -284,7 +284,7 @@ describe("WorkspaceWebhook", () => { expect(ops[0]).toMatchObject({ op: "add", data: { type: "webhook", attributes: { migratedV2: true } } }); }); - it("offers no shared webhook for a provider that can't share one", async () => { + it("offers shared webhook for Bitbucket", async () => { render( { ); await screen.findByText("Triggers (1)"); + expect(screen.getByRole("button", { name: /Migrate to shared webhook/i })).toBeInTheDocument(); + }); + + it("offers no shared webhook for a provider that can't share one", async () => { + render( + + + + ); + await screen.findByText("Triggers (1)"); + expect(screen.queryByRole("button", { name: /shared webhook/i })).not.toBeInTheDocument(); }); });