io.fabric8.kubernetes.api.model.PodSecurityContext Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.PodSecurityContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPodSecurityContextProperty() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{runAsUser: 65534, fsGroup: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

	deployer = new KubernetesAppDeployer(new KubernetesDeployerProperties(), null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
Example #2
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPodSecurityContextGlobalProperty() {
	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), null);

	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();

	KubernetesDeployerProperties.PodSecurityContext securityContext = new KubernetesDeployerProperties.PodSecurityContext();
	securityContext.setFsGroup(65534L);
	securityContext.setRunAsUser(65534L);

	kubernetesDeployerProperties.setPodSecurityContext(securityContext);

	deployer = new KubernetesAppDeployer(kubernetesDeployerProperties, null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
Example #3
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPodSecurityContextUIDOnly() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{runAsUser: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

	deployer = new KubernetesAppDeployer(new KubernetesDeployerProperties(), null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertNull("Unexpected fs group", podSecurityContext.getFsGroup());
}
 
Example #4
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPodSecurityContextFsGroupOnly() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{fsGroup: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

	deployer = new KubernetesAppDeployer(new KubernetesDeployerProperties(), null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertNull("Unexpected run as user", podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
Example #5
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPodSecurityContextPropertyOverrideGlobal() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{runAsUser: 65534, fsGroup: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();

	KubernetesDeployerProperties.PodSecurityContext securityContext = new KubernetesDeployerProperties.PodSecurityContext();
	securityContext.setFsGroup(1000L);
	securityContext.setRunAsUser(1000L);

	kubernetesDeployerProperties.setPodSecurityContext(securityContext);

	deployer = new KubernetesAppDeployer(kubernetesDeployerProperties, null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
Example #6
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldAssignSecurityContextSharedByPods() throws Exception {
  // given
  PodSpec podSpec1 =
      new PodSpecBuilder()
          .withSecurityContext(new PodSecurityContextBuilder().withRunAsUser(42L).build())
          .build();
  podSpec1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());

  PodSpec podSpec2 =
      new PodSpecBuilder()
          .withSecurityContext(new PodSecurityContextBuilder().withRunAsUser(42L).build())
          .build();
  podSpec2.setAdditionalProperty("add2", 2L);
  PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());

  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  PodSecurityContext sc = podTemplate.getSpec().getSecurityContext();
  assertEquals(sc.getRunAsUser(), (Long) 42L);
}
 
Example #7
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPodSecurityContextFromYaml() throws Exception {
	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), null);

	deployer = new KubernetesAppDeployer(bindDeployerProperties(), null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
Example #8
Source File: DeploymentPropertiesResolver.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
PodSecurityContext getPodSecurityContext(Map<String, String> kubernetesDeployerProperties) {
	PodSecurityContext podSecurityContext = null;

	KubernetesDeployerProperties deployerProperties = bindProperties(kubernetesDeployerProperties,
			this.propertyPrefix + ".podSecurityContext", "podSecurityContext");

	if (deployerProperties.getPodSecurityContext() != null) {
		podSecurityContext = new PodSecurityContextBuilder()
				.withRunAsUser(deployerProperties.getPodSecurityContext().getRunAsUser())
				.withFsGroup(deployerProperties.getPodSecurityContext().getFsGroup())
				.build();
	}
	else {
		String runAsUser = PropertyParserUtils.getDeploymentPropertyValue(kubernetesDeployerProperties,
				this.propertyPrefix + ".podSecurityContext.runAsUser");

		String fsGroup = PropertyParserUtils.getDeploymentPropertyValue(kubernetesDeployerProperties,
				this.propertyPrefix + ".podSecurityContext.fsGroup");

		if (!StringUtils.isEmpty(runAsUser) && !StringUtils.isEmpty(fsGroup)) {
			podSecurityContext = new PodSecurityContextBuilder()
					.withRunAsUser(Long.valueOf(runAsUser))
					.withFsGroup(Long.valueOf(fsGroup))
					.build();
		}
		else if (this.properties.getPodSecurityContext() != null) {
			podSecurityContext = new PodSecurityContextBuilder()
					.withRunAsUser(this.properties.getPodSecurityContext().getRunAsUser())
					.withFsGroup(this.properties.getPodSecurityContext().getFsGroup())
					.build();
		}
	}

	return podSecurityContext;
}
 
Example #9
Source File: SecurityContextProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvisionSecurityContextIfItIsConfigured() throws Exception {
  // given
  securityContextProvisioner = new SecurityContextProvisioner("1", "2");

  // when
  securityContextProvisioner.provision(kubernetesEnvironment, runtimeIdentity);

  // then
  PodSecurityContext securityContext = pod.getSpec().getSecurityContext();
  assertNotNull(securityContext);

  assertEquals(securityContext.getRunAsUser(), new Long(1));
  assertEquals(securityContext.getFsGroup(), new Long(2));
}
 
Example #10
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
protected StatefulSet createStatefulSet(
        Map<String, String> stsAnnotations,
        Map<String, String> podAnnotations,
        List<Volume> volumes,
        List<PersistentVolumeClaim> volumeClaims,
        Affinity affinity,
        List<Container> initContainers,
        List<Container> containers,
        List<LocalObjectReference> imagePullSecrets,
        boolean isOpenShift) {

    PodSecurityContext securityContext = templateSecurityContext;

    // if a persistent volume claim is requested and the running cluster is a Kubernetes one (non-openshift) and we
    // have no user configured PodSecurityContext we set the podSecurityContext.
    // This is to give each pod write permissions under a specific group so that if a pod changes users it does not have permission issues.
    if (ModelUtils.containsPersistentStorage(storage) && !isOpenShift && securityContext == null) {
        securityContext = new PodSecurityContextBuilder()
                .withFsGroup(AbstractModel.DEFAULT_FS_GROUPID)
                .build();
    }

    StatefulSet statefulSet = new StatefulSetBuilder()
            .withNewMetadata()
                .withName(name)
                .withLabels(getLabelsWithStrimziName(name, templateStatefulSetLabels).toMap())
                .withNamespace(namespace)
                .withAnnotations(mergeLabelsOrAnnotations(stsAnnotations, templateStatefulSetAnnotations))
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withPodManagementPolicy(templatePodManagementPolicy.toValue())
                .withUpdateStrategy(new StatefulSetUpdateStrategyBuilder().withType("OnDelete").build())
                .withSelector(new LabelSelectorBuilder().withMatchLabels(getSelectorLabels().toMap()).build())
                .withServiceName(headlessServiceName)
                .withReplicas(replicas)
                .withNewTemplate()
                    .withNewMetadata()
                        .withName(name)
                        .withLabels(getLabelsWithStrimziName(name, templatePodLabels).toMap())
                        .withAnnotations(mergeLabelsOrAnnotations(podAnnotations, templatePodAnnotations))
                    .endMetadata()
                    .withNewSpec()
                        .withServiceAccountName(getServiceAccountName())
                        .withAffinity(affinity)
                        .withInitContainers(initContainers)
                        .withContainers(containers)
                        .withVolumes(volumes)
                        .withTolerations(getTolerations())
                        .withTerminationGracePeriodSeconds(Long.valueOf(templateTerminationGracePeriodSeconds))
                        .withImagePullSecrets(templateImagePullSecrets != null ? templateImagePullSecrets : imagePullSecrets)
                        .withSecurityContext(securityContext)
                        .withPriorityClassName(templatePodPriorityClassName)
                        .withSchedulerName(templatePodSchedulerName != null ? templatePodSchedulerName : "default-scheduler")
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(volumeClaims)
            .endSpec()
            .build();

    return statefulSet;
}
 
Example #11
Source File: PodTemplateBuilderTest.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Test
@TestCaseName("{method}(directConnection={0})")
@Parameters({ "true", "false" })
public void testBuildFromTemplate(boolean directConnection) throws Exception {
    cloud.setDirectConnection(directConnection);
    PodTemplate template = new PodTemplate();
    template.setRunAsUser("1000");
    template.setRunAsGroup("1000");
    template.setSupplementalGroups("5001,5002");

    template.setHostNetwork(false);

    List<PodVolume> volumes = new ArrayList<PodVolume>();
    volumes.add(new HostPathVolume("/host/data", "/container/data"));
    volumes.add(new EmptyDirVolume("/empty/dir", false));
    template.setVolumes(volumes);

    List<ContainerTemplate> containers = new ArrayList<ContainerTemplate>();
    ContainerTemplate busyboxContainer = new ContainerTemplate("busybox", "busybox");
    busyboxContainer.setCommand("cat");
    busyboxContainer.setTtyEnabled(true);
    List<TemplateEnvVar> envVars = new ArrayList<TemplateEnvVar>();
    envVars.add(new KeyValueEnvVar("CONTAINER_ENV_VAR", "container-env-var-value"));
    busyboxContainer.setEnvVars(envVars);
    busyboxContainer.setRunAsUser("2000");
    busyboxContainer.setRunAsGroup("2000");
    containers.add(busyboxContainer);
    template.setContainers(containers);

    setupStubs();
    Pod pod = new PodTemplateBuilder(template).withSlave(slave).build();
    pod.getMetadata().setLabels(ImmutableMap.of("some-label","some-label-value"));
    validatePod(pod, false, directConnection);
    ArrayList<Long> supplementalGroups = new ArrayList<Long>();
    supplementalGroups.add(5001L);
    supplementalGroups.add(5002L);

    Map<String, Container> containersMap = toContainerMap(pod);
    PodSecurityContext securityContext = pod.getSpec().getSecurityContext();
    assertEquals(Long.valueOf(1000L), securityContext.getRunAsUser());
    assertEquals(Long.valueOf(1000L), securityContext.getRunAsGroup());
    assertEquals(supplementalGroups, securityContext.getSupplementalGroups());
    assertEquals(Long.valueOf(2000L), containersMap.get("busybox").getSecurityContext().getRunAsUser());
    assertEquals(Long.valueOf(2000L), containersMap.get("busybox").getSecurityContext().getRunAsGroup());
}
 
Example #12
Source File: PodMerger.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
private PodSecurityContext mergeSecurityContexts(
    @Nullable PodSecurityContext a, @Nullable PodSecurityContext b) throws ValidationException {
  return nonNullOrEqual(a, b, "Cannot merge pods with different security contexts: %s, %s");
}
 
Example #13
Source File: AuthenticationServiceSpecStandard.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public void setSecurityContext(PodSecurityContext securityContext) {
    this.securityContext = securityContext;
}
 
Example #14
Source File: AuthenticationServiceSpecStandard.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public PodSecurityContext getSecurityContext() {
    return securityContext;
}
 
Example #15
Source File: PodTemplate.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public void setSecurityContext(PodSecurityContext securityContext) {
    this.securityContext = securityContext;
}
 
Example #16
Source File: PodTemplate.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Description("Configures pod-level security attributes and common container settings.")
@KubeLink(group = "core", version = "v1", kind = "podsecuritycontext")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public PodSecurityContext getSecurityContext() {
    return securityContext;
}
 
Example #17
Source File: AbstractKubernetesDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 4 votes vote down vote up
/**
 * Create PodSpec for the given {@link AppDeploymentRequest}

 * @param appDeploymentRequest the app deployment request to use to create the PodSpec
 * @return the PodSpec
 */
PodSpec createPodSpec(AppDeploymentRequest appDeploymentRequest) {

	String appId = createDeploymentId(appDeploymentRequest);

	Map<String, String>  deploymentProperties = (appDeploymentRequest instanceof ScheduleRequest) ?
			((ScheduleRequest) appDeploymentRequest).getSchedulerProperties() : appDeploymentRequest.getDeploymentProperties();

	PodSpecBuilder podSpec = new PodSpecBuilder();

	String imagePullSecret = this.deploymentPropertiesResolver.getImagePullSecret(deploymentProperties);

	if (imagePullSecret != null) {
		podSpec.addNewImagePullSecret(imagePullSecret);
	}

	boolean hostNetwork = this.deploymentPropertiesResolver.getHostNetwork(deploymentProperties);

	ContainerConfiguration containerConfiguration = new ContainerConfiguration(appId, appDeploymentRequest)
			.withProbeCredentialsSecret(getProbeCredentialsSecret(deploymentProperties))
			.withHostNetwork(hostNetwork);

	if (KubernetesAppDeployer.class.isAssignableFrom(this.getClass())) {
		containerConfiguration.withExternalPort(getExternalPort(appDeploymentRequest));
	}

	Container container = containerFactory.create(containerConfiguration);

	// add memory and cpu resource limits
	ResourceRequirements req = new ResourceRequirements();
	req.setLimits(this.deploymentPropertiesResolver.deduceResourceLimits(deploymentProperties));
	req.setRequests(this.deploymentPropertiesResolver.deduceResourceRequests(deploymentProperties));
	container.setResources(req);
	ImagePullPolicy pullPolicy = this.deploymentPropertiesResolver.deduceImagePullPolicy(deploymentProperties);
	container.setImagePullPolicy(pullPolicy.name());

	Map<String, String> nodeSelectors = this.deploymentPropertiesResolver.getNodeSelectors(deploymentProperties);
	if (nodeSelectors.size() > 0) {
		podSpec.withNodeSelector(nodeSelectors);
	}

	podSpec.withTolerations(this.deploymentPropertiesResolver.getTolerations(deploymentProperties));

	// only add volumes with corresponding volume mounts
	podSpec.withVolumes(this.deploymentPropertiesResolver.getVolumes(deploymentProperties).stream()
			.filter(volume -> container.getVolumeMounts().stream()
					.anyMatch(volumeMount -> volumeMount.getName().equals(volume.getName())))
			.collect(Collectors.toList()));

	if (hostNetwork) {
		podSpec.withHostNetwork(true);
	}
	podSpec.addToContainers(container);

	podSpec.withRestartPolicy(this.deploymentPropertiesResolver.getRestartPolicy(deploymentProperties).name());

	String deploymentServiceAcccountName = this.deploymentPropertiesResolver.getDeploymentServiceAccountName(deploymentProperties);

	if (deploymentServiceAcccountName != null) {
		podSpec.withServiceAccountName(deploymentServiceAcccountName);
	}

	PodSecurityContext podSecurityContext = this.deploymentPropertiesResolver.getPodSecurityContext(deploymentProperties);
	if (podSecurityContext != null) {
		podSpec.withSecurityContext(podSecurityContext);
	}

	Affinity affinity = this.deploymentPropertiesResolver.getAffinityRules(deploymentProperties);
	// Make sure there is at least some rule.
	if (affinity.getNodeAffinity() != null
			|| affinity.getPodAffinity() != null
			|| affinity.getPodAntiAffinity() != null) {
		podSpec.withAffinity(affinity);
	}

	Container initContainer = this.deploymentPropertiesResolver.getInitContainer(deploymentProperties);
	if (initContainer != null) {
		podSpec.addToInitContainers(initContainer);
	}

	return podSpec.build();
}