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 @@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -39,8 +40,15 @@
@Autowired
ObjectMapper objectMapper;

@Autowired

Check warning on line 43 in api/src/main/java/io/terrakube/api/plugin/vcs/controller/WebHookController.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this field injection and use constructor injection instead.

See more on https://sonarcloud.io/project/issues?id=AzBuilder_azb-server&issues=AaIn-WCnMoi91-tjwNFc&open=AaIn-WCnMoi91-tjwNFc&pullRequest=4065
WebhookProperties webhookProperties;

@PostMapping("/webhook/v1/{webhookId}")
public ResponseEntity<String> processWebhook(@PathVariable String webhookId,@RequestBody Map<String, Object> payload,@RequestHeader Map<String, String> headers) {
if (webhookProperties != null && webhookProperties.getV1().isDisabled()) {

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.

Nit: @RequestBody is still deserialized before this check, so a malformed body gets 400 instead of 404 when v1 is disabled. Not a problem functionally, just noting the endpoint still parses bodies.

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.

Acknowledged — keeping @RequestBody as-is since it does not affect valid webhook callers.

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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -44,6 +45,9 @@
@Autowired
RepoWebhookSyncScheduler repoWebhookSyncScheduler;

@Autowired

Check warning on line 48 in api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookManageHook.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this field injection and use constructor injection instead.

See more on https://sonarcloud.io/project/issues?id=AzBuilder_azb-server&issues=AaIn-WCJMoi91-tjwNFb&open=AaIn-WCJMoi91-tjwNFb&pullRequest=4065
WebhookProperties webhookProperties;

@Override
public void execute(Operation operation, TransactionPhase phase, Webhook elideEntity, RequestScope requestScope,
Optional<ChangeSpec> changes) {
Expand All @@ -53,6 +57,12 @@
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
Expand All @@ -64,6 +74,8 @@
} else {
webhookService.createOrUpdateWorkspaceWebhook(elideEntity);
}
} catch (WebhookManagementException e) {
throw e;
} catch (HttpClientErrorException e) {
throw new WebhookManagementException(HttpStatus.SC_FAILED_DEPENDENCY,
buildPermissionErrorMessage(elideEntity, e));
Expand Down Expand Up @@ -123,6 +135,10 @@
}
}

private boolean isWebhookV1Disabled() {
return webhookProperties != null && webhookProperties.getV1().isDisabled();
}

private boolean isMigratedV2Shared(Webhook elideEntity) {
return elideEntity.isMigratedV2() && isSharedWebhookProvider(elideEntity);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Webhook> {

@Autowired

Check warning on line 25 in api/src/main/java/io/terrakube/api/rs/hooks/webhook/WebhookV1RevertGuardHook.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this field injection and use constructor injection instead.

See more on https://sonarcloud.io/project/issues?id=AzBuilder_azb-server&issues=AaIs8-Tm6nBAYS79Rf0M&open=AaIs8-Tm6nBAYS79Rf0M&pullRequest=4065
WebhookProperties webhookProperties;

@Override
public void execute(Operation operation, TransactionPhase phase, Webhook elideEntity, RequestScope requestScope,
Optional<ChangeSpec> 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;
}
}
2 changes: 2 additions & 0 deletions api/src/main/java/io/terrakube/api/rs/webhook/Webhook.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down
4 changes: 4 additions & 0 deletions api/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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}

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.

Turning this on makes every existing v1 hook return 404 while the remote hooks stay registered, and nothing in this PR migrates them (that comes in #4066). Could the comment say that existing workspaces have to be migrated first? Also WebhookV1Disabled is not mentioned anywhere in the docs yet.

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.

Updated the application.properties comment in 75956322f to note that existing v1 workspaces must be migrated first (automated on startup in #4066 once the full stack is merged).


##############
#EXECUTOR URL#
Expand Down
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -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<String> validResponse = controller.processWebhook(
UUID.randomUUID().toString(), Map.of("ref", "refs/heads/main"), Map.of());
ResponseEntity<String> 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<String> invalidResponse = controller.processWebhook("not-a-uuid", Map.of(), Map.of());
ResponseEntity<String> 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")));
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -54,6 +56,9 @@ class WebhookManageHookTest {
@Mock
RepoWebhookSyncScheduler repoWebhookSyncScheduler;

@Spy
WebhookProperties webhookProperties = new WebhookProperties();

@InjectMocks
WebhookManageHook subject;

Expand Down Expand Up @@ -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);
}
}
Loading
Loading