how to do open api format yaml validation, without using clusters?

Viewed 38

I have build a schema in open api format:

type Test_manifest struct {
    metav1.TypeMeta
    metav1.ObjectMeta
    Spec spec
}

type spec struct {
    Policies  []string
    Resources resources
    Results   []results
    Variables variables
}

This is not complete schema, just a part of it. And here below is the actual yaml file:

apiVersion: cli.kyverno.io/v1beta1
kind: kyvernotest
metadata:
  name: test-check-nvidia-gpus
  labels:
    foolabel: foovalue
  annotations:
    fookey: foovalue

I'm trying to validate this incoming yaml file from the user, I can convert this yaml to json and then validate the value of the fields, but I'm not getting how to validate the field itself, I mean if user write name1 rather than name then how to show error on it. Basically how to validate the key.

Here's what I've implemented for value validation:

test := "cmd/cli/kubectl-kyverno/test/test.yaml"
    yamlFile, err := ioutil.ReadFile(test)
    if err != nil {
        fmt.Printf("Error: failed to read file %v", err)
    }
    policyBytes, err1 := yaml.ToJSON(yamlFile)
    if err1 != nil {
        fmt.Printf("failed to convert to JSON")
    }
    tests := &kyvernov1.Test_manifest{}
    if err := json.Unmarshal(policyBytes, tests); err != nil {
        fmt.Printf("failed to decode yaml")
    }
    if tests.TypeMeta.APIVersion == "" {
        fmt.Printf("skipping file as tests.TypeMeta.APIVersion not found")
    }
    if tests.TypeMeta.Kind == "" {
        fmt.Printf("skipping file as tests.TypeMeta.Kind not found")
    } else if tests.TypeMeta.Kind != "KyvernoTest" {
        fmt.Printf("skipping file as tests.TypeMeta.Kind is not `KyvernoTest`")
    }

Also we want this valiadtion to happen outside the cluster.

1 Answers

Two things come to my mind:

  1. I notice that you are trying to build a k8s API extension manually which is a lot of rework, I will suggest you use a framework which will handle this for you. This is the recommended best practice that is used very frequently. It is too complicated to be done manually. Here are some resources. (kube-builder, operator-sdk). These solution are Open-API based as well. They will let you define your schema in a simple template, and generate all the validation and API + controller code for you.
  2. If you want more validation and sanity testing, typically this is done with the help of an admission controller in your cluster. It intercepts the incoming request, and before it is processed by the API server, performs actions on it. (For verification, compliance, policy enforcement, authentication etc.) You can read more about admission controllers here.
Related