Path: blob/main/install/installer/pkg/config/validation.go
2499 views
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package config56import (7"encoding/json"8"fmt"9"io"10"strings"1112"github.com/go-playground/validator/v10"13)1415type ValidationResult struct {16Valid bool `json:"valid"`17Warnings []string `json:"warn,omitempty"`18Fatal []string `json:"fatal,omitempty"`19}2021func Validate(version ConfigVersion, cfg interface{}) (r *ValidationResult, err error) {22defer func() {23if r != nil {24r.Valid = len(r.Fatal) == 025}26}()2728validate := validator.New()29err = version.LoadValidationFuncs(validate)30if err != nil {31return nil, err32}3334var res ValidationResult3536warnings, conflicts := version.CheckDeprecated(cfg)3738for k, v := range warnings {39res.Warnings = append(res.Warnings, fmt.Sprintf("Deprecated config parameter: %s=%v", k, v))40}41res.Fatal = append(res.Fatal, conflicts...)4243err = validate.Struct(cfg)44if err != nil {45validationErrors := err.(validator.ValidationErrors)4647if len(validationErrors) > 0 {48for _, v := range validationErrors {49switch v.Tag() {50case "required":51res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' is required", v.Namespace()))52case "required_if", "required_unless", "required_with":53tag := strings.Replace(v.Tag(), "_", " ", -1)54res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' is %s '%s'", v.Namespace(), tag, v.Param()))55case "startswith":56res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' must start with '%s'", v.Namespace(), v.Param()))57case "block_new_users_passlist":58res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' failed. If 'Enabled = true', there must be at least one fully-qualified domain name in the passlist", v.Namespace()))59default:60// General error message61res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' failed %s validation", v.Namespace(), v.Tag()))62}63}64return &res, nil65}66}6768return &res, nil69}7071// Marshal marshals this result to JSON72func (r *ValidationResult) Marshal(w io.Writer) {73enc := json.NewEncoder(w)74enc.SetIndent("", " ")75enc.Encode(r)76}777879