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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/krateoplatformops/snowplow
go 1.24.2

require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc
github.com/google/go-cmp v0.7.0
github.com/itchyny/gojq v0.12.17
github.com/krateoplatformops/plumbing v0.6.2
Expand All @@ -27,7 +28,6 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/blang/semver/v4 v4.0.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/evanphx/json-patch/v5 v5.9.11 // indirect
github.com/fatih/color v1.18.0 // indirect
Expand Down
28 changes: 0 additions & 28 deletions internal/resolvers/crds/schema/extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import (

"github.com/krateoplatformops/plumbing/maps"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/yaml"
)

func extractOpenAPISchemaFromCRD(crd map[string]any, version string) (*apiextensions.CustomResourceValidation, error) {
Expand Down Expand Up @@ -65,29 +63,3 @@ func dumpSchemaRecursively(s *apiextensions.JSONSchemaProps, prefix string) {
}
}
*/

func buildValidationFromSchemaData(data map[string]interface{}) (*apiextensions.CustomResourceValidation, error) {
// 1. From map to v1.JSONSchemaProps via YAML
yml, err := yaml.Marshal(data)
if err != nil {
return nil, fmt.Errorf("marshal to YAML: %w", err)
}
var schemaV1 apiextv1.JSONSchemaProps
if err := yaml.Unmarshal(yml, &schemaV1); err != nil {
return nil, fmt.Errorf("unmarshal to v1 JSONSchemaProps: %w", err)
}

// 2. From v1.JSONSchemaProps to internal JSONSchemaProps
var schemaInternal apiextensions.JSONSchemaProps
if err := apiextv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(
&schemaV1, &schemaInternal, nil); err != nil {
return nil, fmt.Errorf("convert v1→internal: %w", err)
}

// 3. Dump for debug (to be removed ASAP)
//dumpSchemaRecursively(&schemaInternal, "")

return &apiextensions.CustomResourceValidation{
OpenAPIV3Schema: &schemaInternal,
}, nil
}
59 changes: 59 additions & 0 deletions internal/resolvers/crds/schema/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,70 @@ package schema

import (
"errors"
"fmt"

apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apiextensions-apiserver/pkg/apiserver/validation"
"sigs.k8s.io/yaml"
)

func buildValidationFromSchemaData(data map[string]any) (*apiextensions.CustomResourceValidation, error) {
// 1. Set additionalProperties=false
enforceStrictObjects(data)

// 2. From map to YAML
yml, err := yaml.Marshal(data)
if err != nil {
return nil, fmt.Errorf("marshal to YAML: %w", err)
}

var schemaV1 apiextv1.JSONSchemaProps
if err := yaml.Unmarshal(yml, &schemaV1); err != nil {
return nil, fmt.Errorf("unmarshal to v1 JSONSchemaProps: %w", err)
}

// 3. From v1.JSONSchemaProps to internal JSONSchemaProps
var schemaInternal apiextensions.JSONSchemaProps
if err := apiextv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(
&schemaV1, &schemaInternal, nil); err != nil {
return nil, fmt.Errorf("convert v1→internal: %w", err)
}

return &apiextensions.CustomResourceValidation{
OpenAPIV3Schema: &schemaInternal,
}, nil
}

// enforceStrictObjects set additionalProperties=false on all nodes (type: object)
func enforceStrictObjects(node map[string]any) {
if nodeType, ok := node["type"].(string); ok && nodeType == "object" {
if _, exists := node["additionalProperties"]; !exists {
node["additionalProperties"] = false
}
}

// Recursion for properties
if props, ok := node["properties"].(map[string]any); ok {
for _, v := range props {
if child, ok := v.(map[string]any); ok {
enforceStrictObjects(child)
}
}
}

// Recursion for items (array)
if items, ok := node["items"].(map[string]any); ok {
enforceStrictObjects(items)
} else if itemsSlice, ok := node["items"].([]any); ok {
for _, it := range itemsSlice {
if child, ok := it.(map[string]any); ok {
enforceStrictObjects(child)
}
}
}
}

func validateCustomResource(crv *apiextensions.CustomResourceValidation, doc map[string]any) error {
validator, _, err := validation.NewSchemaValidator(crv.OpenAPIV3Schema)
if err != nil {
Expand Down
12 changes: 7 additions & 5 deletions internal/resolvers/crds/schema/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"testing"

"github.com/davecgh/go-spew/spew"
"github.com/stretchr/testify/assert"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
"sigs.k8s.io/yaml"
Expand Down Expand Up @@ -42,8 +43,8 @@ func TestValidate(t *testing.T) {
})
}

func TestValidateIssue(t *testing.T) {
data, err := os.ReadFile("../../../../testdata/issues/validation/sample-schema.yaml")
func TestValidateMissingAdditionalPropertiesOnObjectIssue(t *testing.T) {
data, err := os.ReadFile("../../../../testdata/missing-additional-props/table.crd.yaml")
assert.NoError(t, err)

var crd map[string]any
Expand All @@ -53,20 +54,21 @@ func TestValidateIssue(t *testing.T) {
schema, err := extractOpenAPISchemaFromCRD(crd, "v1beta1")
assert.NoError(t, err)

doc, err := os.ReadFile("../../../../testdata/issues/validation/sample-cr.json")
doc, err := os.ReadFile("../../../../testdata/missing-additional-props/table.json")
assert.NoError(t, err)

var jsonObj map[string]any
err = json.Unmarshal(doc, &jsonObj)
assert.NoError(t, err)

tmp, ok := jsonObj["status"].(map[string]any)
assert.True(t, ok, "status should be map[string]any")
tmp, ok := jsonObj["spec"].(map[string]any)
assert.True(t, ok, "spec should be map[string]any")

tmp, ok = tmp["widgetData"].(map[string]any)
assert.True(t, ok, "widgetData should be map[string]any")
//spew.Dump(tmp)

err = validateCustomResource(schema, tmp)
assert.Error(t, err)
spew.Dump(err)
}
204 changes: 204 additions & 0 deletions testdata/missing-additional-props/table.crd.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
controller-gen.kubebuilder.io/version: v0.18.0
name: tables.widgets.templates.krateo.io
spec:
group: widgets.templates.krateo.io
names:
categories:
- widgets
- krateo
kind: Table
listKind: TableList
plural: tables
singular: table
scope: Namespaced
versions:
- additionalPrinterColumns:
- jsonPath: .metadata.creationTimestamp
name: AGE
type: date
- jsonPath: .status.conditions[?(@.type=='Ready')].status
name: READY
type: string
name: v1beta1
schema:
openAPIV3Schema:
properties:
apiVersion:
description: |-
APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
type: string
kind:
description: |-
Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated.
In CamelCase.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
type: string
spec:
properties:
apiRef:
properties:
name:
type: string
namespace:
type: string
required:
- name
- namespace
type: object
resourcesRefs:
properties:
_slice_:
properties:
continue:
type: boolean
offset:
type: integer
page:
type: integer
perPage:
type: integer
required:
- page
- perPage
type: object
items:
items:
properties:
apiVersion:
type: string
id:
type: string
name:
type: string
namespace:
type: string
payload:
type: object
resource:
type: string
verb:
enum:
- POST
- PUT
- PATCH
- DELETE
- GET
type: string
required:
- id
type: object
type: array
required:
- items
type: object
resourcesRefsTemplate:
items:
properties:
iterator:
type: string
template:
properties:
apiVersion:
type: string
id:
type: string
name:
type: string
namespace:
type: string
payload:
type: object
x-kubernetes-preserve-unknown-fields: true
resource:
type: string
verb:
enum:
- POST
- PUT
- PATCH
- DELETE
- GET
type: string
type: object
type: object
type: array
widgetData:
properties:
columns:
description: configuration of the table's columns
items:
properties:
color:
description: the color of the value (or the icon) to be
represented
enum:
- blue
- darkBlue
- orange
- gray
- red
- green
type: string
kind:
description: type of data to be represented
enum:
- value
- icon
type: string
title:
description: column header label
type: string
valueKey:
description: key used to extract the value from row data
type: string
required:
- title
- valueKey
type: object
type: array
data:
description: array of objects representing the table's row data
items:
type: object
#x-kubernetes-preserve-unknown-fields: true
type: array
pageSize:
description: number of rows displayed per page
type: integer
prefix:
description: it's the filters prefix to get right values
type: string
required:
- columns
- data
type: object
widgetDataTemplate:
items:
properties:
expression:
type: string
forPath:
type: string
type: object
type: array
required:
- widgetData
type: object
status:
type: object
x-kubernetes-preserve-unknown-fields: true
type: object
served: true
storage: true
subresources:
status: {}
Loading
Loading