diff --git a/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationJob.java b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationJob.java
new file mode 100644
index 0000000000..59ad3a9727
--- /dev/null
+++ b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationJob.java
@@ -0,0 +1,39 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import org.quartz.DisallowConcurrentExecution;
+import org.quartz.Job;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Quartz job executed at API startup when webhook v1 is disabled, migrating any remaining
+ * workspaces from legacy v1 webhooks to shared v2 repository webhooks.
+ *
+ *
{@code @DisallowConcurrentExecution} ensures Quartz never runs overlapping instances of
+ * this migration job across cluster replicas or misfires.
+ */
+@Slf4j
+@Component
+@DisallowConcurrentExecution
+@RequiredArgsConstructor
+public class WebhookV1ToV2MigrationJob implements Job {
+
+ private final WebhookV1ToV2MigrationService migrationService;
+
+ @Override
+ public void execute(JobExecutionContext context) throws JobExecutionException {
+ log.info("Starting Quartz webhook v1->v2 startup migration job");
+ WebhookV1ToV2MigrationService.MigrationSummary summary = migrationService.migrateAllUnmigrated();
+ if (summary.failed() > 0) {
+ log.warn("Finished Quartz webhook v1->v2 startup migration job with errors (migrated={}, skipped={}, failed={})",
+ summary.migrated(), summary.skipped(), summary.failed());
+ } else {
+ log.info("Finished Quartz webhook v1->v2 startup migration job (migrated={}, skipped={}, failed={})",
+ summary.migrated(), summary.skipped(), summary.failed());
+ }
+ }
+}
diff --git a/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationScheduler.java b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationScheduler.java
new file mode 100644
index 0000000000..c6fbe121cc
--- /dev/null
+++ b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationScheduler.java
@@ -0,0 +1,90 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import org.quartz.JobBuilder;
+import org.quartz.JobDetail;
+import org.quartz.JobKey;
+import org.quartz.JobPersistenceException;
+import org.quartz.ObjectAlreadyExistsException;
+import org.quartz.Scheduler;
+import org.quartz.SchedulerException;
+import org.quartz.Trigger;
+import org.quartz.TriggerBuilder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.stereotype.Service;
+
+import io.terrakube.api.plugin.vcs.WebhookProperties;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Schedules {@link WebhookV1ToV2MigrationJob} once on API startup when webhook v1 is disabled,
+ * using a deterministic {@link JobKey} so multi-replica deployments coalesce onto one execution
+ * in the clustered Quartz JDBC job store.
+ */
+@Slf4j
+@Service
+public class WebhookV1ToV2MigrationScheduler {
+
+ static final JobKey JOB_KEY = new JobKey("TerrakubeV2_WebhookV1ToV2Migration", "webhook-v1-migration");
+
+ private final Scheduler scheduler;
+ private final WebhookProperties webhookProperties;
+ private final WebhookV1ToV2MigrationTransactions transactions;
+
+ @Autowired
+ public WebhookV1ToV2MigrationScheduler(@Autowired(required = false) Scheduler scheduler,
+ WebhookProperties webhookProperties,
+ WebhookV1ToV2MigrationTransactions transactions) {
+ this.scheduler = scheduler;
+ this.webhookProperties = webhookProperties;
+ this.transactions = transactions;
+ }
+
+ @EventListener(ApplicationReadyEvent.class)
+ public void scheduleMigrationOnStartup() {
+ if (!webhookProperties.getV1().isDisabled()) {
+ log.info("Webhook v1 is enabled; skipping startup v1->v2 migration job");
+ return;
+ }
+ if (!webhookProperties.getV1().isMigrationOnStartup()) {
+ long remaining = transactions != null
+ ? transactions.countUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES)
+ : 0;
+ if (remaining > 0) {
+ log.warn("Webhook v1 is disabled (404) and startup migration is disabled, but {} unmigrated v1 webhook(s) remain; enable io.terrakube.webhook.v1.migration-on-startup or set WebhookV1Disabled=false to avoid dropped deliveries",
+ remaining);
+ } else {
+ log.info("Webhook v1->v2 startup migration job is disabled by configuration");
+ }
+ return;
+ }
+ if (scheduler == null) {
+ log.warn("Quartz scheduler is not available; skipping webhook v1->v2 startup migration");
+ return;
+ }
+
+ JobDetail jobDetail = JobBuilder.newJob(WebhookV1ToV2MigrationJob.class)
+ .withIdentity(JOB_KEY)
+ .withDescription("Migrate remaining webhook v1 workspaces to webhook v2 on startup")
+ .storeDurably(false)
+ .build();
+
+ Trigger trigger = TriggerBuilder.newTrigger()
+ .forJob(jobDetail)
+ .withIdentity(JOB_KEY.getName(), JOB_KEY.getGroup())
+ .startNow()
+ .build();
+
+ try {
+ scheduler.scheduleJob(jobDetail, trigger);
+ log.info("Scheduled webhook v1->v2 startup migration job {}", JOB_KEY);
+ } catch (ObjectAlreadyExistsException _) {
+ log.info("Webhook v1->v2 startup migration job {} is already scheduled by another replica", JOB_KEY);
+ } catch (JobPersistenceException e) {
+ log.info("Webhook v1->v2 startup migration job {} lost race to schedule on another replica", JOB_KEY, e);
+ } catch (SchedulerException e) {
+ log.error("Failed to schedule webhook v1->v2 startup migration job: {}", e.getMessage(), e);
+ }
+ }
+}
diff --git a/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationService.java b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationService.java
new file mode 100644
index 0000000000..626e8b1327
--- /dev/null
+++ b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationService.java
@@ -0,0 +1,208 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.stereotype.Service;
+
+import io.terrakube.api.plugin.vcs.RepoUrlNormalizer;
+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;
+import io.terrakube.api.rs.vcs.VcsType;
+import io.terrakube.api.rs.webhook.Webhook;
+import io.terrakube.api.rs.workspace.Workspace;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Migrates remaining v1 workspace webhooks to shared v2 repository webhooks and retries any
+ * previously migrated webhooks that still have a pending {@code syncError} or unconfirmed legacy
+ * {@code remoteHookId}.
+ *
+ *
Unmigrated webhooks are grouped by normalized repository URL so every workspace sharing a
+ * repository is marked {@code migratedV2 = true} before scheduling a single
+ * {@link RepoWebhookSyncJob} per repository, preventing coalescing races and ensuring shared hooks
+ * include all workspaces' event types. Legacy v1 remote hook deletion runs best-effort after v2
+ * sync scheduling, and {@code remoteHookId} is cleared only when deletion is confirmed.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class WebhookV1ToV2MigrationService {
+
+ public static final Set SUPPORTED_VCS_TYPES = Set.of(
+ VcsType.GITHUB,
+ VcsType.GITLAB,
+ VcsType.AZURE_DEVOPS,
+ VcsType.AZURE_SP_MI,
+ VcsType.BITBUCKET);
+
+ public record MigrationSummary(int migrated, int skipped, int failed) {
+ }
+
+ private final WebhookV1ToV2MigrationTransactions transactions;
+ private final GitHubWebhookService gitHubWebhookService;
+ private final GitLabWebhookService gitLabWebhookService;
+ private final AzDevOpsWebhookService azDevOpsWebhookService;
+ private final BitBucketWebhookService bitBucketWebhookService;
+ private final RepoWebhookSyncScheduler repoWebhookSyncScheduler;
+
+ public MigrationSummary migrateAllUnmigrated() {
+ List unmigrated = transactions.findUnmigratedV1Webhooks(SUPPORTED_VCS_TYPES);
+ List needsRetry = transactions.findMigratedWebhooksNeedingRetry(SUPPORTED_VCS_TYPES);
+
+ if (unmigrated.isEmpty() && needsRetry.isEmpty()) {
+ log.info("No unmigrated v1 webhooks or pending migration retries found; startup migration complete");
+ return new MigrationSummary(0, 0, 0);
+ }
+
+ int migrated = 0;
+ int skipped = 0;
+ int failed = 0;
+
+ if (!unmigrated.isEmpty()) {
+ log.info("Found {} unmigrated v1 webhook(s); grouping by repository for migration to v2",
+ unmigrated.size());
+ Map> groupedByRepo = new LinkedHashMap<>();
+ for (Webhook webhook : unmigrated) {
+ Workspace workspace = webhook.getWorkspace();
+ Vcs vcs = workspace != null ? workspace.getVcs() : null;
+ String normalizedUrl = workspace != null ? RepoUrlNormalizer.normalize(workspace.getSource()) : null;
+ if (workspace == null || vcs == null || normalizedUrl == null) {
+ log.warn("Skipping v1 webhook {} migration: missing workspace, VCS connection, or source URL",
+ webhook.getId());
+ skipped++;
+ continue;
+ }
+ groupedByRepo.computeIfAbsent(normalizedUrl, _ -> new ArrayList<>()).add(webhook);
+ }
+
+ for (Map.Entry> entry : groupedByRepo.entrySet()) {
+ String normalizedUrl = entry.getKey();
+ List repoWebhooks = entry.getValue();
+ List markedInGroup = new ArrayList<>();
+ String seedWorkspaceId = null;
+
+ for (Webhook webhook : repoWebhooks) {
+ try {
+ if (transactions.markMigrated(webhook.getId())) {
+ markedInGroup.add(webhook);
+ if (seedWorkspaceId == null && webhook.getWorkspace().getId() != null) {
+ seedWorkspaceId = webhook.getWorkspace().getId().toString();
+ }
+ migrated++;
+ } else {
+ skipped++;
+ }
+ } catch (Exception e) {
+ log.error("Failed to mark webhook {} on workspace {} as migrated: {}",
+ webhook.getId(), webhook.getWorkspace().getId(), e.getMessage(), e);
+ transactions.recordMigrationError(webhook.getId(), RepoWebhookSyncStatus.describe(e));
+ failed++;
+ }
+ }
+
+ if (!markedInGroup.isEmpty()) {
+ try {
+ repoWebhookSyncScheduler.scheduleSync(normalizedUrl, seedWorkspaceId);
+ log.info("Marked {} webhook(s) migrated for {} and scheduled shared v2 sync",
+ markedInGroup.size(), normalizedUrl);
+ } catch (Exception e) {
+ log.error("Failed to schedule shared webhook sync for {}: {}", normalizedUrl, e.getMessage(), e);
+ String error = RepoWebhookSyncStatus.describe(e);
+ for (Webhook webhook : markedInGroup) {
+ transactions.recordMigrationError(webhook.getId(), error);
+ }
+ failed += markedInGroup.size();
+ }
+
+ // Best-effort cleanup of legacy v1 remote hooks after v2 sync has been queued;
+ // failures keep remoteHookId intact so a later startup can retry cleanup without blocking v2.
+ for (Webhook webhook : markedInGroup) {
+ cleanupLegacyHookIfConfirmed(webhook);
+ }
+ }
+ }
+ }
+
+ if (!needsRetry.isEmpty()) {
+ log.info("Found {} migrated webhook(s) needing retry for syncError or legacy v1 hook cleanup",
+ needsRetry.size());
+ Map reposToResync = new LinkedHashMap<>();
+ for (Webhook webhook : needsRetry) {
+ Workspace workspace = webhook.getWorkspace();
+ Vcs vcs = workspace != null ? workspace.getVcs() : null;
+ String normalizedUrl = workspace != null ? RepoUrlNormalizer.normalize(workspace.getSource()) : null;
+ if (workspace == null || vcs == null || normalizedUrl == null) {
+ continue;
+ }
+ if (webhook.getSyncError() != null && !webhook.getSyncError().isBlank()) {
+ reposToResync.putIfAbsent(normalizedUrl,
+ workspace.getId() != null ? workspace.getId().toString() : null);
+ }
+ cleanupLegacyHookIfConfirmed(webhook);
+ }
+ for (Map.Entry entry : reposToResync.entrySet()) {
+ try {
+ repoWebhookSyncScheduler.scheduleSync(entry.getKey(), entry.getValue());
+ log.info("Re-scheduled shared v2 sync for {} after previous syncError", entry.getKey());
+ } catch (Exception e) {
+ log.error("Failed to re-schedule shared webhook sync for {}: {}",
+ entry.getKey(), e.getMessage(), e);
+ failed++;
+ }
+ }
+ }
+
+ MigrationSummary summary = new MigrationSummary(migrated, skipped, failed);
+ if (failed > 0) {
+ log.warn("Completed webhook v1->v2 startup migration with errors: migrated={}, skipped={}, failed={}",
+ summary.migrated(), summary.skipped(), summary.failed());
+ } else {
+ log.info("Completed webhook v1->v2 startup migration: migrated={}, skipped={}, failed={}",
+ summary.migrated(), summary.skipped(), summary.failed());
+ }
+ return summary;
+ }
+
+ private void cleanupLegacyHookIfConfirmed(Webhook webhook) {
+ String remoteHookId = webhook.getRemoteHookId();
+ if (remoteHookId == null || remoteHookId.isBlank()) {
+ return;
+ }
+ Workspace workspace = webhook.getWorkspace();
+ VcsType vcsType = workspace != null && workspace.getVcs() != null
+ ? workspace.getVcs().getVcsType()
+ : null;
+ if (workspace == null || vcsType == null) {
+ return;
+ }
+ try {
+ if (deleteLegacyV1Hook(workspace, vcsType, remoteHookId)) {
+ transactions.clearRemoteHookId(webhook.getId());
+ } else {
+ log.warn("Legacy v1 hook {} on workspace {} was not confirmed deleted; keeping remoteHookId for retry",
+ remoteHookId, workspace.getId());
+ }
+ } catch (Exception e) {
+ log.warn("Failed to delete legacy v1 hook {} on workspace {}; keeping remoteHookId for retry: {}",
+ remoteHookId, workspace.getId(), e.getMessage());
+ }
+ }
+
+ private boolean deleteLegacyV1Hook(Workspace workspace, VcsType vcsType, String remoteHookId) {
+ return switch (vcsType) {
+ case GITHUB -> gitHubWebhookService.deleteWebhook(workspace, remoteHookId);
+ case GITLAB -> gitLabWebhookService.deleteWebhook(workspace, remoteHookId);
+ case AZURE_DEVOPS, AZURE_SP_MI -> azDevOpsWebhookService.deleteWebhook(workspace, remoteHookId);
+ case BITBUCKET -> bitBucketWebhookService.deleteWebhook(workspace, remoteHookId);
+ default -> throw new IllegalArgumentException("Unsupported VCS type for webhook migration: " + vcsType);
+ };
+ }
+}
diff --git a/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationTransactions.java b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationTransactions.java
new file mode 100644
index 0000000000..f772c3568e
--- /dev/null
+++ b/api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationTransactions.java
@@ -0,0 +1,91 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.terrakube.api.repository.WebhookRepository;
+import io.terrakube.api.rs.vcs.VcsType;
+import io.terrakube.api.rs.webhook.Webhook;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Isolated transaction boundaries for {@link WebhookV1ToV2MigrationService} so outbound VCS API
+ * calls run outside of database transactions while each webhook's state transition commits
+ * independently before scheduling {@link RepoWebhookSyncJob}.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class WebhookV1ToV2MigrationTransactions {
+
+ private final WebhookRepository webhookRepository;
+
+ @Transactional(readOnly = true)
+ public List findUnmigratedV1Webhooks(Set types) {
+ return webhookRepository.findUnmigratedV1Webhooks(types);
+ }
+
+ @Transactional(readOnly = true)
+ public long countUnmigratedV1Webhooks(Set types) {
+ return webhookRepository.countUnmigratedV1Webhooks(types);
+ }
+
+ @Transactional(readOnly = true)
+ public List findMigratedWebhooksNeedingRetry(Set types) {
+ return webhookRepository.findMigratedWebhooksNeedingRetry(types);
+ }
+
+ /**
+ * Marks a single webhook as migrated to v2 in its own committed transaction so the
+ * downstream {@link RepoWebhookSyncJob} immediately observes {@code migratedV2 = true}.
+ * {@code remoteHookId} is intentionally preserved here and cleared only by
+ * {@link #clearRemoteHookId(UUID)} once remote v1 hook deletion is confirmed.
+ *
+ * @return {@code true} if the webhook was transitioned from v1 to v2, {@code false} if it
+ * was already migrated or no longer exists.
+ */
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public boolean markMigrated(UUID webhookId) {
+ Webhook webhook = webhookRepository.findById(webhookId).orElse(null);
+ if (webhook == null || webhook.isMigratedV2()) {
+ return false;
+ }
+ webhook.setMigratedV2(true);
+ webhook.setSyncError(null);
+ webhookRepository.save(webhook);
+ return true;
+ }
+
+ /**
+ * Clears {@code remoteHookId} in its own transaction only after remote v1 webhook deletion
+ * has been confirmed (2xx/204 or 404).
+ */
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public void clearRemoteHookId(UUID webhookId) {
+ Webhook webhook = webhookRepository.findById(webhookId).orElse(null);
+ if (webhook == null || webhook.getRemoteHookId() == null) {
+ return;
+ }
+ webhook.setRemoteHookId(null);
+ webhookRepository.save(webhook);
+ }
+
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public void recordMigrationError(UUID webhookId, String error) {
+ Webhook webhook = webhookRepository.findById(webhookId).orElse(null);
+ if (webhook == null) {
+ return;
+ }
+ String message = error == null || error.length() <= RepoWebhookSyncStatus.MAX_LENGTH
+ ? error
+ : error.substring(0, RepoWebhookSyncStatus.MAX_LENGTH);
+ webhook.setSyncError(message);
+ webhookRepository.save(webhook);
+ }
+}
diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookProperties.java b/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookProperties.java
index 375cc28c2b..2acb0e8a80 100644
--- a/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookProperties.java
+++ b/api/src/main/java/io/terrakube/api/plugin/vcs/WebhookProperties.java
@@ -29,8 +29,14 @@ public class WebhookProperties {
public static class V1 {
/**
* Whether legacy webhook v1 (/webhook/v1/{webhookId}) is disabled.
- * When true, /webhook/v1/{webhookId} returns 404 Not Found and webhook creation/updates enforce v2.
+ * Defaults to true; when true, /webhook/v1/{webhookId} returns 404 Not Found and webhook creation/updates enforce v2.
*/
- private boolean disabled = false;
+ private boolean disabled = true;
+
+ /**
+ * Whether the startup Quartz job that migrates remaining unmigrated v1 workspaces to v2 runs on API startup.
+ * Only takes effect when {@link #disabled} is true.
+ */
+ private boolean migrationOnStartup = true;
}
}
diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/azdevops/AzDevOpsWebhookService.java b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/azdevops/AzDevOpsWebhookService.java
index 41d33785ab..d6d402cadf 100644
--- a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/azdevops/AzDevOpsWebhookService.java
+++ b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/azdevops/AzDevOpsWebhookService.java
@@ -17,6 +17,7 @@
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
+import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriUtils;
@@ -370,14 +371,15 @@ public String createOrUpdateWebhook(Workspace workspace, Webhook webhook) {
return String.join(",", subscriptionIds);
}
- public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
+ public boolean deleteWebhook(Workspace workspace, String webhookRemoteId) {
AzureRepo repo = parseSource(workspace.getSource());
if (repo == null) {
log.warn("Unable to parse Azure DevOps repository from source {}, skipping deletion",
workspace.getSource());
- return;
+ return false;
}
+ boolean allDeleted = true;
for (String subscriptionId : webhookRemoteId.split(",")) {
subscriptionId = subscriptionId.trim();
if (subscriptionId.isEmpty()) {
@@ -385,14 +387,20 @@ public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
}
String apiUrl = String.format("%s/_apis/hooks/subscriptions/%s?api-version=%s",
repo.orgBaseUrl, subscriptionId, HOOKS_API_VERSION);
- ResponseEntity response = callAzureApi(workspace.getVcs(), "", apiUrl, HttpMethod.DELETE);
- if (response != null && response.getStatusCode().is2xxSuccessful()) {
- log.info("Azure DevOps subscription {} deleted successfully", subscriptionId);
- } else {
- log.warn("Failed to delete Azure DevOps subscription {}, message {}", subscriptionId,
- response != null ? response.getBody() : NO_RESPONSE);
+ try {
+ ResponseEntity response = callAzureApi(workspace.getVcs(), "", apiUrl, HttpMethod.DELETE);
+ if (response != null && response.getStatusCode().is2xxSuccessful()) {
+ log.info("Azure DevOps subscription {} deleted successfully", subscriptionId);
+ } else {
+ log.warn("Failed to delete Azure DevOps subscription {}, message {}", subscriptionId,
+ response != null ? response.getBody() : NO_RESPONSE);
+ allDeleted = false;
+ }
+ } catch (HttpClientErrorException.NotFound _) {
+ log.info("Azure DevOps subscription {} no longer exists", subscriptionId);
}
}
+ return allDeleted;
}
public void sendCommitStatus(Job job, JobStatus jobStatus, String runSummary) {
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 2848f2f193..f9665fe27b 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
@@ -523,7 +523,7 @@ public String createOrUpdateWebhook(Workspace workspace, Webhook webhook) {
return remoteHookId;
}
- public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
+ public boolean deleteWebhook(Workspace workspace, String webhookRemoteId) {
String apiUrl = webhookRemoteId;
String ownerAndRepo = String.join("/", extractOwnerAndRepo(workspace.getSource()));
@@ -531,18 +531,24 @@ public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
apiUrl = workspace.getVcs().getApiUrl() + "/repositories/" + ownerAndRepo + "/hooks/" + webhookRemoteId;
} else if (!VcsApiUrlValidator.isAllowedForVcs(workspace.getVcs(), apiUrl)) {
log.warn("Blocked Bitbucket webhook deletion to URL outside configured VCS API origin");
- return;
+ return false;
}
- ResponseEntity response = callBitBucketApi(workspace.getVcs().getAccessToken(), "", apiUrl,
- HttpMethod.DELETE);
- if (response.getStatusCode().value() == 204) {
+ ResponseEntity response;
+ try {
+ response = callBitBucketApi(workspace.getVcs().getAccessToken(), "", apiUrl, HttpMethod.DELETE);
+ } catch (HttpClientErrorException.NotFound _) {
+ log.info("Webhook {} on repository {} no longer exists on Bitbucket", webhookRemoteId, ownerAndRepo);
+ return true;
+ }
+ if (response != null && response.getStatusCode().is2xxSuccessful()) {
log.info("Webhook with remote hook id {} on repository {} deleted successfully", webhookRemoteId,
ownerAndRepo);
- } else {
- log.warn("Failed to delete webhook with remote hook id {} on repository {}, message {}", webhookRemoteId,
- ownerAndRepo, response.getBody());
+ return true;
}
+ log.warn("Failed to delete webhook with remote hook id {} on repository {}, message {}", webhookRemoteId,
+ ownerAndRepo, response != null ? response.getBody() : "no response");
+ return false;
}
/**
diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/github/GitHubWebhookService.java b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/github/GitHubWebhookService.java
index e0bcf993c8..46c6510ea3 100644
--- a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/github/GitHubWebhookService.java
+++ b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/github/GitHubWebhookService.java
@@ -493,7 +493,7 @@ public String createOrUpdateWebhook(Workspace workspace, Webhook webhook) {
}
- public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
+ public boolean deleteWebhook(Workspace workspace, String webhookRemoteId) {
String apiUrl = webhookRemoteId;
String ownerAndRepo[] = extractOwnerAndRepo(workspace.getSource());
@@ -504,21 +504,27 @@ public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
+ webhookRemoteId;
}
- ResponseEntity response = callGitHubApi(workspace.getVcs(), ownerAndRepo, "", apiUrl,
- HttpMethod.DELETE);
+ ResponseEntity response;
+ try {
+ response = callGitHubApi(workspace.getVcs(), ownerAndRepo, "", apiUrl, HttpMethod.DELETE);
+ } catch (HttpClientErrorException.NotFound _) {
+ log.info("Webhook {} on repository {} no longer exists on GitHub", webhookRemoteId, workspace.getSource());
+ return true;
+ }
if (response == null) {
log.error("Failed to delete webhook with remote hook id {} on repository {}/{}", webhookRemoteId,
ownerAndRepo[0], ownerAndRepo[1]);
- return;
+ return false;
}
- if (response.getStatusCode().value() == 204) {
+ if (response.getStatusCode().is2xxSuccessful()) {
log.info("Webhook with remote hook id {} on repository {} deleted successfully", webhookRemoteId,
workspace.getSource());
- } else {
- log.warn("Failed to delete webhook with remote hook id {} on repository {}, message {}", webhookRemoteId,
- workspace.getSource(), response.getBody());
+ return true;
}
+ log.warn("Failed to delete webhook with remote hook id {} on repository {}, message {}", webhookRemoteId,
+ workspace.getSource(), response.getBody());
+ return false;
}
public String postPrComment(Job job, String markdownBody) {
diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/gitlab/GitLabWebhookService.java b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/gitlab/GitLabWebhookService.java
index d9779c6619..15ddfab169 100644
--- a/api/src/main/java/io/terrakube/api/plugin/vcs/provider/gitlab/GitLabWebhookService.java
+++ b/api/src/main/java/io/terrakube/api/plugin/vcs/provider/gitlab/GitLabWebhookService.java
@@ -631,23 +631,33 @@ public String getGitlabProjectId(String ownerAndRepo, String accessToken, String
return projectId.get();
}
- public void deleteWebhook(Workspace workspace, String webhookRemoteId) {
+ public boolean deleteWebhook(Workspace workspace, String webhookRemoteId) {
try {
String ownerAndRepo = extractOwnerAndRepoGitlab(workspace.getSource());
String projectId = getGitlabProjectId(ownerAndRepo, workspace.getVcs().getAccessToken(), workspace.getVcs().getApiUrl());
String apiUrl = workspace.getVcs().getApiUrl() + "/projects/" + projectId + "/hooks/" + webhookRemoteId;
- ResponseEntity response = callGitlabApi(workspace.getVcs().getAccessToken(), "", apiUrl, HttpMethod.DELETE);
- if (response.getStatusCode().value() == 204) {
+ ResponseEntity response;
+ try {
+ response = callGitlabApi(workspace.getVcs().getAccessToken(), "", apiUrl, HttpMethod.DELETE);
+ } catch (HttpClientErrorException.NotFound _) {
+ log.info("Webhook {} on repository {} no longer exists on GitLab", webhookRemoteId, ownerAndRepo);
+ return true;
+ }
+ if (response != null && response.getStatusCode().is2xxSuccessful()) {
log.info("Webhook with remote hook id {} on repository {} deleted successfully", webhookRemoteId, ownerAndRepo);
- } else {
- log.warn("Failed to delete webhook with remote hook id {} on repository {}, message {}", webhookRemoteId, ownerAndRepo, response.getBody());
+ return true;
}
+ log.warn("Failed to delete webhook with remote hook id {} on repository {}, message {}",
+ webhookRemoteId, ownerAndRepo, response != null ? response.getBody() : "no response");
+ return false;
} catch (IOException e) {
log.error("Failed to delete webhook IOException with remote hook id {} on repository {}: {}", webhookRemoteId, workspace.getSource(), e.getMessage());
+ return false;
} catch (InterruptedException ex) {
log.error("Failed to delete webhook InterruptedException with remote hook id {} on repository {}: {}", webhookRemoteId, workspace.getSource(), ex.getMessage());
Thread.currentThread().interrupt();
+ return false;
}
}
diff --git a/api/src/main/java/io/terrakube/api/repository/WebhookRepository.java b/api/src/main/java/io/terrakube/api/repository/WebhookRepository.java
index 0923fa99b4..45545fd54a 100644
--- a/api/src/main/java/io/terrakube/api/repository/WebhookRepository.java
+++ b/api/src/main/java/io/terrakube/api/repository/WebhookRepository.java
@@ -1,6 +1,7 @@
package io.terrakube.api.repository;
import java.util.List;
+import java.util.Set;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -17,4 +18,26 @@ public interface WebhookRepository extends JpaRepository {
// annotated with @SQLRestriction("deleted = false"), so deleted workspaces are excluded.
@Query("SELECT wh FROM webhook wh JOIN FETCH wh.workspace w JOIN FETCH w.vcs v WHERE v.vcsType IN :types")
List findByWorkspaceVcsTypeIn(@Param("types") List types);
+
+ /**
+ * Returns all non-migrated v1 webhooks for workspaces backed by one of the given VCS types.
+ * Soft-deleted workspaces are excluded automatically by {@link Webhook}'s {@code @SQLRestriction}.
+ */
+ @Query("SELECT wh FROM webhook wh JOIN FETCH wh.workspace w JOIN FETCH w.vcs v "
+ + "WHERE wh.migratedV2 = false AND v.vcsType IN :types ORDER BY wh.id")
+ List findUnmigratedV1Webhooks(@Param("types") Set types);
+
+ @Query("SELECT COUNT(wh) FROM webhook wh JOIN wh.workspace w JOIN w.vcs v "
+ + "WHERE wh.migratedV2 = false AND v.vcsType IN :types")
+ long countUnmigratedV1Webhooks(@Param("types") Set types);
+
+ /**
+ * Returns already-migrated v2 webhooks that still need startup follow-up: either their shared
+ * repository webhook sync failed ({@code syncError != null}) or their legacy v1 remote hook was
+ * not confirmed deleted yet ({@code remoteHookId != null}).
+ */
+ @Query("SELECT wh FROM webhook wh JOIN FETCH wh.workspace w JOIN FETCH w.vcs v "
+ + "WHERE wh.migratedV2 = true AND (wh.syncError IS NOT NULL OR (wh.remoteHookId IS NOT NULL AND wh.remoteHookId <> '')) "
+ + "AND v.vcsType IN :types ORDER BY wh.id")
+ List findMigratedWebhooksNeedingRetry(@Param("types") Set types);
}
diff --git a/api/src/main/resources/application.properties b/api/src/main/resources/application.properties
index 76434d0049..dc93b9daf4 100644
--- a/api/src/main/resources/application.properties
+++ b/api/src/main/resources/application.properties
@@ -174,10 +174,12 @@ io.terrakube.webhook.dispatch.http.connectionRequestTimeoutSeconds=${WebhookDisp
# whose configured branch matches the PR's target (base) branch. Trigger branch patterns
# continue to match against the PR source (head) branch. Defaults to false for backward compatibility.
io.terrakube.webhook.pr-base-branch-filter=${WebhookPrBaseBranchFilter:false}
-# When true, /webhook/v1/{webhookId} returns 404 and new webhooks for supported VCS providers
-# are created as shared v2 webhooks. Existing v1 workspaces must be migrated first (automated on
-# startup once the full migration stack is merged).
-io.terrakube.webhook.v1.disabled=${WebhookV1Disabled:false}
+# When true (default), the legacy per-workspace /webhook/v1/{webhookId} endpoint returns 404,
+# new webhooks for supported VCS providers are created as shared v2 webhooks, and a startup
+# Quartz job migrates remaining unmigrated v1 workspaces to v2.
+# Set WebhookV1Disabled=false to opt out (keeps /webhook/v1 active and skips startup migration).
+io.terrakube.webhook.v1.disabled=${WebhookV1Disabled:true}
+io.terrakube.webhook.v1.migration-on-startup=${WebhookV1MigrationOnStartup:true}
##############
#EXECUTOR URL#
diff --git a/api/src/test/java/io/terrakube/api/WebhookTests.java b/api/src/test/java/io/terrakube/api/WebhookTests.java
index ee621fabef..7ebabd4c1b 100644
--- a/api/src/test/java/io/terrakube/api/WebhookTests.java
+++ b/api/src/test/java/io/terrakube/api/WebhookTests.java
@@ -17,6 +17,7 @@
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
+import org.springframework.test.context.TestPropertySource;
import java.util.ArrayList;
import java.util.List;
@@ -29,6 +30,7 @@
import static io.restassured.RestAssured.given;
import static org.mockito.Mockito.when;
+@TestPropertySource(properties = "io.terrakube.webhook.v1.disabled=false")
class WebhookTests extends ServerApplicationTests {
private static final String ORGANIZATION_ID = "d9b58bd3-f3fc-4056-a026-1163297e80a8";
diff --git a/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java b/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java
index a08db5c7e9..ec3caf219f 100644
--- a/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java
+++ b/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java
@@ -2,13 +2,11 @@
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
-import org.springframework.test.context.TestPropertySource;
import java.util.UUID;
import static io.restassured.RestAssured.given;
-@TestPropertySource(properties = "io.terrakube.webhook.v1.disabled=true")
class WebhookV1DisabledIntegrationTest extends ServerApplicationTests {
@Test
diff --git a/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java b/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java
index c8124f4c0e..37ef09e3a1 100644
--- a/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java
+++ b/api/src/test/java/io/terrakube/api/WebhookV1MigratedSecurityIntegrationTest.java
@@ -14,6 +14,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
+import org.springframework.test.context.TestPropertySource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -32,6 +33,7 @@
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
+@TestPropertySource(properties = "io.terrakube.webhook.v1.disabled=false")
class WebhookV1MigratedSecurityIntegrationTest extends ServerApplicationTests {
private static final String ORGANIZATION_ID = "d9b58bd3-f3fc-4056-a026-1163297e80a8";
diff --git a/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationJobTest.java b/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationJobTest.java
new file mode 100644
index 0000000000..9724202187
--- /dev/null
+++ b/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationJobTest.java
@@ -0,0 +1,29 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.junit.jupiter.api.Test;
+import org.quartz.DisallowConcurrentExecution;
+import org.quartz.JobExecutionContext;
+
+class WebhookV1ToV2MigrationJobTest {
+
+ @Test
+ void jobDisallowsConcurrentExecution() {
+ assertTrue(WebhookV1ToV2MigrationJob.class.isAnnotationPresent(DisallowConcurrentExecution.class));
+ }
+
+ @Test
+ void executeDelegatesToMigrationService() throws Exception {
+ WebhookV1ToV2MigrationService service = mock(WebhookV1ToV2MigrationService.class);
+ when(service.migrateAllUnmigrated()).thenReturn(new WebhookV1ToV2MigrationService.MigrationSummary(2, 0, 0));
+
+ WebhookV1ToV2MigrationJob job = new WebhookV1ToV2MigrationJob(service);
+ job.execute(mock(JobExecutionContext.class));
+
+ verify(service).migrateAllUnmigrated();
+ }
+}
diff --git a/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationSchedulerTest.java b/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationSchedulerTest.java
new file mode 100644
index 0000000000..8a8aa433bd
--- /dev/null
+++ b/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationSchedulerTest.java
@@ -0,0 +1,83 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.quartz.JobDetail;
+import org.quartz.JobPersistenceException;
+import org.quartz.ObjectAlreadyExistsException;
+import org.quartz.Scheduler;
+import org.quartz.Trigger;
+
+import io.terrakube.api.plugin.vcs.WebhookProperties;
+
+class WebhookV1ToV2MigrationSchedulerTest {
+
+ @Test
+ void schedulesOneShotMigrationJobWhenV1DisabledAndStartupEnabled() throws Exception {
+ Scheduler scheduler = mock(Scheduler.class);
+ WebhookV1ToV2MigrationTransactions transactions = mock(WebhookV1ToV2MigrationTransactions.class);
+ WebhookProperties properties = new WebhookProperties();
+ properties.getV1().setDisabled(true);
+ properties.getV1().setMigrationOnStartup(true);
+
+ WebhookV1ToV2MigrationScheduler migrationScheduler =
+ new WebhookV1ToV2MigrationScheduler(scheduler, properties, transactions);
+ migrationScheduler.scheduleMigrationOnStartup();
+
+ ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(JobDetail.class);
+ ArgumentCaptor triggerCaptor = ArgumentCaptor.forClass(Trigger.class);
+ verify(scheduler).scheduleJob(jobCaptor.capture(), triggerCaptor.capture());
+
+ assertEquals(WebhookV1ToV2MigrationScheduler.JOB_KEY, jobCaptor.getValue().getKey());
+ assertEquals(WebhookV1ToV2MigrationJob.class, jobCaptor.getValue().getJobClass());
+ assertEquals(WebhookV1ToV2MigrationScheduler.JOB_KEY.getName(), triggerCaptor.getValue().getKey().getName());
+ }
+
+ @Test
+ void skipsSchedulingWhenV1EnabledOrMigrationOnStartupDisabled() {
+ Scheduler scheduler = mock(Scheduler.class);
+ WebhookV1ToV2MigrationTransactions transactions = mock(WebhookV1ToV2MigrationTransactions.class);
+ when(transactions.countUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES)).thenReturn(3L);
+
+ WebhookProperties v1Enabled = new WebhookProperties();
+ v1Enabled.getV1().setDisabled(false);
+ v1Enabled.getV1().setMigrationOnStartup(true);
+ new WebhookV1ToV2MigrationScheduler(scheduler, v1Enabled, transactions).scheduleMigrationOnStartup();
+
+ WebhookProperties migrationDisabled = new WebhookProperties();
+ migrationDisabled.getV1().setDisabled(true);
+ migrationDisabled.getV1().setMigrationOnStartup(false);
+ new WebhookV1ToV2MigrationScheduler(scheduler, migrationDisabled, transactions).scheduleMigrationOnStartup();
+
+ verifyNoInteractions(scheduler);
+ verify(transactions).countUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES);
+ }
+
+ @Test
+ void ignoresDuplicateJobExceptionsAcrossReplicas() throws Exception {
+ Scheduler scheduler = mock(Scheduler.class);
+ WebhookV1ToV2MigrationTransactions transactions = mock(WebhookV1ToV2MigrationTransactions.class);
+ WebhookProperties properties = new WebhookProperties();
+ properties.getV1().setDisabled(true);
+ properties.getV1().setMigrationOnStartup(true);
+ WebhookV1ToV2MigrationScheduler migrationScheduler =
+ new WebhookV1ToV2MigrationScheduler(scheduler, properties, transactions);
+
+ doThrow(new ObjectAlreadyExistsException("already exists"))
+ .when(scheduler).scheduleJob(any(JobDetail.class), any(Trigger.class));
+ assertDoesNotThrow(migrationScheduler::scheduleMigrationOnStartup);
+
+ doThrow(new JobPersistenceException("unique constraint"))
+ .when(scheduler).scheduleJob(any(JobDetail.class), any(Trigger.class));
+ assertDoesNotThrow(migrationScheduler::scheduleMigrationOnStartup);
+ }
+}
diff --git a/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationServiceTest.java b/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationServiceTest.java
new file mode 100644
index 0000000000..aaed786890
--- /dev/null
+++ b/api/src/test/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationServiceTest.java
@@ -0,0 +1,181 @@
+package io.terrakube.api.plugin.scheduler.webhook;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.UUID;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.HttpClientErrorException;
+
+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;
+import io.terrakube.api.rs.vcs.VcsType;
+import io.terrakube.api.rs.webhook.Webhook;
+import io.terrakube.api.rs.workspace.Workspace;
+
+class WebhookV1ToV2MigrationServiceTest {
+
+ private WebhookV1ToV2MigrationTransactions transactions;
+ private GitHubWebhookService gitHubWebhookService;
+ private GitLabWebhookService gitLabWebhookService;
+ private AzDevOpsWebhookService azDevOpsWebhookService;
+ private BitBucketWebhookService bitBucketWebhookService;
+ private RepoWebhookSyncScheduler repoWebhookSyncScheduler;
+ private WebhookV1ToV2MigrationService service;
+
+ @BeforeEach
+ void setUp() {
+ transactions = mock(WebhookV1ToV2MigrationTransactions.class);
+ gitHubWebhookService = mock(GitHubWebhookService.class);
+ gitLabWebhookService = mock(GitLabWebhookService.class);
+ azDevOpsWebhookService = mock(AzDevOpsWebhookService.class);
+ bitBucketWebhookService = mock(BitBucketWebhookService.class);
+ repoWebhookSyncScheduler = mock(RepoWebhookSyncScheduler.class);
+ service = new WebhookV1ToV2MigrationService(
+ transactions,
+ gitHubWebhookService,
+ gitLabWebhookService,
+ azDevOpsWebhookService,
+ bitBucketWebhookService,
+ repoWebhookSyncScheduler);
+ when(transactions.findMigratedWebhooksNeedingRetry(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES))
+ .thenReturn(List.of());
+ }
+
+ @Test
+ void migrateAllUnmigrated_returnsZeroSummaryWhenAlreadyMigrated() {
+ when(transactions.findUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES))
+ .thenReturn(List.of());
+
+ WebhookV1ToV2MigrationService.MigrationSummary summary = service.migrateAllUnmigrated();
+
+ assertEquals(new WebhookV1ToV2MigrationService.MigrationSummary(0, 0, 0), summary);
+ verifyNoInteractions(gitHubWebhookService, gitLabWebhookService, azDevOpsWebhookService,
+ bitBucketWebhookService, repoWebhookSyncScheduler);
+ verify(transactions, never()).markMigrated(any());
+ }
+
+ @Test
+ void migrateAllUnmigrated_groupsByRepoMarksAllFirstAndConfirmsV1Deletes() {
+ Webhook gh1 = webhookFor(VcsType.GITHUB, "https://github.com/acme/infra.git", "gh-1");
+ Webhook gh2 = webhookFor(VcsType.GITHUB, "https://github.com/acme/infra", "gh-2");
+ Webhook gl = webhookFor(VcsType.GITLAB, "https://gitlab.com/acme/infra.git", "gl-1");
+ Webhook az = webhookFor(VcsType.AZURE_DEVOPS, "https://dev.azure.com/org/proj/_git/repo", "az-1");
+ Webhook bb = webhookFor(VcsType.BITBUCKET, "https://bitbucket.org/acme/infra.git", "{bb-1}");
+
+ when(transactions.findUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES))
+ .thenReturn(List.of(gh1, gh2, gl, az, bb));
+ when(transactions.markMigrated(any())).thenReturn(true);
+ when(gitHubWebhookService.deleteWebhook(any(), any())).thenReturn(true);
+ when(gitLabWebhookService.deleteWebhook(any(), any())).thenReturn(true);
+ when(azDevOpsWebhookService.deleteWebhook(any(), any())).thenReturn(true);
+ when(bitBucketWebhookService.deleteWebhook(any(), any())).thenReturn(true);
+
+ WebhookV1ToV2MigrationService.MigrationSummary summary = service.migrateAllUnmigrated();
+
+ assertEquals(new WebhookV1ToV2MigrationService.MigrationSummary(5, 0, 0), summary);
+
+ // Both GitHub workspaces sharing https://github.com/acme/infra are marked before a single sync is scheduled,
+ // and remoteHookId is cleared only after confirmed v1 deletion.
+ InOrder ghOrder = inOrder(transactions, repoWebhookSyncScheduler, gitHubWebhookService);
+ ghOrder.verify(transactions).markMigrated(gh1.getId());
+ ghOrder.verify(transactions).markMigrated(gh2.getId());
+ ghOrder.verify(repoWebhookSyncScheduler).scheduleSync(
+ "https://github.com/acme/infra", gh1.getWorkspace().getId().toString());
+ ghOrder.verify(gitHubWebhookService).deleteWebhook(gh1.getWorkspace(), "gh-1");
+ ghOrder.verify(transactions).clearRemoteHookId(gh1.getId());
+ ghOrder.verify(gitHubWebhookService).deleteWebhook(gh2.getWorkspace(), "gh-2");
+ ghOrder.verify(transactions).clearRemoteHookId(gh2.getId());
+
+ verify(repoWebhookSyncScheduler, times(1)).scheduleSync(
+ "https://github.com/acme/infra", gh1.getWorkspace().getId().toString());
+ verify(transactions).clearRemoteHookId(gl.getId());
+ verify(transactions).clearRemoteHookId(az.getId());
+ verify(transactions).clearRemoteHookId(bb.getId());
+ }
+
+ @Test
+ void migrateAllUnmigrated_keepsRemoteHookIdWhenV1DeleteFailsWithoutBlockingV2() {
+ Webhook unconfirmedFalse = webhookFor(VcsType.GITHUB, "https://github.com/acme/repo-a", "gh-fail");
+ Webhook forbiddenDelete = webhookFor(VcsType.GITLAB, "https://gitlab.com/acme/repo-b", "gl-denied");
+ Webhook missingSource = webhookFor(VcsType.GITHUB, null, "no-src");
+
+ when(transactions.findUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES))
+ .thenReturn(List.of(unconfirmedFalse, forbiddenDelete, missingSource));
+ when(transactions.markMigrated(unconfirmedFalse.getId())).thenReturn(true);
+ when(transactions.markMigrated(forbiddenDelete.getId())).thenReturn(true);
+
+ when(gitHubWebhookService.deleteWebhook(unconfirmedFalse.getWorkspace(), "gh-fail")).thenReturn(false);
+ when(gitLabWebhookService.deleteWebhook(forbiddenDelete.getWorkspace(), "gl-denied"))
+ .thenThrow(HttpClientErrorException.create(HttpStatus.FORBIDDEN, "Forbidden", HttpHeaders.EMPTY,
+ new byte[0], StandardCharsets.UTF_8));
+
+ WebhookV1ToV2MigrationService.MigrationSummary summary = service.migrateAllUnmigrated();
+
+ assertEquals(new WebhookV1ToV2MigrationService.MigrationSummary(2, 1, 0), summary);
+ verify(repoWebhookSyncScheduler).scheduleSync(
+ "https://github.com/acme/repo-a", unconfirmedFalse.getWorkspace().getId().toString());
+ verify(repoWebhookSyncScheduler).scheduleSync(
+ "https://gitlab.com/acme/repo-b", forbiddenDelete.getWorkspace().getId().toString());
+ verify(transactions, never()).clearRemoteHookId(unconfirmedFalse.getId());
+ verify(transactions, never()).clearRemoteHookId(forbiddenDelete.getId());
+ }
+
+ @Test
+ void migrateAllUnmigrated_retriesPreviouslyMigratedRowsWithSyncErrorOrLeftoverRemoteHookId() {
+ Webhook syncErrorRow = webhookFor(VcsType.GITHUB, "https://github.com/acme/retry-sync.git", null);
+ syncErrorRow.setMigratedV2(true);
+ syncErrorRow.setSyncError("The VCS provider could not be reached");
+
+ Webhook leftoverHookRow = webhookFor(VcsType.BITBUCKET, "https://bitbucket.org/acme/retry-clean", "{bb-left}");
+ leftoverHookRow.setMigratedV2(true);
+
+ when(transactions.findUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES))
+ .thenReturn(List.of());
+ when(transactions.findMigratedWebhooksNeedingRetry(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES))
+ .thenReturn(List.of(syncErrorRow, leftoverHookRow));
+ when(bitBucketWebhookService.deleteWebhook(leftoverHookRow.getWorkspace(), "{bb-left}")).thenReturn(true);
+
+ WebhookV1ToV2MigrationService.MigrationSummary summary = service.migrateAllUnmigrated();
+
+ assertEquals(new WebhookV1ToV2MigrationService.MigrationSummary(0, 0, 0), summary);
+ verify(repoWebhookSyncScheduler).scheduleSync(
+ "https://github.com/acme/retry-sync", syncErrorRow.getWorkspace().getId().toString());
+ verify(bitBucketWebhookService).deleteWebhook(leftoverHookRow.getWorkspace(), "{bb-left}");
+ verify(transactions).clearRemoteHookId(leftoverHookRow.getId());
+ }
+
+ private Webhook webhookFor(VcsType vcsType, String source, String remoteHookId) {
+ Vcs vcs = new Vcs();
+ vcs.setVcsType(vcsType);
+
+ Workspace workspace = new Workspace();
+ workspace.setId(UUID.randomUUID());
+ workspace.setSource(source);
+ workspace.setVcs(vcs);
+
+ Webhook webhook = new Webhook();
+ webhook.setId(UUID.randomUUID());
+ webhook.setWorkspace(workspace);
+ webhook.setRemoteHookId(remoteHookId);
+ webhook.setMigratedV2(false);
+ return webhook;
+ }
+}
diff --git a/api/src/test/java/io/terrakube/api/plugin/vcs/controller/WebHookControllerTest.java b/api/src/test/java/io/terrakube/api/plugin/vcs/controller/WebHookControllerTest.java
index c7387abdb9..cb2a61cd73 100644
--- a/api/src/test/java/io/terrakube/api/plugin/vcs/controller/WebHookControllerTest.java
+++ b/api/src/test/java/io/terrakube/api/plugin/vcs/controller/WebHookControllerTest.java
@@ -14,6 +14,7 @@
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -40,7 +41,7 @@ void setUp() {
@Test
void processWebhookReturns404WhenV1DisabledForValidAndInvalidIds() {
- webhookProperties.getV1().setDisabled(true);
+ assertTrue(webhookProperties.getV1().isDisabled());
ResponseEntity validResponse = controller.processWebhook(
UUID.randomUUID().toString(), Map.of("ref", "refs/heads/main"), Map.of());
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 586a67a7ec..e1f7f548d9 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
@@ -67,6 +67,13 @@ class WebhookManageHookTest {
@BeforeEach
void setUp() {
+ webhookProperties.getV1().setDisabled(false);
+ }
+
+ @Test
+ void webhookPropertiesDefaultsV1DisabledToTrue() {
+ assertTrue(new WebhookProperties().getV1().isDisabled());
+ assertTrue(new WebhookProperties().getV1().isMigrationOnStartup());
}
@Test
diff --git a/api/src/test/resources/application-test.properties b/api/src/test/resources/application-test.properties
index b04e2a30ff..6b339126e9 100644
--- a/api/src/test/resources/application-test.properties
+++ b/api/src/test/resources/application-test.properties
@@ -116,3 +116,6 @@ io.terrakube.api.module.refresh.poller-enabled=false
# last job status is active but has no active run, which is exactly the fixture of several tests, so it rewrote their
# workspaces while they ran. The sweep has its own unit and integration tests.
io.terrakube.api.scheduler.reconciliation.sweep-enabled=false
+
+# Tests drive webhook v1->v2 migration explicitly; avoid racing unrelated H2 fixtures on context start.
+io.terrakube.webhook.v1.migration-on-startup=false
diff --git a/ui/src/domain/Workspaces/Settings/Webhook.tsx b/ui/src/domain/Workspaces/Settings/Webhook.tsx
index abf61e46c7..b25db8131e 100644
--- a/ui/src/domain/Workspaces/Settings/Webhook.tsx
+++ b/ui/src/domain/Workspaces/Settings/Webhook.tsx
@@ -377,7 +377,7 @@ export const WorkspaceWebhook = ({
disabled={!manageWorkspace}
/>
- {webhookEnabled && webhookId && migratedV2 && syncError && (
+ {webhookEnabled && webhookId && syncError && (
{
expect(screen.queryByRole("button", { name: /Migrate to shared webhook/i })).not.toBeInTheDocument();
});
- it("says why the shared repository webhook could not be synced", async () => {
- mockWebhook({ migratedV2: true, remoteHookId: null, syncError: "The VCS connection does not have permission." });
+ it.each([
+ [{ migratedV2: true, remoteHookId: null, syncError: "The VCS connection does not have permission." }],
+ [{ migratedV2: false, remoteHookId: "1", syncError: "Migration failed" }],
+ ])("says why the repository webhook could not be synced (%p)", async (attributes) => {
+ mockWebhook(attributes);
renderWebhook();
expect(await screen.findByText("The repository webhook is not working")).toBeInTheDocument();
- expect(screen.getByText(/The VCS connection does not have permission\./)).toBeInTheDocument();
+ expect(screen.getByText(new RegExp(String(attributes.syncError)))).toBeInTheDocument();
});
it.each([
[{ migratedV2: true, remoteHookId: null, syncError: null }],
- [{ migratedV2: false, remoteHookId: "1", syncError: "old" }],
- ])("shows no sync problem when the shared webhook works or the webhook is not shared (%p)", async (attributes) => {
+ [{ migratedV2: false, remoteHookId: "1", syncError: null }],
+ ])("shows no sync problem when syncError is absent (%p)", async (attributes) => {
mockWebhook(attributes);
renderWebhook();