Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
93 changes: 93 additions & 0 deletions pkg/dynamicrp/frontend/defaultsfilter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
Copyright 2023 The Radius Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package frontend

import (
"context"

v1 "github.com/radius-project/radius/pkg/armrpc/api/v1"
"github.com/radius-project/radius/pkg/armrpc/frontend/controller"
"github.com/radius-project/radius/pkg/armrpc/rest"
"github.com/radius-project/radius/pkg/dynamicrp/datamodel"
"github.com/radius-project/radius/pkg/schema"
"github.com/radius-project/radius/pkg/ucp/api/v20231001preview"
"github.com/radius-project/radius/pkg/ucp/ucplog"
)

// makeDefaultsFilter creates an UpdateFilter that materializes schema defaults into the resource's
// Properties before it is saved, so the stored resource, the API response and the recipe agree.
//
// oldResource is deliberately not consulted: a PUT replaces the resource, so a dropped property
// returns to its default rather than keeping its previous value.
func makeDefaultsFilter(ucpClient *v20231001preview.ClientFactory) controller.UpdateFilter[datamodel.DynamicResource] {
return func(
ctx context.Context,
newResource *datamodel.DynamicResource,
oldResource *datamodel.DynamicResource,
options *controller.Options,
) (rest.Response, error) {
return applySchemaDefaults(ctx, newResource, ucpClient)
}
}

// applySchemaDefaults fills unset properties from the "default" values declared in the resource type schema.
func applySchemaDefaults(
Comment thread
AzureMike marked this conversation as resolved.
ctx context.Context,
newResource *datamodel.DynamicResource,
ucpClient *v20231001preview.ClientFactory,
) (rest.Response, error) {
logger := ucplog.FromContextOrDiscard(ctx)
serviceCtx := v1.ARMRequestContextFromContext(ctx)

if newResource == nil {
return nil, nil
}

resourceID := serviceCtx.ResourceID.String()
resourceType := serviceCtx.ResourceID.Type()
apiVersion := serviceCtx.APIVersion

schemaData, err := schema.GetSchema(ctx, ucpClient, resourceID, resourceType, apiVersion)
if err != nil {
logger.Error(err, "Failed to fetch schema for defaults",
"resourceType", resourceType, "apiVersion", apiVersion)
return rest.NewInternalServerErrorARMResponse(v1.ErrorResponse{
Error: &v1.ErrorDetails{
Code: v1.CodeInternal,
Message: "Failed to fetch schema to apply property defaults",
},
}), nil
}

if schemaData == nil {
return nil, nil
}

// Attach the map only if something was applied, so an empty resource serializes as before.
properties := newResource.Properties
if properties == nil {
properties = map[string]any{}
}

if applied := schema.ApplyDefaults(properties, schemaData); applied > 0 {
newResource.Properties = properties
logger.V(ucplog.LevelDebug).Info("Applied schema defaults",
"count", applied, "resourceType", resourceType, "resourceID", resourceID)
}

return nil, nil
}
4 changes: 4 additions & 0 deletions pkg/dynamicrp/frontend/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,15 @@ func (s *Service) registerRoutes(
// Create encryption filter for sensitive fields
encryptionFilter := makeEncryptionFilter(ucpClient, handler)

// Materialize schema defaults before encryption, so a defaulted sensitive field is still encrypted.
defaultsFilter := makeDefaultsFilter(ucpClient)

// Resource options with encryption filter applied to PUT operations
resourceOptions := controller.ResourceOptions[datamodel.DynamicResource]{
RequestConverter: converter.DynamicResourceDataModelFromVersioned,
ResponseConverter: converter.DynamicResourceDataModelToVersioned,
UpdateFilters: []controller.UpdateFilter[datamodel.DynamicResource]{
defaultsFilter,
encryptionFilter,
},
AsyncOperationRetryAfter: time.Second * 5,
Expand Down
110 changes: 110 additions & 0 deletions pkg/schema/defaults.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
Copyright 2023 The Radius Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package schema

// ApplyDefaults fills unset properties from the "default" declared in the schema and returns the
// number applied.
//
// Explicit values are never overwritten. Required properties are never defaulted, so omitting one
// still fails validation. Read-only properties are recipe outputs, and an absent object is not
// created just to hold defaults.
func ApplyDefaults(properties map[string]any, schemaData map[string]any) int {
if properties == nil || schemaData == nil {
return 0
}

declared, ok := schemaData["properties"].(map[string]any)
if !ok {
return 0
}

required := requiredProperties(schemaData)

applied := 0
for name, raw := range declared {
fieldSchema, ok := raw.(map[string]any)
if !ok {
continue
}

if readOnly, ok := fieldSchema["readOnly"].(bool); ok && readOnly {
continue
}

// A supplied object is descended into even when required, since its own optional
// properties may declare defaults.
if existing, present := properties[name]; present {
if nested, ok := existing.(map[string]any); ok {
Comment thread
AzureMike marked this conversation as resolved.
Outdated
applied += ApplyDefaults(nested, fieldSchema)
}
continue
}

if required[name] {
continue
}

if defaultValue, ok := fieldSchema["default"]; ok {
properties[name] = copyDefaultValue(defaultValue)
applied++
}
}

return applied
}

// requiredProperties reads the schema's "required" list, accepting either the []any from JSON
// decoding or a []string.
func requiredProperties(schemaData map[string]any) map[string]bool {
required := map[string]bool{}

switch list := schemaData["required"].(type) {
case []any:
for _, item := range list {
if name, ok := item.(string); ok {
required[name] = true
}
}
case []string:
for _, name := range list {
required[name] = true
}
}

return required
}

// copyDefaultValue deep copies a default so mutating a materialized property cannot reach back into
// a cached schema.
func copyDefaultValue(value any) any {
switch typed := value.(type) {
case map[string]any:
copied := make(map[string]any, len(typed))
for key, item := range typed {
copied[key] = copyDefaultValue(item)
}
return copied
case []any:
copied := make([]any, len(typed))
for i, item := range typed {
copied[i] = copyDefaultValue(item)
}
return copied
default:
return value
}
}
Loading
Loading