Search in sources :

Example 51 with ValidationFailed

use of io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed in project stackgres by ongres.

the class ValidationResourceTest method givenAnInvalidAdmissionReview_itShouldReturnAFailedResponse.

@Test
void givenAnInvalidAdmissionReview_itShouldReturnAFailedResponse() throws ValidationFailed {
    doThrow(new ValidationFailed("validation failed")).when(pipeline).validate(review);
    AdmissionReviewResponse response = resource.validate(review);
    assertFalse(response.getResponse().isAllowed());
    assertEquals("validation failed", response.getResponse().getStatus().getMessage());
    verify(pipeline).validate(review);
}
Also used : AdmissionReviewResponse(io.stackgres.operatorframework.admissionwebhook.AdmissionReviewResponse) ValidationFailed(io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed) Test(org.junit.jupiter.api.Test)

Example 52 with ValidationFailed

use of io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed in project stackgres by ongres.

the class BackupConfigConstraintValidationTest method givenStorageClass_shouldFail.

@ParameterizedTest
@ValueSource(strings = { "DEMO", "STANDARDIA", "reduced_redundancy" })
void givenStorageClass_shouldFail(String storageClass) {
    BackupConfigReview review = JsonUtil.readFromJson("backupconfig_allow_request/update.json", BackupConfigReview.class);
    review.getRequest().getObject().getSpec().getStorage().getS3Compatible().setStorageClass(storageClass);
    ValidationFailed ex = assertThrows(ValidationFailed.class, () -> {
        validator.validate(review);
    });
    String errorMessage = ex.getResult().getMessage();
    assertEquals("SGBackupConfig has invalid properties. " + "storageClass must be one of STANDARD, STANDARD_IA or REDUCED_REDUNDANCY.", errorMessage);
}
Also used : ValidationFailed(io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed) BackupConfigReview(io.stackgres.operator.common.BackupConfigReview) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 53 with ValidationFailed

use of io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed in project stackgres by ongres.

the class DbOpsSecurityUpgradeValidatorTest method givenInvalidStackGresVersionOnCreation_shouldFail.

@Test
void givenInvalidStackGresVersionOnCreation_shouldFail() {
    final StackGresDbOpsReview review = getCreationReview();
    String sgcluster = review.getRequest().getObject().getSpec().getSgCluster();
    String namespace = review.getRequest().getObject().getMetadata().getNamespace();
    cluster.getSpec().getPostgres().setVersion("11.11");
    when(clusterFinder.findByNameAndNamespace(sgcluster, namespace)).thenReturn(Optional.of(cluster));
    ValidationFailed ex = assertThrows(ValidationFailed.class, () -> {
        validator.validate(review);
    });
    String resultMessage = ex.getMessage();
    assertEquals("Major version upgrade must be performed on StackGresCluster before performing" + " the upgrade since Postgres version 11.11 will not be" + " supported after the upgrade is completed", resultMessage);
}
Also used : StackGresDbOpsReview(io.stackgres.operator.common.StackGresDbOpsReview) ValidationFailed(io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed) Test(org.junit.jupiter.api.Test)

Example 54 with ValidationFailed

use of io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed in project stackgres by ongres.

the class PostgresConfigValidator method validate.

@Override
public void validate(StackGresClusterReview review) throws ValidationFailed {
    StackGresCluster cluster = review.getRequest().getObject();
    if (cluster == null) {
        return;
    }
    String givenPgVersion = cluster.getSpec().getPostgres().getVersion();
    String pgConfig = cluster.getSpec().getConfiguration().getPostgresConfig();
    checkIfProvided(givenPgVersion, "postgres version");
    checkIfProvided(pgConfig, "sgPostgresConfig");
    if (givenPgVersion != null && !isPostgresVersionSupported(givenPgVersion)) {
        final String message = "Unsupported postgres version " + givenPgVersion + ".  Supported postgres versions are: " + StackGresComponent.POSTGRESQL.getOrderedVersions().toString(", ");
        fail(errorPostgresMismatchUri, message);
    }
    String givenMajorVersion = StackGresComponent.POSTGRESQL.findMajorVersion(givenPgVersion);
    String namespace = cluster.getMetadata().getNamespace();
    switch(review.getRequest().getOperation()) {
        case CREATE:
            validateAgainstConfiguration(givenMajorVersion, pgConfig, namespace);
            break;
        case UPDATE:
            StackGresCluster oldCluster = review.getRequest().getOldObject();
            String oldPgConfig = oldCluster.getSpec().getConfiguration().getPostgresConfig();
            if (!oldPgConfig.equals(pgConfig)) {
                validateAgainstConfiguration(givenMajorVersion, pgConfig, namespace);
            }
            long givenMajorVersionIndex = StackGresComponent.POSTGRESQL.getOrderedMajorVersions().zipWithIndex().filter(t -> t.v1.equals(givenMajorVersion)).map(Tuple2::v2).findAny().get();
            String oldPgVersion = oldCluster.getSpec().getPostgres().getVersion();
            String oldMajorVersion = StackGresComponent.POSTGRESQL.findMajorVersion(oldPgVersion);
            long oldMajorVersionIndex = StackGresComponent.POSTGRESQL.getOrderedMajorVersions().zipWithIndex().filter(t -> t.v1.equals(oldMajorVersion)).map(Tuple2::v2).findAny().get();
            if (givenMajorVersionIndex > oldMajorVersionIndex) {
                fail(errorForbiddenUpdateUri, "postgres version can not be changed to a previous major version");
            }
            break;
        default:
    }
}
Also used : StackGresClusterReview(io.stackgres.operator.common.StackGresClusterReview) StackGresCluster(io.stackgres.common.crd.sgcluster.StackGresCluster) ValidationType(io.stackgres.operator.validation.ValidationType) Singleton(javax.inject.Singleton) StackGresPostgresConfig(io.stackgres.common.crd.sgpgconfig.StackGresPostgresConfig) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ValidationFailed(io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed) StackGresComponent(io.stackgres.common.StackGresComponent) List(java.util.List) Tuple2(org.jooq.lambda.tuple.Tuple2) ErrorType(io.stackgres.common.ErrorType) Optional(java.util.Optional) CustomResourceFinder(io.stackgres.common.resource.CustomResourceFinder) StackGresCluster(io.stackgres.common.crd.sgcluster.StackGresCluster) Tuple2(org.jooq.lambda.tuple.Tuple2)

Example 55 with ValidationFailed

use of io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed in project stackgres by ongres.

the class ConstraintValidator method validate.

@Override
public void validate(T review) throws ValidationFailed {
    final HasMetadata target = review.getRequest().getObject();
    if (target != null) {
        if (StackGresCluster.KIND.equals(target.getKind())) {
            try {
                // Names must not be longer than valid labels.
                Preconditions.checkArgument(target.getMetadata().getName().length() <= 53, "Valid name must be 53 characters or less");
                ResourceUtil.resourceName(target.getMetadata().getName());
            } catch (IllegalArgumentException e) {
                Status status = new StatusBuilder().withCode(422).withMessage(e.getMessage()).withKind(target.getKind()).withReason(constraintViolationDocumentationUri).build();
                throw new ValidationFailed(status);
            }
        }
        Set<ConstraintViolation<Object>> violations = constraintValidator.validate(target);
        if (!violations.isEmpty()) {
            StatusDetailsBuilder detailsBuilder = new StatusDetailsBuilder();
            violations.forEach(violation -> {
                final List<String> fields = getOffendingFields(violation);
                final String reason = violation.getConstraintDescriptor().getAnnotation().annotationType().getName();
                fields.forEach(field -> detailsBuilder.addNewCause(field, violation.getMessage(), reason));
            });
            if (violations.stream().map(this::getOffendingFields).flatMap(List::stream).count() == 1) {
                violations.forEach(violation -> detailsBuilder.withName(getOffendingFields(violation).get(0)));
            }
            StatusDetails details = detailsBuilder.build();
            Status status = new StatusBuilder().withCode(422).withMessage(target.getKind() + " has invalid properties. " + details.getCauses().get(0).getMessage()).withKind(target.getKind()).withReason(constraintViolationDocumentationUri).withDetails(details).build();
            throw new ValidationFailed(status);
        }
    }
}
Also used : Status(io.fabric8.kubernetes.api.model.Status) StatusDetailsBuilder(io.fabric8.kubernetes.api.model.StatusDetailsBuilder) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ValidationFailed(io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed) ConstraintViolation(javax.validation.ConstraintViolation) StatusDetails(io.fabric8.kubernetes.api.model.StatusDetails) StatusBuilder(io.fabric8.kubernetes.api.model.StatusBuilder) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Aggregations

ValidationFailed (io.stackgres.operatorframework.admissionwebhook.validating.ValidationFailed)61 Test (org.junit.jupiter.api.Test)46 StackGresClusterReview (io.stackgres.operator.common.StackGresClusterReview)24 BackupConfigReview (io.stackgres.operator.common.BackupConfigReview)17 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)15 SecretBuilder (io.fabric8.kubernetes.api.model.SecretBuilder)10 StackGresClusterSpec (io.stackgres.common.crd.sgcluster.StackGresClusterSpec)5 Status (io.fabric8.kubernetes.api.model.Status)4 StackGresPostgresConfig (io.stackgres.common.crd.sgpgconfig.StackGresPostgresConfig)4 StatusBuilder (io.fabric8.kubernetes.api.model.StatusBuilder)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3 ValueSource (org.junit.jupiter.params.provider.ValueSource)3 StatusDetailsBuilder (io.fabric8.kubernetes.api.model.StatusDetailsBuilder)2 StackGresCluster (io.stackgres.common.crd.sgcluster.StackGresCluster)2 PgConfigReview (io.stackgres.operator.common.PgConfigReview)2 StackGresDbOpsReview (io.stackgres.operator.common.StackGresDbOpsReview)2 Operation (io.stackgres.operatorframework.admissionwebhook.Operation)2 List (java.util.List)2 ImmutableList (com.google.common.collect.ImmutableList)1 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)1