Skip to content

feat: add Bitbucket support for shared repository webhooks (v2) - #4064

Open
alfespa17 wants to merge 2 commits into
mainfrom
feat/webhook-v2-bitbucket
Open

alfespa17 wants to merge 2 commits into
mainfrom
feat/webhook-v2-bitbucket

Conversation

@alfespa17

@alfespa17 alfespa17 commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 1 of the stacked PR plan to deprecate Webhook v1 and standardize on shared repository webhooks (Webhook v2): adds full Webhook v2 support for Bitbucket (VcsType.BITBUCKET), the remaining webhook-capable VCS provider without v2 support.

Stack Overview

PR Branch Base Scope Status
#4064 (This PR) feat/webhook-v2-bitbucket main Bitbucket Webhook v2 support (API + UI) Open
#4065 feat/webhook-v1-disable-flag feat/webhook-v2-bitbucket io.terrakube.webhook.v1.disabled flag, 404/hook enforcement, UI v2-only creation Open
#4066 feat/webhook-v1-to-v2-startup-migration feat/webhook-v1-disable-flag Startup @DisallowConcurrentExecution Quartz migration job + default disabled=true Open

Changes

  • BitBucketWebhookService:
    • Extracted SSRF-checked, same-origin-redirect-safe fetchDiffFileChanges(Vcs, String) shared by v1 and v2.
    • Added parseBitBucketPayload(String, Map<String, String>) for v2 deliveries (repo:push, pullrequest:created, pullrequest:updated, pullrequest:comment_created, tag pushes) with null-safe event checks and prFilesUrl population.
    • Added createOrUpdateRepoWebhook(...) (PUT with 404 -> POST re-creation fallback) and deleteRepoWebhook(...).
    • Updated callBitBucketApi & WebhookServiceBase.makeApiRequest(..., URI, ...) to percent-encode { and } in Bitbucket hook UUIDs so RestTemplate does not treat them as URI template variables.
  • RepoWebhookService:
    • Wired BitBucketWebhookService into createOrUpdateSharedWebhook, cleanupIfOrphan, acceptV2Webhook (x-hub-signature HMAC-SHA256 verification), processClaimedDelivery, processWorkspaceWebhook, and saveAndScheduleJob (skipping commit status for Bitbucket).
  • Shared Webhook Providers (API & UI):
    • Added VcsType.BITBUCKET to WebhookService.isSharedWebhookProvider, WebhookManageHook, WebhookEventManageHook, ModuleRefreshTransactions.WEBHOOK_VCS_TYPES, and Webhook.tsx (SHARED_WEBHOOK_VCS).
  • Tests:
    • Added and updated unit & integration tests across BitBucketWebhookServiceTest, RepoWebhookServiceTest, RepoWebhookJobAuditIntegrationTest, WebhookServiceTest, WebhookManageHookTest, WebhookEventManageHookTest, WebhookV1MigratedSecurityIntegrationTest, ModuleManageHookTest, ModuleRefreshTransactionsIntegrationTest, and Webhook.test.tsx.

Verification

  • API unit tests (BitBucketWebhookServiceTest, RepoWebhookServiceTest, WebhookServiceTest, WebhookManageHookTest, WebhookEventManageHookTest, WebhookSecurityHardeningTest, ModuleManageHookTest): 154 tests passed (0 failures, 0 errors).
  • API integration tests (ModuleRefreshTransactionsIntegrationTest, WebhookV1MigratedSecurityIntegrationTest, RepoWebhookJobAuditIntegrationTest): 33 tests passed (0 failures, 0 errors).
  • UI tests & checks (Webhook.test.tsx: 27/27 passed; lint:check: 0 errors; format:check & typecheck: passed).

@Macbet Macbet left a comment

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.

Looks good overall: HMAC check is constant-time and fails closed, the SSRF/same-origin check covers the diff URL on every redirect hop, and the {} encoding also fixes the v1 deleteWebhook. A few things inline, the Bitbucket Server one being the most important.

One thing outside this diff that is worth a separate issue: PrApplyAuthorizationService.refusalReason has no Bitbucket branch and falls through to default -> Optional.empty(), so with PR apply enabled any user who can comment on the PR can trigger an apply. This already applies to v1, so it is not a regression of this PR.

|| 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.

@@ -129,15 +147,17 @@ private WebhookResult handlePushCommit(String jsonPayload, WebhookResult result,
BitbucketTokenModel bitbucketTokenModel = new ObjectMapper().readValue(jsonPayload,
BitbucketTokenModel.class);
if (bitbucketTokenModel.getPush().getChanges().size() == 1) {

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.

Pushes with more than one change are dropped: handlePushEvent only looks at changes[0], and here with size() != 1 neither the commit nor the diff URL is set, so checkFileChanges gets nothing and no job is created. git push --follow-tags or git push origin a b produce such payloads, and a tag sitting in changes[1] never marks modules as due.

This is inherited from v1, but v2 now depends on it for every workspace sharing the repo. Iterating over the changes (first branch change, plus each tag change) would cover it.

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.

Fixed in 8816190bb — BitBucketWebhookService.handlePushEvent now iterates over all entries in push.changes, processing the first branch commit change, recording any accompanying tag name (e.g. git push --follow-tags) on result.setTag(...) for module refresh, and handling tag-only pushes as release events. Added unit tests for multi-change pushes in BitBucketWebhookServiceTest.

bitbucketTokenModel.getPush().getChanges().get(0).getLinks().getDiff().getHref(),
result.getWorkspaceId()));
var change = bitbucketTokenModel.getPush().getChanges().get(0);
String diffUrl = change.getLinks() != null && change.getLinks().getDiff() != null

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.

Not verified against a real delivery, so treat as a question: for the first push to a new branch (old is null) does Bitbucket include links.diff? If it does not, diffUrl is null here, there are no file changes, and the push never matches a workspace path filter. A fallback to the commit diff for new.target.hash would close that gap.

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.

Fixed in 8816190bb — added resolvePushDiffUrl fallback when change.links.diff.href is omitted: it checks change.new.target.links.diff.href and then derives {repository.links.self.href}/diff/{commit} (still validated by VcsApiUrlValidator.isAllowedForVcs). Added unit tests covering both fallbacks.

@alfespa17

Copy link
Copy Markdown
Member Author

Addressed the inline feedback on feat/webhook-v2-bitbucket in commit 8816190bb. Regarding PrApplyAuthorizationService.refusalReason for Bitbucket: agreed that is a pre-existing v1 gap outside this PR — we can track it in a separate follow-up issue.

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/scheduler Touches job scheduling, queueing or locking author/maintainer Authored by a maintainer priority/high Review soon: high-risk area, bug fix or security update size/L 250-999 lines changed terrakube-api terrakube-ui type/feature New functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants