go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/config_service/internal/service/metadata.go (about)

     1  // Copyright 2023 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package service
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"net/url"
    21  	"regexp"
    22  	"strings"
    23  
    24  	cfgcommonpb "go.chromium.org/luci/common/proto/config"
    25  )
    26  
    27  func validateMetadata(metadata *cfgcommonpb.ServiceMetadata) error {
    28  	var errs []error
    29  	for i, pattern := range metadata.GetConfigPatterns() {
    30  		if err := validateConfigPattern(pattern); err != nil {
    31  			errs = append(errs, fmt.Errorf("invalid config pattern [%d]: %w", i, err))
    32  		}
    33  	}
    34  	return errors.Join(errs...)
    35  }
    36  
    37  func validateLegacyMetadata(legacyMetadata *cfgcommonpb.ServiceDynamicMetadata) error {
    38  	var errs []error
    39  	for i, pattern := range legacyMetadata.GetValidation().GetPatterns() {
    40  		if err := validateConfigPattern(pattern); err != nil {
    41  			errs = append(errs, fmt.Errorf("invalid config pattern [%d]: %w", i, err))
    42  		}
    43  	}
    44  	switch u := legacyMetadata.GetValidation().GetUrl(); {
    45  	case u == "":
    46  		errs = append(errs, errors.New("empty validation url"))
    47  	default:
    48  		if _, err := url.Parse(u); err != nil {
    49  			errs = append(errs, fmt.Errorf("invalid url %q: %w", u, err))
    50  		}
    51  	}
    52  	return errors.Join(errs...)
    53  }
    54  
    55  func validateConfigPattern(pattern *cfgcommonpb.ConfigPattern) error {
    56  	if expr, found := strings.CutPrefix(pattern.GetConfigSet(), "regex:"); found {
    57  		if _, err := regexp.Compile(expr); err != nil {
    58  			return fmt.Errorf("invalid regular expression %q for config set pattern: %w", expr, err)
    59  		}
    60  	}
    61  	if expr, found := strings.CutPrefix(pattern.GetPath(), "regex:"); found {
    62  		if _, err := regexp.Compile(expr); err != nil {
    63  			return fmt.Errorf("invalid regular expression %q for path pattern: %w", expr, err)
    64  		}
    65  	}
    66  	return nil
    67  }