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