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 04b01c85f5..375cc28c2b 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 @@ -21,4 +21,16 @@ public class WebhookProperties { * Defaults to false for backward compatibility. */ private boolean prBaseBranchFilter = false; + + private V1 v1 = new V1(); + + @Getter + @Setter + 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. + */ + private boolean disabled = false; + } } diff --git a/api/src/main/java/io/terrakube/api/plugin/vcs/controller/WebHookController.java b/api/src/main/java/io/terrakube/api/plugin/vcs/controller/WebHookController.java index ec077a419d..1a5f6536bd 100644 --- a/api/src/main/java/io/terrakube/api/plugin/vcs/controller/WebHookController.java +++ b/api/src/main/java/io/terrakube/api/plugin/vcs/controller/WebHookController.java @@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.RestController; import io.terrakube.api.plugin.vcs.RepoWebhookDispatchService; import io.terrakube.api.plugin.vcs.RepoWebhookService; +import io.terrakube.api.plugin.vcs.WebhookProperties; import io.terrakube.api.plugin.vcs.WebhookService; import com.fasterxml.jackson.databind.ObjectMapper; @@ -39,8 +40,15 @@ public class WebHookController { @Autowired ObjectMapper objectMapper; + @Autowired + WebhookProperties webhookProperties; + @PostMapping("/webhook/v1/{webhookId}") public ResponseEntity processWebhook(@PathVariable String webhookId,@RequestBody Map payload,@RequestHeader Map headers) { + if (webhookProperties != null && webhookProperties.getV1().isDisabled()) { + log.warn("Webhook v1 is disabled, returning 404 for webhook {}", webhookId); + return ResponseEntity.notFound().build(); + } if (!UUID_PATTERN.matcher(webhookId).matches()) { return ResponseEntity.status(401).build(); } 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 f29abdb4d4..412d9deb41 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 @@ -7,6 +7,7 @@ import org.springframework.web.client.HttpClientErrorException; import io.terrakube.api.plugin.scheduler.webhook.RepoWebhookSyncScheduler; import io.terrakube.api.plugin.vcs.RepoUrlNormalizer; +import io.terrakube.api.plugin.vcs.WebhookProperties; 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; @@ -44,6 +45,9 @@ public class WebhookManageHook implements LifeCycleHook { @Autowired RepoWebhookSyncScheduler repoWebhookSyncScheduler; + @Autowired + WebhookProperties webhookProperties; + @Override public void execute(Operation operation, TransactionPhase phase, Webhook elideEntity, RequestScope requestScope, Optional changes) { @@ -53,6 +57,12 @@ public void execute(Operation operation, TransactionPhase phase, Webhook elideEn switch (phase) { case PRECOMMIT: try { + if (operation == Operation.CREATE && isWebhookV1Disabled() + && isSharedWebhookProvider(elideEntity) && !elideEntity.isMigratedV2()) { + log.info("Webhook v1 is disabled; forcing migratedV2=true for new webhook on workspace {}", + elideEntity.getWorkspace().getId()); + elideEntity.setMigratedV2(true); + } if (isMigratedV2Shared(elideEntity)) { // Delete the old per-workspace hook, if any — this is // workspace-specific cleanup, not the shared-repo setup @@ -64,6 +74,8 @@ public void execute(Operation operation, TransactionPhase phase, Webhook elideEn } else { webhookService.createOrUpdateWorkspaceWebhook(elideEntity); } + } catch (WebhookManagementException e) { + throw e; } catch (HttpClientErrorException e) { throw new WebhookManagementException(HttpStatus.SC_FAILED_DEPENDENCY, buildPermissionErrorMessage(elideEntity, e)); @@ -123,6 +135,10 @@ public void execute(Operation operation, TransactionPhase phase, Webhook elideEn } } + private boolean isWebhookV1Disabled() { + return webhookProperties != null && webhookProperties.getV1().isDisabled(); + } + private boolean isMigratedV2Shared(Webhook elideEntity) { return elideEntity.isMigratedV2() && isSharedWebhookProvider(elideEntity); } diff --git a/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHook.java b/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHook.java new file mode 100644 index 0000000000..32dc1f59be --- /dev/null +++ b/api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHook.java @@ -0,0 +1,57 @@ +package io.terrakube.api.rs.hooks.webhook; + +import java.util.Optional; + +import org.apache.hc.core5.http.HttpStatus; +import org.springframework.beans.factory.annotation.Autowired; + +import com.yahoo.elide.annotation.LifeCycleHookBinding.Operation; +import com.yahoo.elide.annotation.LifeCycleHookBinding.TransactionPhase; +import com.yahoo.elide.core.lifecycle.LifeCycleHook; +import com.yahoo.elide.core.security.ChangeSpec; +import com.yahoo.elide.core.security.RequestScope; + +import io.terrakube.api.plugin.vcs.WebhookProperties; +import io.terrakube.api.rs.vcs.VcsType; +import io.terrakube.api.rs.webhook.Webhook; + +/** + * Rejects attempts to revert an already-migrated v2 webhook back to v1 ({@code migratedV2} + * transitioning from {@code true} to {@code false}) when {@code io.terrakube.webhook.v1.disabled} + * is enabled, while allowing unrelated updates (such as trigger edits) on untouched v1 webhooks. + */ +public class WebhookV1RevertGuardHook implements LifeCycleHook { + + @Autowired + WebhookProperties webhookProperties; + + @Override + public void execute(Operation operation, TransactionPhase phase, Webhook elideEntity, RequestScope requestScope, + Optional changes) { + if (operation != Operation.UPDATE || phase != TransactionPhase.PRECOMMIT) { + return; + } + if (webhookProperties == null || !webhookProperties.getV1().isDisabled()) { + return; + } + boolean revertingToV1 = changes + .filter(change -> "migratedV2".equals(change.getFieldName())) + .map(change -> Boolean.TRUE.equals(change.getOriginal()) && Boolean.FALSE.equals(change.getModified())) + .orElse(false); + if (revertingToV1 && isSharedWebhookProvider(elideEntity)) { + throw new WebhookManagementException(HttpStatus.SC_BAD_REQUEST, + "Webhook v1 is disabled; switching to webhook v1 is not allowed"); + } + } + + private boolean isSharedWebhookProvider(Webhook webhook) { + VcsType vcsType = webhook.getWorkspace() != null && webhook.getWorkspace().getVcs() != null + ? webhook.getWorkspace().getVcs().getVcsType() + : null; + 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/webhook/Webhook.java b/api/src/main/java/io/terrakube/api/rs/webhook/Webhook.java index 16b021a3ba..84769f89b2 100644 --- a/api/src/main/java/io/terrakube/api/rs/webhook/Webhook.java +++ b/api/src/main/java/io/terrakube/api/rs/webhook/Webhook.java @@ -8,6 +8,7 @@ import org.hibernate.annotations.SQLRestriction; import io.terrakube.api.plugin.security.audit.GenericAuditFields; import io.terrakube.api.rs.hooks.webhook.WebhookManageHook; +import io.terrakube.api.rs.hooks.webhook.WebhookV1RevertGuardHook; import io.terrakube.api.rs.workspace.Workspace; import com.yahoo.elide.annotation.CreatePermission; @@ -56,6 +57,7 @@ public class Webhook extends GenericAuditFields { @OneToOne(fetch = FetchType.LAZY, optional = false) private Workspace workspace; + @LifeCycleHookBinding(operation = LifeCycleHookBinding.Operation.UPDATE, phase = LifeCycleHookBinding.TransactionPhase.PRECOMMIT, hook = WebhookV1RevertGuardHook.class) @Column(name = "migrated_v2") private boolean migratedV2 = false; diff --git a/api/src/main/resources/application.properties b/api/src/main/resources/application.properties index a6a24a338e..76434d0049 100644 --- a/api/src/main/resources/application.properties +++ b/api/src/main/resources/application.properties @@ -174,6 +174,10 @@ 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} ############## #EXECUTOR URL# diff --git a/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java b/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java new file mode 100644 index 0000000000..a08db5c7e9 --- /dev/null +++ b/api/src/test/java/io/terrakube/api/WebhookV1DisabledIntegrationTest.java @@ -0,0 +1,35 @@ +package io.terrakube.api; + +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 + void webhookV1Returns404WhenDisabledForValidUuid() { + given() + .contentType("application/json") + .body("{}") + .when() + .post("/webhook/v1/" + UUID.randomUUID()) + .then() + .statusCode(HttpStatus.NOT_FOUND.value()); + } + + @Test + void webhookV1Returns404WhenDisabledForInvalidUuid() { + given() + .contentType("application/json") + .body("{}") + .when() + .post("/webhook/v1/not-a-uuid") + .then() + .statusCode(HttpStatus.NOT_FOUND.value()); + } +} 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 new file mode 100644 index 0000000000..c7387abdb9 --- /dev/null +++ b/api/src/test/java/io/terrakube/api/plugin/vcs/controller/WebHookControllerTest.java @@ -0,0 +1,68 @@ +package io.terrakube.api.plugin.vcs.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.terrakube.api.plugin.vcs.RepoWebhookDispatchService; +import io.terrakube.api.plugin.vcs.RepoWebhookService; +import io.terrakube.api.plugin.vcs.WebhookProperties; +import io.terrakube.api.plugin.vcs.WebhookService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +class WebHookControllerTest { + + private WebhookService webhookService; + private WebhookProperties webhookProperties; + private WebHookController controller; + + @BeforeEach + void setUp() { + webhookService = mock(WebhookService.class); + webhookProperties = new WebhookProperties(); + controller = new WebHookController(); + controller.webhookService = webhookService; + controller.repoWebhookService = mock(RepoWebhookService.class); + controller.repoWebhookDispatchService = mock(RepoWebhookDispatchService.class); + controller.objectMapper = new ObjectMapper(); + controller.webhookProperties = webhookProperties; + } + + @Test + void processWebhookReturns404WhenV1DisabledForValidAndInvalidIds() { + webhookProperties.getV1().setDisabled(true); + + ResponseEntity validResponse = controller.processWebhook( + UUID.randomUUID().toString(), Map.of("ref", "refs/heads/main"), Map.of()); + ResponseEntity invalidResponse = controller.processWebhook( + "not-a-uuid", Map.of(), Map.of()); + + assertEquals(HttpStatus.NOT_FOUND, validResponse.getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, invalidResponse.getStatusCode()); + verifyNoInteractions(webhookService); + } + + @Test + void processWebhookProcessesRequestWhenV1Enabled() { + webhookProperties.getV1().setDisabled(false); + String webhookId = UUID.randomUUID().toString(); + + ResponseEntity invalidResponse = controller.processWebhook("not-a-uuid", Map.of(), Map.of()); + ResponseEntity validResponse = controller.processWebhook( + webhookId, Map.of("key", "value"), Map.of("X-Test", "1")); + + assertEquals(HttpStatus.UNAUTHORIZED, invalidResponse.getStatusCode()); + assertEquals(HttpStatus.OK, validResponse.getStatusCode()); + verify(webhookService).processWebhook(eq(webhookId), any(), eq(Map.of("X-Test", "1"))); + } +} 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 a7956de96b..586a67a7ec 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 @@ -1,6 +1,7 @@ package io.terrakube.api.rs.hooks.webhook; import io.terrakube.api.plugin.scheduler.webhook.RepoWebhookSyncScheduler; +import io.terrakube.api.plugin.vcs.WebhookProperties; 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; @@ -19,6 +20,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; @@ -54,6 +56,9 @@ class WebhookManageHookTest { @Mock RepoWebhookSyncScheduler repoWebhookSyncScheduler; + @Spy + WebhookProperties webhookProperties = new WebhookProperties(); + @InjectMocks WebhookManageHook subject; @@ -340,4 +345,45 @@ void execute_forbiddenWithPrWorkflow_reportsPullRequestPermissionToo() { assertEquals(424, exception.getStatus()); assertTrue(exception.getMessage().contains("'Pull requests: write' permission")); } + + @Test + void execute_create_whenV1Disabled_forcesMigratedV2True() { + webhookProperties.getV1().setDisabled(true); + + Workspace workspace = new Workspace(); + workspace.setId(java.util.UUID.fromString("66666666-6666-6666-6666-666666666666")); + workspace.setSource("https://github.com/owner/repo"); + Vcs vcs = new Vcs(); + vcs.setVcsType(VcsType.GITHUB); + workspace.setVcs(vcs); + + Webhook webhook = new Webhook(); + webhook.setWorkspace(workspace); + webhook.setMigratedV2(false); + + subject.execute(Operation.CREATE, TransactionPhase.PRECOMMIT, webhook, requestScope, Optional.empty()); + + assertTrue(webhook.isMigratedV2()); + verify(webhookService, never()).createOrUpdateWorkspaceWebhook(any()); + } + + @Test + void execute_update_whenV1Disabled_allowsUntouchedV1WebhookUpdate() { + webhookProperties.getV1().setDisabled(true); + + Workspace workspace = new Workspace(); + workspace.setId(java.util.UUID.fromString("77777777-7777-7777-7777-777777777777")); + 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(false); + + subject.execute(Operation.UPDATE, TransactionPhase.PRECOMMIT, webhook, requestScope, Optional.empty()); + + verify(webhookService).createOrUpdateWorkspaceWebhook(webhook); + } } diff --git a/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHookTest.java b/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHookTest.java new file mode 100644 index 0000000000..a4b31a5bc0 --- /dev/null +++ b/api/src/test/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHookTest.java @@ -0,0 +1,96 @@ +package io.terrakube.api.rs.hooks.webhook; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.yahoo.elide.annotation.LifeCycleHookBinding.Operation; +import com.yahoo.elide.annotation.LifeCycleHookBinding.TransactionPhase; +import com.yahoo.elide.core.security.ChangeSpec; +import com.yahoo.elide.core.security.RequestScope; + +import io.terrakube.api.plugin.vcs.WebhookProperties; +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 WebhookV1RevertGuardHookTest { + + private WebhookProperties webhookProperties; + private WebhookV1RevertGuardHook hook; + private RequestScope requestScope; + + @BeforeEach + void setUp() { + webhookProperties = new WebhookProperties(); + hook = new WebhookV1RevertGuardHook(); + hook.webhookProperties = webhookProperties; + requestScope = mock(RequestScope.class); + } + + @Test + void rejectsRevertFromTrueToFalseWhenV1Disabled() { + webhookProperties.getV1().setDisabled(true); + Webhook webhook = webhookFor(VcsType.BITBUCKET, false); + ChangeSpec change = changeSpec("migratedV2", true, false); + + WebhookManagementException exception = assertThrows(WebhookManagementException.class, + () -> hook.execute(Operation.UPDATE, TransactionPhase.PRECOMMIT, webhook, requestScope, + Optional.of(change))); + + assertEquals(400, exception.getStatus()); + assertTrue(exception.getMessage().contains("Webhook v1 is disabled")); + } + + @Test + void allowsUntouchedV1WebhookUpdateWhenV1Disabled() { + webhookProperties.getV1().setDisabled(true); + Webhook webhook = webhookFor(VcsType.GITHUB, false); + ChangeSpec unchanged = changeSpec("migratedV2", false, false); + + assertDoesNotThrow(() -> hook.execute( + Operation.UPDATE, TransactionPhase.PRECOMMIT, webhook, requestScope, Optional.of(unchanged))); + assertDoesNotThrow(() -> hook.execute( + Operation.UPDATE, TransactionPhase.PRECOMMIT, webhook, requestScope, Optional.empty())); + } + + @Test + void allowsRevertWhenV1Enabled() { + webhookProperties.getV1().setDisabled(false); + Webhook webhook = webhookFor(VcsType.GITHUB, false); + ChangeSpec change = changeSpec("migratedV2", true, false); + + assertDoesNotThrow(() -> hook.execute( + Operation.UPDATE, TransactionPhase.PRECOMMIT, webhook, requestScope, Optional.of(change))); + } + + private Webhook webhookFor(VcsType vcsType, boolean migratedV2) { + Vcs vcs = new Vcs(); + vcs.setVcsType(vcsType); + Workspace workspace = new Workspace(); + workspace.setId(UUID.randomUUID()); + workspace.setVcs(vcs); + Webhook webhook = new Webhook(); + webhook.setWorkspace(workspace); + webhook.setMigratedV2(migratedV2); + return webhook; + } + + private ChangeSpec changeSpec(String fieldName, Object original, Object modified) { + ChangeSpec change = mock(ChangeSpec.class); + when(change.getFieldName()).thenReturn(fieldName); + when(change.getOriginal()).thenReturn(original); + when(change.getModified()).thenReturn(modified); + return change; + } +} diff --git a/api/src/test/java/io/terrakube/api/rs/webhook/WebhookLifeCycleHookBindingTest.java b/api/src/test/java/io/terrakube/api/rs/webhook/WebhookLifeCycleHookBindingTest.java index d30c2464a5..6b64c68f49 100644 --- a/api/src/test/java/io/terrakube/api/rs/webhook/WebhookLifeCycleHookBindingTest.java +++ b/api/src/test/java/io/terrakube/api/rs/webhook/WebhookLifeCycleHookBindingTest.java @@ -10,6 +10,7 @@ import com.yahoo.elide.annotation.LifeCycleHookBinding; import io.terrakube.api.rs.hooks.webhook.WebhookManageHook; +import io.terrakube.api.rs.hooks.webhook.WebhookV1RevertGuardHook; /** * WebhookManageHookTest exercises the hook's execute() method directly, which @@ -28,7 +29,7 @@ private record Binding(LifeCycleHookBinding.Operation operation, LifeCycleHookBi } @Test - void registersWebhookManageHookForEveryOperationAndCommitPhaseItNeeds() { + void registersWebhookManageHookForEveryOperationAndCommitPhaseItNeeds() throws NoSuchFieldException { LifeCycleHookBinding[] bindings = Webhook.class.getAnnotationsByType(LifeCycleHookBinding.class); Set registered = java.util.Arrays.stream(bindings) @@ -49,5 +50,13 @@ void registersWebhookManageHookForEveryOperationAndCommitPhaseItNeeds() { new Binding(LifeCycleHookBinding.Operation.CREATE, LifeCycleHookBinding.TransactionPhase.POSTCOMMIT), new Binding(LifeCycleHookBinding.Operation.UPDATE, LifeCycleHookBinding.TransactionPhase.POSTCOMMIT), new Binding(LifeCycleHookBinding.Operation.DELETE, LifeCycleHookBinding.TransactionPhase.POSTCOMMIT)); + + LifeCycleHookBinding[] fieldBindings = Webhook.class.getDeclaredField("migratedV2") + .getAnnotationsByType(LifeCycleHookBinding.class); + boolean hasRevertGuardBinding = java.util.Arrays.stream(fieldBindings) + .anyMatch(b -> b.hook() == WebhookV1RevertGuardHook.class + && b.operation() == LifeCycleHookBinding.Operation.UPDATE + && b.phase() == LifeCycleHookBinding.TransactionPhase.PRECOMMIT); + assertThat(hasRevertGuardBinding).isTrue(); } } diff --git a/ui/src/domain/Workspaces/Settings/Webhook.tsx b/ui/src/domain/Workspaces/Settings/Webhook.tsx index fc50d4d90a..abf61e46c7 100644 --- a/ui/src/domain/Workspaces/Settings/Webhook.tsx +++ b/ui/src/domain/Workspaces/Settings/Webhook.tsx @@ -129,8 +129,6 @@ export const WorkspaceWebhook = ({ const [migratedV2, setMigratedV2] = useState(false); // Why the last background sync of the shared repository webhook failed, if it did. const [syncError, setSyncError] = useState(""); - // Only for a webhook that does not exist yet: create it as the shared repository webhook straight away. - const [createShared, setCreateShared] = useState(false); const [expanded, setExpanded] = useState([]); // Save model: every change waits for "Save webhook", then deleted, edited and new triggers go in one // atomic request, so a failed save changes nothing. @@ -217,7 +215,9 @@ export const WorkspaceWebhook = ({ data: { type: "webhook", id: newWebhookId, - ...(!webhookId && createShared && { attributes: { migratedV2: true } }), + ...(!webhookId && + vcsProvider && + SHARED_WEBHOOK_VCS.includes(vcsProvider) && { attributes: { migratedV2: true } }), }, relationships: { events: { data: events.map((event) => ({ type: "webhook_event", id: event.id })) }, @@ -243,7 +243,6 @@ export const WorkspaceWebhook = ({ ); setDeletedIds([]); setExpanded([]); - setCreateShared(false); message.success("Webhook saved"); onWorkspaceUpdate?.(); } catch (error: any) { @@ -257,27 +256,23 @@ export const WorkspaceWebhook = ({ } }; - // Both directions are one PATCH. Going back to a dedicated webhook creates it on the repository straight away, - // so the new repository webhook ID is read again. - const setShared = async (shared: boolean) => { + // One-way migration from a legacy v1 per-workspace webhook to the shared v2 repository webhook. + const migrateToShared = async () => { setSaving(true); try { const response = await axiosInstance.patch( `${baseUrl}/${webhookId}`, - { data: { type: "webhook", id: webhookId, attributes: { migratedV2: shared } } }, + { data: { type: "webhook", id: webhookId, attributes: { migratedV2: true } } }, { headers: { "Content-Type": "application/vnd.api+json" } } ); if (response.status !== 200 && response.status !== 204) { throw new Error(`Unexpected response ${response.status}`); } - setMigratedV2(shared); - if (!shared) { - const webhookRes = await axiosInstance.get(`${baseUrl}/${webhookId}`); - setRemoteHookId(webhookRes.data.data.attributes.remoteHookId ?? ""); - } - message.success(shared ? "Migrated to a shared webhook" : "Switched to a webhook for this workspace"); + setMigratedV2(true); + setRemoteHookId(""); + message.success("Migrated to a shared webhook"); } catch (error) { - message.error(`Couldn't ${shared ? "migrate" : "switch"} the webhook: ${getErrorMessage(error)}`); + message.error(`Couldn't migrate the webhook: ${getErrorMessage(error)}`); } finally { setSaving(false); } @@ -382,20 +377,6 @@ export const WorkspaceWebhook = ({ disabled={!manageWorkspace} /> - {webhookEnabled && !webhookId && vcsProvider && SHARED_WEBHOOK_VCS.includes(vcsProvider) && ( - - setCreateShared(e.target.checked)} - disabled={!manageWorkspace} - > - Share one webhook across this repository - - - )} {webhookEnabled && webhookId && migratedV2 && syncError && ( ) )} - {vcsProvider && SHARED_WEBHOOK_VCS.includes(vcsProvider) && ( + {!migratedV2 && vcsProvider && SHARED_WEBHOOK_VCS.includes(vcsProvider) && ( setShared(!migratedV2)} + onConfirm={migrateToShared} disabled={!manageWorkspace} > - + )} diff --git a/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx b/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx index a7aa29a1ad..e715dbf5f6 100644 --- a/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx +++ b/ui/src/domain/Workspaces/Settings/__tests__/Webhook.test.tsx @@ -233,19 +233,13 @@ describe("WorkspaceWebhook", () => { expect(screen.queryByLabelText("Repository webhook ID")).not.toBeInTheDocument(); }); - it("switches a shared webhook back to one for the workspace and shows its new ID", async () => { + it("does not allow switching a shared v2 webhook back to v1", async () => { mockWebhook({ migratedV2: true, remoteHookId: null }); - patch().mockResolvedValue({ status: 200 }); renderWebhook(); - const revert = await screen.findByRole("button", { name: "Switch to a webhook for this workspace" }); - mockWebhook({ migratedV2: false, remoteHookId: "9001" }); - fireEvent.click(revert); - fireEvent.click(await screen.findByRole("button", { name: "Switch" })); - - await waitFor(() => expect(patch()).toHaveBeenCalledTimes(1)); - expect(patch().mock.calls[0][1].data.attributes).toEqual({ migratedV2: false }); - expect(await screen.findByLabelText("Repository webhook ID")).toHaveValue("9001"); + expect(await screen.findByText("Shared with every workspace on this repository.")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /Switch to a webhook for this workspace/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /Migrate to shared webhook/i })).not.toBeInTheDocument(); }); it("says why the shared repository webhook could not be synced", async () => { @@ -267,10 +261,13 @@ describe("WorkspaceWebhook", () => { expect(screen.queryByText("The repository webhook is not working")).not.toBeInTheDocument(); }); - it("creates a new webhook as a shared one when asked", async () => { + it("always creates a new webhook as a shared v2 webhook", async () => { renderWebhook(workspace({ vcs: { data: { type: "vcs", id: "vcs-1" } } })); fireEvent.click(screen.getByRole("switch", { name: "Enable webhook" })); - fireEvent.click(screen.getByRole("checkbox", { name: "Share one webhook across this repository" })); + + expect( + screen.queryByRole("checkbox", { name: "Share one webhook across this repository" }) + ).not.toBeInTheDocument(); fireEvent.click(await screen.findByLabelText("Any branch")); fireEvent.mouseDown(screen.getByLabelText("Event"));