github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/validator/shellsafe/shellsafe.go (about)

     1  // Copyright (c) 2018-2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package shellsafe
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"reflect"
    11  	"strings"
    12  )
    13  
    14  // Validate checks if a string is safe to use in a shell without any escapes or redirects
    15  func Validate(input string) (bool, error) {
    16  	badchars := []string{"`", "$", ";", "|", "&&", ">", "<"}
    17  
    18  	for _, c := range badchars {
    19  		if strings.Contains(input, c) {
    20  			return false, fmt.Errorf("may not contain '%s'", c)
    21  		}
    22  	}
    23  
    24  	return true, nil
    25  }
    26  
    27  // ValidateStructField validates a reflect.Value is shellsafe
    28  func ValidateStructField(value reflect.Value, tag string) (bool, error) {
    29  	if value.Kind() != reflect.String {
    30  		return false, errors.New("should be a string")
    31  	}
    32  
    33  	return Validate(value.String())
    34  }