From 9cecf6353cabbf05d3d8c9d415deb5ce628bdbd1 Mon Sep 17 00:00:00 2001 From: Yongwen Xu Date: Wed, 18 Nov 2026 18:07:28 +0000 Subject: [PATCH] Check cluster ownership for infra applies and cluster bindings (BUG-319978) POST /v1/envs/{env}/{stage}/infras authorizes only the env in the path, but ApplyInfraWorker acted on the clusterName from the request body. Any env admin could reconfigure or resize another env's Rodimus cluster, or claim a group that live hosts report. PUT and POST /v1/envs also accepted any clusterName, which lets an env bind a name another env owns. Add one ownership check in EnvironmentHandler and run it: - in ApplyInfraWorker before any Rodimus or Teletraan change, which also covers jobs already queued; - when an env stage's clusterName changes, and when an env stage is created with one. The check rejects cluster names Rodimus cannot address, existing Rodimus clusters not bound to the env, names bound to another env, and new names that another non-sidecar env deploys to or that hosts already report. Co-Authored-By: Claude Opus 5.5 --- .../teletraan/handler/EnvironmentHandler.java | 105 ++++++++ .../teletraan/resource/ApplyInfraWorker.java | 7 +- .../teletraan/resource/Environs.java | 9 + .../handler/EnvironmentHandlerTest.java | 141 +++++++++++ .../resource/ApplyInfraWorkerTest.java | 55 ++++ .../resource/InfraClusterOwnershipTest.java | 237 ++++++++++++++++++ 6 files changed, 553 insertions(+), 1 deletion(-) create mode 100644 deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/InfraClusterOwnershipTest.java diff --git a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/handler/EnvironmentHandler.java b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/handler/EnvironmentHandler.java index bccdf6f76a..c8be75cbfb 100644 --- a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/handler/EnvironmentHandler.java +++ b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/handler/EnvironmentHandler.java @@ -21,6 +21,7 @@ import com.pinterest.deployservice.common.Constants; import com.pinterest.deployservice.dao.EnvironDAO; import com.pinterest.deployservice.dao.GroupDAO; +import com.pinterest.deployservice.dao.HostDAO; import com.pinterest.deployservice.handler.ConfigHistoryHandler; import com.pinterest.deployservice.handler.EnvironHandler; import com.pinterest.teletraan.TeletraanServiceContext; @@ -32,6 +33,7 @@ import com.pinterest.teletraan.universal.security.bean.TeletraanPrincipal; import java.security.Principal; import java.util.*; +import java.util.regex.Pattern; import javax.ws.rs.ForbiddenException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; @@ -43,11 +45,14 @@ public class EnvironmentHandler { private static final Logger LOG = LoggerFactory.getLogger(EnvironmentHandler.class); + // Rodimus cluster paths accept [a-zA-Z0-9\-_]+; environs.cluster_name is VARCHAR(128). + private static final Pattern CLUSTER_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9\\-_]{1,128}"); private final ConfigHistoryHandler configHistoryHandler; private final EnvironDAO environDAO; private final EnvironHandler environHandler; private final GroupDAO groupDAO; + private final HostDAO hostDAO; private final AuthorizationFactory authorizationFactory; private final TeletraanServiceContext context; @@ -56,6 +61,7 @@ public EnvironmentHandler(TeletraanServiceContext context) { environDAO = context.getEnvironDAO(); environHandler = new EnvironHandler(context); groupDAO = context.getGroupDAO(); + hostDAO = context.getHostDAO(); authorizationFactory = context.getAuthorizationFactory(); this.context = context; } @@ -110,6 +116,13 @@ public void updateEnvironment( updateEnvironBean.setSystem_priority(originalSystemPriority); } + String updateClusterName = updateEnvironBean.getCluster_name(); + if (StringUtils.isNotEmpty(updateClusterName) + && !StringUtils.equalsIgnoreCase( + updateClusterName, originEnvironBean.getCluster_name())) { + validateClusterClaim(originEnvironBean, updateClusterName); + } + try { updateEnvironBean.validate(); stageTypeValidate(originEnvironBean, updateEnvironBean); @@ -261,4 +274,96 @@ public void validateSystemPriorityPermission( envName, stageName); } + + /** + * Rejects cluster names that Rodimus cannot address. Cluster names are interpolated into + * Rodimus URLs, so anything outside the Rodimus path pattern is refused. + */ + public static void validateClusterName(String clusterName) { + if (clusterName == null || !CLUSTER_NAME_PATTERN.matcher(clusterName).matches()) { + throw new WebApplicationException( + "clusterName must be 1-128 letters, digits, '-' or '_'", + Response.Status.BAD_REQUEST); + } + } + + /** + * Validates that an infrastructure apply for {@code environBean} may act on {@code clusterName} + * (BUG-319978). + * + *

An existing Rodimus cluster may be changed only through the environment it is bound to. A + * cluster that does not exist yet may be created only if the environment may claim its name; + * see {@link #validateClusterClaim}. + * + * @param clusterExists whether Rodimus already has a cluster named {@code clusterName} + * @throws WebApplicationException 400 if the name is invalid + * @throws ForbiddenException if the environment may not act on the cluster + */ + public void validateInfraCluster( + EnvironBean environBean, String clusterName, boolean clusterExists) throws Exception { + validateClusterName(clusterName); + if (clusterExists + && !StringUtils.equalsIgnoreCase(environBean.getCluster_name(), clusterName)) { + throw new ForbiddenException( + String.format( + "Cluster %s is not bound to env %s/%s", + clusterName, environBean.getEnv_name(), environBean.getStage_name())); + } + validateClusterClaim(environBean, clusterName); + } + + /** + * Validates that {@code environBean} may bind {@code clusterName} as its cluster (BUG-319978). + * + *

Binding makes the environment the cluster's owner: capacity checks, main-environment + * lookups and Rodimus resolve the cluster's hosts to it. The name must not be bound to another + * environment. If this environment is not yet bound to it, no other non-sidecar environment may + * deploy to the group, and no hosts may report the group unless this environment already + * deploys to it. + * + * @param environBean the environment claiming the cluster; its env_id is null if it does not + * exist yet + * @throws WebApplicationException 400 if the name is invalid + * @throws ForbiddenException if the cluster belongs to, or is in use by, something else + */ + public void validateClusterClaim(EnvironBean environBean, String clusterName) throws Exception { + validateClusterName(clusterName); + EnvironBean owner = environDAO.getByCluster(clusterName); + if (owner != null && !isSameEnvironment(environBean, owner)) { + throw new ForbiddenException( + String.format( + "Cluster %s is bound to env %s/%s", + clusterName, owner.getEnv_name(), owner.getStage_name())); + } + if (StringUtils.equalsIgnoreCase(environBean.getCluster_name(), clusterName)) { + return; + } + + boolean deploysToGroup = false; + for (EnvironBean groupEnv : + environDAO.getEnvsByGroups(Collections.singletonList(clusterName))) { + if (isSameEnvironment(environBean, groupEnv)) { + deploysToGroup = true; + } else if (!isSidecarEnvironment(groupEnv)) { + throw new ForbiddenException( + String.format( + "Group %s is already capacity of env %s/%s", + clusterName, groupEnv.getEnv_name(), groupEnv.getStage_name())); + } + } + if (!deploysToGroup && hostDAO.getGroupSize(clusterName) > 0) { + throw new ForbiddenException( + String.format( + "Group %s already has hosts that env %s/%s does not deploy to", + clusterName, environBean.getEnv_name(), environBean.getStage_name())); + } + } + + private static boolean isSameEnvironment(EnvironBean a, EnvironBean b) { + return a.getEnv_id() != null && a.getEnv_id().equals(b.getEnv_id()); + } + + private static boolean isSidecarEnvironment(EnvironBean environBean) { + return environBean.getSystem_priority() != null && environBean.getSystem_priority() > 0; + } } diff --git a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/ApplyInfraWorker.java b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/ApplyInfraWorker.java index 6d85a2f1b3..6fca709ff0 100644 --- a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/ApplyInfraWorker.java +++ b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/ApplyInfraWorker.java @@ -146,15 +146,20 @@ private void applyInfra(WorkerJobBean workerJobBean) throws Exception { String stageName = infraConfigBean.getStageName(); String clusterName = infraConfigBean.getClusterName(); + EnvironmentHandler.validateClusterName(clusterName); ClusterInfoPublicIdsBean newClusterInfoPublicIdsBean = ClusterInfoPublicIdsBean.fromInfraConfigBean(infraConfigBean); ClusterInfoPublicIdsBean existingClusterInfoPublicIdsBean = rodimusManager.getClusterInfoPublicIdsBean(clusterName); + EnvironBean originEnvironBean = Utils.getEnvStage(environDAO, envName, stageName); + // EnvInfras authorizes only the env in the request path; clusterName comes from the request + // body. Check it against that env here, at execution time, before changing anything. + environmentHandler.validateInfraCluster( + originEnvironBean, clusterName, existingClusterInfoPublicIdsBean != null); if (existingClusterInfoPublicIdsBean == null) { LOG.info( "Creating cluster and supporting teletraan records for cluster: {}", clusterName); - EnvironBean originEnvironBean = Utils.getEnvStage(environDAO, envName, stageName); try { EnvironBean updateEnvironBean = originEnvironBean.withCluster_name(clusterName); environmentHandler.updateEnvironment( diff --git a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Environs.java b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Environs.java index 885a0a4e8b..0fea758a58 100644 --- a/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Environs.java +++ b/deploy-service/teletraanservice/src/main/java/com/pinterest/teletraan/resource/Environs.java @@ -201,6 +201,15 @@ public Response create( environBean.getStage_name(), environBean.getSystem_priority()); + if (StringUtils.isNotEmpty(environBean.getCluster_name())) { + // Check against a bean that only names the new stage: the request's id is + // caller-supplied and is replaced when the stage is created. + EnvironBean newEnvironBean = new EnvironBean(); + newEnvironBean.setEnv_name(environBean.getEnv_name()); + newEnvironBean.setStage_name(environBean.getStage_name()); + environmentHandler.validateClusterClaim(newEnvironBean, environBean.getCluster_name()); + } + String operator = sc.getUserPrincipal().getName(); String envName = environBean.getEnv_name(); List environBeans = environDAO.getByName(envName); diff --git a/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/handler/EnvironmentHandlerTest.java b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/handler/EnvironmentHandlerTest.java index 637d53e24d..983a77103a 100644 --- a/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/handler/EnvironmentHandlerTest.java +++ b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/handler/EnvironmentHandlerTest.java @@ -22,12 +22,16 @@ import com.pinterest.deployservice.bean.EnvironBean; import com.pinterest.deployservice.dao.EnvironDAO; import com.pinterest.deployservice.dao.GroupDAO; +import com.pinterest.deployservice.dao.HostDAO; import com.pinterest.deployservice.handler.ConfigHistoryHandler; import com.pinterest.deployservice.handler.EnvironHandler; import com.pinterest.teletraan.TeletraanServiceContext; import com.pinterest.teletraan.resource.EnvCapacities.CapacityType; import com.pinterest.teletraan.resource.Utils; +import java.util.Arrays; +import java.util.Collections; import java.util.Optional; +import javax.ws.rs.ForbiddenException; import javax.ws.rs.WebApplicationException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,6 +43,7 @@ class EnvironmentHandlerTest { @Mock private EnvironDAO mockEnvironDAO; @Mock private EnvironHandler mockEnvironHandler; @Mock private GroupDAO mockGroupDAO; + @Mock private HostDAO mockHostDAO; @Mock private TeletraanServiceContext mockContext; private EnvironmentHandler handler; @@ -50,6 +55,7 @@ void setUp() { // Set up context to return mocks when(mockContext.getEnvironDAO()).thenReturn(mockEnvironDAO); when(mockContext.getGroupDAO()).thenReturn(mockGroupDAO); + when(mockContext.getHostDAO()).thenReturn(mockHostDAO); // Use real constructor, but inject our mocks after (quick hack) handler = new EnvironmentHandler(mockContext); @@ -220,6 +226,141 @@ void testDeleteCapacityForHost() throws Exception { verify(mockEnvironDAO, never()).deleteCluster(any(), any()); } } + + @Test + void testValidateClusterName() { + char[] maxLength = new char[128]; + Arrays.fill(maxLength, 'a'); + assertDoesNotThrow(() -> EnvironmentHandler.validateClusterName("svc-prod_1")); + assertDoesNotThrow(() -> EnvironmentHandler.validateClusterName(new String(maxLength))); + + for (String invalid : + new String[] { + null, "", new String(maxLength) + "a", "a/b", "../a", "a?b", "a#b", "a.b", "a b" + }) { + WebApplicationException e = + assertThrows( + WebApplicationException.class, + () -> EnvironmentHandler.validateClusterName(invalid)); + assertEquals(400, e.getResponse().getStatus()); + } + } + + @Test + void testValidateInfraCluster_existingClusterMustBeBoundToEnv() throws Exception { + EnvironBean own = env("id1", "own-asg", null); + EnvironBean unbound = env("id1", null, null); + when(mockEnvironDAO.getByCluster("own-asg")).thenReturn(own); + + assertDoesNotThrow(() -> handler.validateInfraCluster(own, "own-asg", true)); + assertDoesNotThrow(() -> handler.validateInfraCluster(own, "OWN-ASG", true)); + assertThrows( + ForbiddenException.class, + () -> handler.validateInfraCluster(own, "other-asg", true)); + assertThrows( + ForbiddenException.class, + () -> handler.validateInfraCluster(unbound, "own-asg", true)); + } + + @Test + void testValidateInfraCluster_rejectsWhenOwnerIsAnotherEnv() throws Exception { + // Even if this env's cluster_name matches, the cluster's recorded owner must be this env. + EnvironBean attacker = env("attacker", "victim-asg", null); + when(mockEnvironDAO.getByCluster("victim-asg")) + .thenReturn(env("victim", "victim-asg", null)); + + assertThrows( + ForbiddenException.class, + () -> handler.validateInfraCluster(attacker, "victim-asg", true)); + assertThrows( + ForbiddenException.class, + () -> handler.validateInfraCluster(attacker, "victim-asg", false)); + } + + @Test + void testValidateClusterClaim_newUnusedName() throws Exception { + EnvironBean bean = env("id1", null, null); + + assertDoesNotThrow(() -> handler.validateClusterClaim(bean, "env-stage")); + assertDoesNotThrow(() -> handler.validateInfraCluster(bean, "env-stage", false)); + } + + @Test + void testValidateClusterClaim_groupOfAnotherEnv() throws Exception { + EnvironBean bean = env("id1", null, null); + when(mockEnvironDAO.getEnvsByGroups(Collections.singletonList("shared"))) + .thenReturn(Collections.singletonList(env("id2", null, null))); + + assertThrows(ForbiddenException.class, () -> handler.validateClusterClaim(bean, "shared")); + } + + @Test + void testValidateClusterClaim_ignoresSidecarEnvs() throws Exception { + EnvironBean bean = env("id1", null, null); + when(mockEnvironDAO.getEnvsByGroups(Collections.singletonList("grp"))) + .thenReturn(Collections.singletonList(env("sidecar", null, 10))); + + assertDoesNotThrow(() -> handler.validateClusterClaim(bean, "grp")); + } + + @Test + void testValidateClusterClaim_hostsInGroup() throws Exception { + EnvironBean bean = env("id1", null, null); + when(mockHostDAO.getGroupSize("grp")).thenReturn(2L); + + assertThrows(ForbiddenException.class, () -> handler.validateClusterClaim(bean, "grp")); + + // Hosts are fine if this environment already deploys to the group. + when(mockEnvironDAO.getEnvsByGroups(Collections.singletonList("grp"))) + .thenReturn(Collections.singletonList(bean)); + assertDoesNotThrow(() -> handler.validateClusterClaim(bean, "grp")); + } + + @Test + void testUpdateEnvironment_rejectsClusterBoundToAnotherEnv() throws Exception { + EnvironBean origin = env("id1", null, null); + origin.setEnv_name("env"); + origin.setStage_name("stage"); + when(mockEnvironDAO.getByCluster("victim-asg")).thenReturn(env("id2", "victim-asg", null)); + EnvironBean update = new EnvironBean(); + update.setCluster_name("victim-asg"); + + try (MockedStatic mocked = mockStatic(Utils.class)) { + when(Utils.getEnvStage(any(), any(), any())).thenReturn(origin); + + assertThrows( + ForbiddenException.class, + () -> handler.updateEnvironment(null, "op", "env", "stage", update)); + verify(mockEnvironHandler, never()).updateStage(any(), any()); + } + } + + @Test + void testUpdateEnvironment_skipsClusterCheckWhenUnchanged() throws Exception { + EnvironBean origin = env("id1", "env-stage", null); + origin.setEnv_name("env"); + origin.setStage_name("stage"); + origin.setStage_type(EnvType.PRODUCTION); + EnvironBean update = new EnvironBean(); + update.setCluster_name("ENV-STAGE"); + update.setStage_type(EnvType.PRODUCTION); + + try (MockedStatic mocked = mockStatic(Utils.class)) { + when(Utils.getEnvStage(any(), any(), any())).thenReturn(origin); + + assertDoesNotThrow(() -> handler.updateEnvironment(null, "op", "env", "stage", update)); + verify(mockEnvironDAO, never()).getByCluster(any()); + verify(mockEnvironHandler).updateStage(any(), eq("op")); + } + } + + private static EnvironBean env(String id, String clusterName, Integer systemPriority) { + EnvironBean bean = new EnvironBean(); + bean.setEnv_id(id); + bean.setCluster_name(clusterName); + bean.setSystem_priority(systemPriority); + return bean; + } } // Utility for injecting and mocking statics diff --git a/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/ApplyInfraWorkerTest.java b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/ApplyInfraWorkerTest.java index 3785db71c8..88a9cda139 100644 --- a/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/ApplyInfraWorkerTest.java +++ b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/ApplyInfraWorkerTest.java @@ -39,6 +39,7 @@ import java.sql.Connection; import java.util.Collections; import java.util.Optional; +import javax.ws.rs.ForbiddenException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; @@ -69,6 +70,10 @@ void setUp() { when(mockContext.getRodimusManager()).thenReturn(mockRodimusManager); when(mockContext.getUtilDAO()).thenReturn(mockUtilDAO); when(mockContext.getWorkerJobDAO()).thenReturn(mockWorkerJobDAO); + try { + when(mockEnvironDAO.getByStage("env", "stage")).thenReturn(new EnvironBean()); + } catch (Exception ignored) { + } // Patch the counter creation with dummy counters mockSuccessCounter = mock(Counter.class); @@ -133,6 +138,7 @@ void testRunInternal_clusterCreateBranch_success() throws Exception { verify(mockWorkerJobDAO) .updateStatus(eq(job), eq(WorkerJobBean.Status.RUNNING), anyLong()); + verify(mockEnvHandler).validateInfraCluster(origEnv, "CLUSTER-NEW", false); verify(mockEnvHandler) .updateEnvironment(isNull(), eq("op"), eq("env"), eq("stage"), any()); verify(mockEnvHandler) @@ -175,6 +181,7 @@ void testRunInternal_clusterUpdateBranch_success() throws Exception { worker.run(); + verify(mockEnvHandler).validateInfraCluster(any(), eq("CLUSTER-EXIST"), eq(true)); verify(mockRodimusManager).updateClusterWithPublicIds(eq("CLUSTER-EXIST"), any()); verify(mockWorkerJobDAO).updateStatus(eq(job), eq(WorkerJobBean.Status.RUNNING), anyLong()); verify(mockWorkerJobDAO) @@ -293,6 +300,54 @@ void testApplyInfra_invokesCapacityPoliciesAlarmsActionsUpdate() throws Exceptio verify(mockRodimusManager).postClusterScheduledActions(eq(clusterName), any()); } + @Test + void testRunInternal_ownershipRejected_noChanges() throws Exception { + WorkerJobBean job = + makeJobBean( + "4", + WorkerJobBean.Status.INITIALIZED, + makeInfraConfigJson("OTHER-ENVS-CLUSTER", "env", "stage", "op")); + when(mockWorkerJobDAO.getOldestByJobTypeStatus(any(), any(), anyInt())) + .thenReturn(Collections.singletonList(job)); + when(mockUtilDAO.getLock(any())).thenReturn(mock(Connection.class)); + when(mockWorkerJobDAO.getById("4")).thenReturn(job); + when(mockRodimusManager.getClusterInfoPublicIdsBean("OTHER-ENVS-CLUSTER")) + .thenReturn(mock(ClusterInfoPublicIdsBean.class)); + doThrow(new ForbiddenException("not owned")) + .when(mockEnvHandler) + .validateInfraCluster(any(), eq("OTHER-ENVS-CLUSTER"), anyBoolean()); + + worker.run(); + + verify(mockWorkerJobDAO).updateStatus(eq(job), eq(WorkerJobBean.Status.FAILED), anyLong()); + verify(mockRodimusManager, never()).updateClusterWithPublicIds(any(), any()); + verify(mockRodimusManager, never()) + .createClusterWithEnvPublicIds(any(), any(), any(), any()); + verify(mockRodimusManager, never()).updateClusterCapacity(any(), any(), any()); + verify(mockRodimusManager, never()).postClusterScalingPolicies(any(), any()); + verify(mockEnvHandler, never()).updateEnvironment(any(), any(), any(), any(), any()); + verify(mockEnvHandler, never()) + .createCapacityForHostOrGroup(any(), any(), any(), any(), any(), any()); + } + + @Test + void testRunInternal_invalidClusterName_noRodimusCalls() throws Exception { + WorkerJobBean job = + makeJobBean( + "5", + WorkerJobBean.Status.INITIALIZED, + makeInfraConfigJson("victim/../other", "env", "stage", "op")); + when(mockWorkerJobDAO.getOldestByJobTypeStatus(any(), any(), anyInt())) + .thenReturn(Collections.singletonList(job)); + when(mockUtilDAO.getLock(any())).thenReturn(mock(Connection.class)); + when(mockWorkerJobDAO.getById("5")).thenReturn(job); + + worker.run(); + + verify(mockWorkerJobDAO).updateStatus(eq(job), eq(WorkerJobBean.Status.FAILED), anyLong()); + verifyNoInteractions(mockRodimusManager); + } + // Helper for WorkerJobBean private WorkerJobBean makeJobBean(String id, WorkerJobBean.Status status, String configJson) { WorkerJobBean job = new WorkerJobBean(); diff --git a/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/InfraClusterOwnershipTest.java b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/InfraClusterOwnershipTest.java new file mode 100644 index 0000000000..2817e39fb5 --- /dev/null +++ b/deploy-service/teletraanservice/src/test/java/com/pinterest/teletraan/resource/InfraClusterOwnershipTest.java @@ -0,0 +1,237 @@ +/** + * Copyright (c) 2026 Pinterest, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.pinterest.teletraan.resource; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.pinterest.deployservice.bean.ClusterInfoPublicIdsBean; +import com.pinterest.deployservice.bean.EnvironBean; +import com.pinterest.deployservice.bean.InfraBean; +import com.pinterest.deployservice.bean.InfraConfigBean; +import com.pinterest.deployservice.bean.WorkerJobBean; +import com.pinterest.deployservice.bean.rodimus.RodimusAutoScalingPolicies; +import com.pinterest.deployservice.dao.EnvironDAO; +import com.pinterest.deployservice.dao.GroupDAO; +import com.pinterest.deployservice.dao.HostDAO; +import com.pinterest.deployservice.dao.UtilDAO; +import com.pinterest.deployservice.dao.WorkerJobDAO; +import com.pinterest.deployservice.rodimus.RodimusManager; +import com.pinterest.teletraan.TeletraanServiceContext; +import com.pinterest.teletraan.handler.EnvironmentHandler; +import java.security.Principal; +import java.sql.Connection; +import java.util.Collections; +import javax.ws.rs.ForbiddenException; +import javax.ws.rs.core.SecurityContext; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * BUG-319978: an infra apply is authorized against the env in the request path, but the cluster it + * acts on comes from the request body. These tests use the reporter's topology: victim-svc/prod + * owns victim-asg, the caller owns attacker-svc/prod (bound to attacker-asg), unclaimed-grp has + * hosts but no owning environment, and orphan-asg exists in Rodimus without a Teletraan owner. + */ +class InfraClusterOwnershipTest { + + private static final String ATTACKER_ENV = "attacker-svc"; + private static final String STAGE = "prod"; + + private EnvironDAO environDAO; + private GroupDAO groupDAO; + private HostDAO hostDAO; + private RodimusManager rodimusManager; + private WorkerJobDAO workerJobDAO; + private UtilDAO utilDAO; + private TeletraanServiceContext context; + private SecurityContext securityContext; + private EnvironBean attackerEnv; + + @BeforeEach + void setUp() throws Exception { + environDAO = mock(EnvironDAO.class); + groupDAO = mock(GroupDAO.class); + hostDAO = mock(HostDAO.class); + rodimusManager = mock(RodimusManager.class); + workerJobDAO = mock(WorkerJobDAO.class); + utilDAO = mock(UtilDAO.class); + + context = new TeletraanServiceContext(); + context.setEnvironDAO(environDAO); + context.setGroupDAO(groupDAO); + context.setHostDAO(hostDAO); + context.setRodimusManager(rodimusManager); + context.setWorkerJobDAO(workerJobDAO); + context.setUtilDAO(utilDAO); + + Principal principal = mock(Principal.class); + when(principal.getName()).thenReturn("attacker"); + securityContext = mock(SecurityContext.class); + when(securityContext.getUserPrincipal()).thenReturn(principal); + + EnvironBean victimEnv = env("env-victim", "victim-svc", "victim-asg"); + attackerEnv = env("env-attacker", ATTACKER_ENV, "attacker-asg"); + when(environDAO.getByStage("victim-svc", STAGE)).thenReturn(victimEnv); + when(environDAO.getByStage(ATTACKER_ENV, STAGE)).thenReturn(attackerEnv); + when(environDAO.getByCluster("victim-asg")).thenReturn(victimEnv); + when(environDAO.getByCluster("attacker-asg")).thenReturn(attackerEnv); + when(environDAO.getEnvsByGroups(Collections.singletonList("victim-asg"))) + .thenReturn(Collections.singletonList(victimEnv)); + when(hostDAO.getGroupSize("victim-asg")).thenReturn(5L); + when(hostDAO.getGroupSize("unclaimed-grp")).thenReturn(3L); + + ClusterInfoPublicIdsBean existingCluster = mock(ClusterInfoPublicIdsBean.class); + when(rodimusManager.getClusterInfoPublicIdsBean("victim-asg")).thenReturn(existingCluster); + when(rodimusManager.getClusterInfoPublicIdsBean("attacker-asg")) + .thenReturn(existingCluster); + when(rodimusManager.getClusterInfoPublicIdsBean("orphan-asg")).thenReturn(existingCluster); + when(rodimusManager.getClusterScalingPolicies(anyString())) + .thenReturn(RodimusAutoScalingPolicies.builder().build()); + } + + @Test + void worker_failsJobForAnotherEnvsCluster() throws Exception { + WorkerJobBean job = queueJob("victim-asg"); + + new ApplyInfraWorker(context).run(); + + assertFailedWithoutChanges(job); + } + + @Test + void worker_failsJobForRodimusClusterWithoutTeletraanOwner() throws Exception { + WorkerJobBean job = queueJob("orphan-asg"); + + new ApplyInfraWorker(context).run(); + + assertFailedWithoutChanges(job); + } + + @Test + void worker_failsJobClaimingUnclaimedGroupThatHasHosts() throws Exception { + WorkerJobBean job = queueJob("unclaimed-grp"); + + new ApplyInfraWorker(context).run(); + + assertFailedWithoutChanges(job); + verify(rodimusManager, never()).createClusterWithEnvPublicIds(any(), any(), any(), any()); + } + + @Test + void worker_updatesOwnCluster() throws Exception { + WorkerJobBean job = queueJob("attacker-asg"); + + new ApplyInfraWorker(context).run(); + + verify(rodimusManager).updateClusterWithPublicIds(eq("attacker-asg"), any()); + verify(rodimusManager).updateClusterCapacity(eq("attacker-asg"), any(), any()); + verify(workerJobDAO).updateStatus(eq(job), eq(WorkerJobBean.Status.COMPLETED), anyLong()); + } + + @Test + void envUpdate_rejectsBindingAnotherEnvsCluster() throws Exception { + EnvironBean update = new EnvironBean(); + update.setCluster_name("victim-asg"); + + assertThrows( + ForbiddenException.class, + () -> + new EnvironmentHandler(context) + .updateEnvironment(null, "attacker", ATTACKER_ENV, STAGE, update)); + + verify(environDAO, never()).update(any(), any(), any()); + } + + @Test + void envUpdate_rejectsBindingUnclaimedGroupThatHasHosts() throws Exception { + EnvironBean update = new EnvironBean(); + update.setCluster_name("unclaimed-grp"); + + assertThrows( + ForbiddenException.class, + () -> + new EnvironmentHandler(context) + .updateEnvironment(null, "attacker", ATTACKER_ENV, STAGE, update)); + + verify(environDAO, never()).update(any(), any(), any()); + } + + @Test + void envCreate_rejectsAnotherEnvsClusterEvenWithSpoofedId() throws Exception { + EnvironBean create = new EnvironBean(); + create.setEnv_id("env-victim"); + create.setEnv_name(ATTACKER_ENV); + create.setStage_name("new"); + create.setCluster_name("victim-asg"); + + assertThrows( + ForbiddenException.class, + () -> new Environs(context).create(securityContext, null, create)); + + verify(environDAO, never()).insert(any()); + } + + private void assertFailedWithoutChanges(WorkerJobBean job) throws Exception { + verify(workerJobDAO).updateStatus(eq(job), eq(WorkerJobBean.Status.FAILED), anyLong()); + verify(rodimusManager, never()).updateClusterWithPublicIds(any(), any()); + verify(rodimusManager, never()).updateClusterCapacity(any(), any(), any()); + verify(rodimusManager, never()).deleteClusterScalingPolicy(any(), any()); + verify(rodimusManager, never()).deleteClusterAlarm(any(), any()); + verify(rodimusManager, never()).deleteClusterScheduledAction(any(), any()); + verify(environDAO, never()).update(any(), any(), any()); + verify(groupDAO, never()).addGroupCapacity(any(), any()); + } + + private WorkerJobBean queueJob(String clusterName) throws Exception { + InfraConfigBean config = + InfraConfigBean.fromInfraBean("attacker", ATTACKER_ENV, STAGE, infra(clusterName)); + WorkerJobBean job = + WorkerJobBean.builder() + .id("job-" + clusterName) + .job_type(WorkerJobBean.JobType.INFRA_APPLY) + .config(new ObjectMapper().writeValueAsString(config)) + .status(WorkerJobBean.Status.INITIALIZED) + .build(); + when(workerJobDAO.getOldestByJobTypeStatus(any(), any(), anyInt())) + .thenReturn(new java.util.ArrayList<>(Collections.singletonList(job))); + when(workerJobDAO.getById(job.getId())).thenReturn(job); + when(utilDAO.getLock(any())).thenReturn(mock(Connection.class)); + return job; + } + + private static InfraBean infra(String clusterName) { + return InfraBean.builder().clusterName(clusterName).minCapacity(0).maxCapacity(0).build(); + } + + private static EnvironBean env(String id, String name, String clusterName) { + EnvironBean bean = new EnvironBean(); + bean.setEnv_id(id); + bean.setEnv_name(name); + bean.setStage_name(STAGE); + bean.setCluster_name(clusterName); + return bean; + } +}