|
| 1 | +package bundle |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/invopop/jsonschema" |
| 10 | + schemavalidation "github.com/santhosh-tekuri/jsonschema/v6" |
| 11 | + "github.com/santhosh-tekuri/jsonschema/v6/kind" |
| 12 | + "k8s.io/apimachinery/pkg/util/sets" |
| 13 | + "k8s.io/apimachinery/pkg/util/validation" |
| 14 | + |
| 15 | + "github.com/operator-framework/api/pkg/operators/v1alpha1" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + dns1123SubdomainFormat = "RFC-1123" |
| 20 | + |
| 21 | + // the format name is injected into the error |
| 22 | + notOwnNamespaceFormat = "watchNamespace" |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + // unsupportedInstallModes set of unsupported ClusterServiceVersion install modes |
| 27 | + unsupportedInstallModes = sets.New[v1alpha1.InstallModeType](v1alpha1.InstallModeTypeMultiNamespace) |
| 28 | + |
| 29 | + // dnsFormat checks conformity to RFC1213 lowercase dns subdomain format by any field with format 'RFC-1123' |
| 30 | + dnsFormat = &schemavalidation.Format{ |
| 31 | + Name: dns1123SubdomainFormat, |
| 32 | + Validate: func(v any) error { |
| 33 | + if v == nil { |
| 34 | + return nil |
| 35 | + } |
| 36 | + s, ok := v.(string) |
| 37 | + if !ok { |
| 38 | + return fmt.Errorf("invalid type %T, expected string", v) |
| 39 | + } |
| 40 | + errs := validation.IsDNS1123Subdomain(s) |
| 41 | + if len(errs) > 0 { |
| 42 | + return fmt.Errorf("%q is not a valid namespace name: %s", v, strings.Join(errs, ", ")) |
| 43 | + } |
| 44 | + return nil |
| 45 | + }, |
| 46 | + } |
| 47 | +) |
| 48 | + |
| 49 | +// Config is a registry+v1 bundle configuration surface |
| 50 | +type Config struct { |
| 51 | + // WatchNamespace is supported for certain bundles to allow the user to configure installation in Single- or OwnNamespace modes |
| 52 | + // The validation behavior of this field is determined by the install modes supported by the bundle, e.g.: |
| 53 | + // - If a bundle only supports AllNamespaces mode (or only OwnNamespace mode): this field will be unknown |
| 54 | + // - If a bundle supports AllNamespaces and SingleNamespace install modes: this field is optional |
| 55 | + // - If a bundle supports AllNamespaces and OwnNamespace: this field is optional, but if set must be equal to the install namespace |
| 56 | + WatchNamespace string `json:"watchNamespace,omitempty"` |
| 57 | +} |
| 58 | + |
| 59 | +// ValidatedBundleConfigFromRaw returns a validated Config struct from the values given in rawConfig. |
| 60 | +// The applied validation will be determined by the install modes supported by the bundle |
| 61 | +func ValidatedBundleConfigFromRaw(rv1 RegistryV1, installNamespace string, rawConfig map[string]interface{}) (*Config, error) { |
| 62 | + if len(rawConfig) == 0 { |
| 63 | + return nil, nil |
| 64 | + } |
| 65 | + |
| 66 | + rawSchema := bundleConfigSchema(rv1, installNamespace) |
| 67 | + customFormats := []*schemavalidation.Format{ |
| 68 | + dnsFormat, |
| 69 | + notOwnNamespaceFmt(installNamespace), |
| 70 | + } |
| 71 | + |
| 72 | + if err := validateBundleConfig(rawSchema, customFormats, rawConfig); err != nil { |
| 73 | + return nil, fmt.Errorf("invalid configuration: %v", err) |
| 74 | + } |
| 75 | + |
| 76 | + return toConfig(rawConfig) |
| 77 | +} |
| 78 | + |
| 79 | +// bundleConfigSchema generates a jsonschema used to validate bundle configuration |
| 80 | +func bundleConfigSchema(rv1 RegistryV1, installNamespace string) []byte { |
| 81 | + // configure reflector |
| 82 | + r := new(jsonschema.Reflector) |
| 83 | + r.ExpandedStruct = true |
| 84 | + r.AllowAdditionalProperties = false |
| 85 | + |
| 86 | + // generate base schema |
| 87 | + schema := r.Reflect(&Config{}) |
| 88 | + |
| 89 | + // apply bundle rawConfig based mutations for watchNamespace |
| 90 | + configureWatchNamespaceProperty(rv1, installNamespace, schema) |
| 91 | + |
| 92 | + // return schema |
| 93 | + out, err := schema.MarshalJSON() |
| 94 | + if err != nil { |
| 95 | + panic(err) |
| 96 | + } |
| 97 | + return out |
| 98 | +} |
| 99 | + |
| 100 | +// configureWatchNamespaceProperty modifies schema to configure the watchNamespace config property based on |
| 101 | +// the install modes supported by the bundle marking the field required or optional, or restricting the possible values |
| 102 | +// it can take |
| 103 | +func configureWatchNamespaceProperty(rv1 RegistryV1, installNamespace string, schema *jsonschema.Schema) { |
| 104 | + supportedInstallModes := sets.New[v1alpha1.InstallModeType]() |
| 105 | + for _, im := range rv1.CSV.Spec.InstallModes { |
| 106 | + if im.Supported && !unsupportedInstallModes.Has(im.Type) { |
| 107 | + supportedInstallModes.Insert(im.Type) |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + allSupported := supportedInstallModes.Has(v1alpha1.InstallModeTypeAllNamespaces) |
| 112 | + singleSupported := supportedInstallModes.Has(v1alpha1.InstallModeTypeSingleNamespace) |
| 113 | + ownSupported := supportedInstallModes.Has(v1alpha1.InstallModeTypeOwnNamespace) |
| 114 | + |
| 115 | + if len(supportedInstallModes) == 0 { |
| 116 | + panic("bundle does not support any supported install modes") |
| 117 | + } |
| 118 | + |
| 119 | + // no watchNamespace rawConfig parameter if bundle only supports AllNamespaces or OwnNamespace install modes |
| 120 | + if len(supportedInstallModes) == 1 && (allSupported || ownSupported) { |
| 121 | + schema.Properties.Delete("watchNamespace") |
| 122 | + return |
| 123 | + } |
| 124 | + |
| 125 | + watchNamespaceProperty, ok := schema.Properties.Get("watchNamespace") |
| 126 | + if !ok { |
| 127 | + panic("watchNamespace not found in schema") |
| 128 | + } |
| 129 | + |
| 130 | + watchNamespaceProperty.Format = dns1123SubdomainFormat |
| 131 | + |
| 132 | + // required or optional |
| 133 | + if !allSupported && singleSupported { |
| 134 | + schema.Required = append(schema.Required, "watchNamespace") |
| 135 | + } else { |
| 136 | + // note: the library currently doesn't support jsonschema.Types |
| 137 | + // this is the current workaround for declaring optional/nullable fields |
| 138 | + // https://github.com/invopop/jsonschema/issues/115 |
| 139 | + watchNamespaceProperty.Extras = map[string]any{ |
| 140 | + "type": []string{"string", "null"}, |
| 141 | + } |
| 142 | + if !ownSupported { |
| 143 | + // if own namespace is not supported validate that it is not being used |
| 144 | + watchNamespaceProperty.Format = notOwnNamespaceFormat |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + // must be the install namespace |
| 149 | + if allSupported && ownSupported && !singleSupported { |
| 150 | + watchNamespaceProperty.Enum = []any{ |
| 151 | + installNamespace, |
| 152 | + nil, |
| 153 | + } |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +// validateBundleConfig validates the bundle rawConfig |
| 158 | +func validateBundleConfig(rawSchema []byte, customFormats []*schemavalidation.Format, rawConfig map[string]interface{}) error { |
| 159 | + schema, err := schemavalidation.UnmarshalJSON(strings.NewReader(string(rawSchema))) |
| 160 | + if err != nil { |
| 161 | + return err |
| 162 | + } |
| 163 | + |
| 164 | + compiler := schemavalidation.NewCompiler() |
| 165 | + for _, format := range customFormats { |
| 166 | + compiler.RegisterFormat(format) |
| 167 | + } |
| 168 | + compiler.AssertFormat() |
| 169 | + if err := compiler.AddResource("schema.json", schema); err != nil { |
| 170 | + return err |
| 171 | + } |
| 172 | + compiledSchema, err := compiler.Compile("schema.json") |
| 173 | + if err != nil { |
| 174 | + return err |
| 175 | + } |
| 176 | + |
| 177 | + return formatJSONSchemaValidationError(compiledSchema.Validate(rawConfig)) |
| 178 | +} |
| 179 | + |
| 180 | +// toConfig converts rawConfig into a Config struct |
| 181 | +func toConfig(rawConfig map[string]interface{}) (*Config, error) { |
| 182 | + cfg := Config{} |
| 183 | + dataBytes, err := json.Marshal(rawConfig) |
| 184 | + if err != nil { |
| 185 | + return nil, err |
| 186 | + } |
| 187 | + err = json.Unmarshal(dataBytes, &cfg) |
| 188 | + if err != nil { |
| 189 | + return nil, err |
| 190 | + } |
| 191 | + |
| 192 | + return &cfg, nil |
| 193 | +} |
| 194 | + |
| 195 | +// formatJSONSchemaValidationError extracts and formats the jsonschema validation errors given by the underlying library |
| 196 | +func formatJSONSchemaValidationError(err error) error { |
| 197 | + var validationErr *schemavalidation.ValidationError |
| 198 | + if !errors.As(err, &validationErr) { |
| 199 | + return err |
| 200 | + } |
| 201 | + var errs []error |
| 202 | + for _, cause := range validationErr.Causes { |
| 203 | + if cause == nil || cause.ErrorKind == nil { |
| 204 | + continue |
| 205 | + } |
| 206 | + |
| 207 | + var errMsg string |
| 208 | + switch e := cause.ErrorKind.(type) { |
| 209 | + case *kind.Format: |
| 210 | + errMsg = e.Err.Error() |
| 211 | + default: |
| 212 | + errMsg = cause.Error() |
| 213 | + } |
| 214 | + |
| 215 | + instanceLocation := "." + strings.Join(cause.InstanceLocation, ".") |
| 216 | + if instanceLocation == "." { |
| 217 | + errs = append(errs, fmt.Errorf("%v", errMsg)) |
| 218 | + } else { |
| 219 | + errs = append(errs, fmt.Errorf("at path %q: %s", instanceLocation, errMsg)) |
| 220 | + } |
| 221 | + } |
| 222 | + if len(errs) > 0 { |
| 223 | + return errors.Join(errs...) |
| 224 | + } |
| 225 | + return err |
| 226 | +} |
| 227 | + |
| 228 | +// notOwnNamespaceFmt returns a dynamically generated format specifically for the case where |
| 229 | +// a bundle does not support own namespace installation but a watch namespace can be optionally given |
| 230 | +func notOwnNamespaceFmt(installNamespace string) *schemavalidation.Format { |
| 231 | + return &schemavalidation.Format{ |
| 232 | + Name: notOwnNamespaceFormat, |
| 233 | + Validate: func(v any) error { |
| 234 | + if err := dnsFormat.Validate(v); err != nil { |
| 235 | + return err |
| 236 | + } |
| 237 | + if v == installNamespace { |
| 238 | + return fmt.Errorf("unsupported value %q, watchNamespace cannot be install namespace", v) |
| 239 | + } |
| 240 | + return nil |
| 241 | + }, |
| 242 | + } |
| 243 | +} |
0 commit comments