Skip to content

Commit

Permalink
fix: restrict the value of version_expr for security
Browse files Browse the repository at this point in the history
  • Loading branch information
suzuki-shunsuke committed Dec 15, 2024
1 parent 1dd274b commit c897f6f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
5 changes: 4 additions & 1 deletion pkg/expr/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ package expr

import "errors"

var errMustBeBoolean = errors.New("the evaluation result must be a boolean")
var (
errMustBeBoolean = errors.New("the evaluation result must be a boolean")
errMustBeString = errors.New("the evaluation result must be a string")
)
27 changes: 23 additions & 4 deletions pkg/expr/version_expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package expr

import (
"encoding/json"
"errors"
"fmt"
"path/filepath"
"regexp"
"strings"

"github.com/expr-lang/expr"
Expand All @@ -16,6 +18,10 @@ type Reader struct {
fs afero.Fs
}

const safeVersionPattern = `^v?\d+\.\d+(\.\d+)*[.-]?((alpha|beta|dev|rc)[.-]?)?\d*`

var safeVersionRegexp = regexp.MustCompile(safeVersionPattern)

func EvalVersionExpr(fs afero.Fs, pwd string, expression string) (string, error) {
r := Reader{fs: fs, pwd: pwd}
compiled, err := expr.Compile(expression, expr.Env(map[string]any{
Expand All @@ -32,11 +38,20 @@ func EvalVersionExpr(fs afero.Fs, pwd string, expression string) (string, error)
"readYAML": r.readYAML,
})
if err != nil {
return "", fmt.Errorf("evaluate the expression: %w", err)
// Don't output error to prevent leaking sensitive information
// Maybe malicious users tries to read a secret file
return "", errors.New("evaluate the expression")
}
s, ok := a.(string)
if !ok {
return "", errMustBeBoolean
return "", errMustBeString
}
// Restrict the value of version_expr to a semver for security reason.
// This prevents secrets from being exposed.
if !safeVersionRegexp.MatchString(s) {
// Don't output the valuof of version_expr to prevent leaking sensitive information
// Maybe malicious users tries to read a secret file
return "", errors.New("the evaluation result of version_expr must match with " + safeVersionPattern)
}
return s, nil
}
Expand All @@ -60,7 +75,9 @@ func (r *Reader) readJSON(s string) any {
b := r.read(s)
var a any
if err := json.Unmarshal(b, &a); err != nil {
panic(err)
// Don't output error to prevent leaking sensitive information
// Maybe malicious users tries to read a secret file
panic("failed to unmarshal JSON")
}
return a
}
Expand All @@ -69,7 +86,9 @@ func (r *Reader) readYAML(s string) any {
b := r.read(s)
var a any
if err := yaml.Unmarshal(b, &a); err != nil {
panic(err)
// Don't output error to prevent leaking sensitive information
// Maybe malicious users tries to read a secret file
panic("failed to unmarshal YAML")
}
return a
}

0 comments on commit c897f6f

Please sign in to comment.