Skip to content
Merged
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,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;
Expand All @@ -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;
Expand All @@ -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;

Expand All @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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).
*
* <p>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).
*
* <p>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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<EnvironBean> environBeans = environDAO.getByName(envName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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<Utils> 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<Utils> 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
Expand Down
Loading
Loading