Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<VcsType> 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]+@");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -63,6 +64,7 @@ public class RepoWebhookService {
GitHubWebhookService gitHubWebhookService;
GitLabWebhookService gitLabWebhookService;
AzDevOpsWebhookService azDevOpsWebhookService;
BitBucketWebhookService bitBucketWebhookService;
JobRepository jobRepository;
ScheduleJobService scheduleJobService;
PrCommentService prCommentService;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down Expand Up @@ -213,6 +228,7 @@ public UUID acceptV2Webhook(String repoWebhookId, String jsonPayload, Map<String

boolean gitlab = isGitLab(repoWebhook);
boolean azureDevOps = isAzureDevOps(repoWebhook);
boolean bitbucket = isBitBucket(repoWebhook);
if (azureDevOps) {
if (!verifyAzDevOpsToken(headers, repoWebhook.getWebhookSecret())) {
log.error("Token verification failed for repo webhook {}", repoWebhookId);
Expand All @@ -223,7 +239,12 @@ public UUID acceptV2Webhook(String repoWebhookId, String jsonPayload, Map<String
log.error("Token verification failed for repo webhook {}", repoWebhookId);
throw new SecurityException("GitLab token verification failed");
}
} else if (!verifyHmacSignature(headers, repoWebhook.getWebhookSecret(), jsonPayload)) {
} else if (bitbucket) {
if (!verifyHmacSignature(headers, "x-hub-signature", repoWebhook.getWebhookSecret(), jsonPayload)) {
log.error("Signature verification failed for repo webhook {}", repoWebhookId);
throw new SecurityException("Bitbucket HMAC signature verification failed");
}
} else if (!verifyHmacSignature(headers, "x-hub-signature-256", repoWebhook.getWebhookSecret(), jsonPayload)) {
log.error("Signature verification failed for repo webhook {}", repoWebhookId);
throw new SecurityException("HMAC signature verification failed");
}
Expand All @@ -241,12 +262,15 @@ public void processClaimedDelivery(RepoWebhook repoWebhook, String jsonPayload,
headers = WebhookHeaders.caseInsensitive(headers);
boolean azureDevOps = isAzureDevOps(repoWebhook);
boolean gitlab = isGitLab(repoWebhook);
boolean bitbucket = isBitBucket(repoWebhook);

WebhookResult webhookResult;
if (azureDevOps) {
webhookResult = azDevOpsWebhookService.parseAzDevOpsPayload(jsonPayload, headers);
} else if (gitlab) {
webhookResult = gitLabWebhookService.parseGitLabPayload(jsonPayload, headers);
} else if (bitbucket) {
webhookResult = bitBucketWebhookService.parseBitBucketPayload(jsonPayload, headers);
} else {
webhookResult = gitHubWebhookService.parseGitHubPayload(jsonPayload, headers);
}
Expand Down Expand Up @@ -281,11 +305,17 @@ public void processClaimedDelivery(RepoWebhook repoWebhook, String jsonPayload,
// excluded: per-workspace credentials there aren't just a fallback, see the comment in
// processWorkspaceWebhook.
if (!azureDevOps && webhookResult.getPrFilesUrl() != null && repoWebhook.getVcs() != null) {
List<String> prFiles = gitlab
? gitLabWebhookService.fetchPrFileChanges(repoWebhook.getVcs(), normalizedUrl,
webhookResult.getPrFilesUrl())
: gitHubWebhookService.fetchPrFileChanges(repoWebhook.getVcs(), normalizedUrl,
webhookResult.getPrFilesUrl());
List<String> 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);
}

Expand Down Expand Up @@ -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<String> prFiles = isGitLab(workspace)
? gitLabWebhookService.fetchPrFileChanges(
workspace.getVcs(), workspace.getSource(), webhookResult.getPrFilesUrl())
: gitHubWebhookService.fetchPrFileChanges(
workspace.getVcs(), workspace.getSource(), webhookResult.getPrFilesUrl());
List<String> 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());
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -576,11 +612,11 @@ private boolean verifyGitlabToken(Map<String, String> headers, String secret) {
secret.getBytes(StandardCharsets.UTF_8));
}

private boolean verifyHmacSignature(Map<String, String> headers, String secret, String payload) {
private boolean verifyHmacSignature(Map<String, String> 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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bitbucket Server / Data Center connections are also stored as VcsType.BITBUCKET (see the comment in BitbucketRepositoryDiscoveryService, they differ only by apiUrl), but createOrUpdateRepoWebhook builds the Cloud-only {apiUrl}/repositories/{owner}/{repo}/hooks URL and the parser only knows Cloud event keys.

For a Server repo the webhook is saved as migratedV2=true, the background sync fails, and v1 deliveries are ignored for migrated rows, so the workspace ends up with a webhook that never fires. Before this PR the v1 path failed loudly with a 424.

Could we gate this on apiUrl containing api.bitbucket.org (same check discovery uses), here, in the two hook copies of isSharedWebhookProvider, and in SHARED_WEBHOOK_VCS in the UI?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bitbucket Cloud is the only supported option for Bitbucket webhooks in Terrakube, so keeping VcsType.BITBUCKET enabled for Webhook v2 without gating on api.bitbucket.org is intentional.

}

private void sendCommitStatus(Job job) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,19 @@ protected ResponseEntity<String> makeApiRequest(HttpHeaders headers, String body
}
}

protected ResponseEntity<String> makeApiRequest(HttpHeaders headers, String body, URI apiUri, HttpMethod method) {
if (body != null && !body.isEmpty() && headers.getContentType() == null) {
headers.setContentType(MediaType.APPLICATION_JSON);
}
HttpEntity<String> 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();
Expand Down
Loading
Loading