Skip to content

Commit

Permalink
checker: forbid accessing custom functions from $env
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Dec 10, 2023
1 parent 87fda67 commit d7fe04b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
14 changes: 8 additions & 6 deletions checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ func (v *checker) IdentifierNode(node *ast.IdentifierNode) (reflect.Type, info)
if node.Value == "$env" {
return mapType, info{}
}
if fn, ok := v.config.Builtins[node.Value]; ok {
return functionType, info{fn: fn}
}
if fn, ok := v.config.Functions[node.Value]; ok {
return functionType, info{fn: fn}
}
return v.env(node, node.Value, true)
}

Expand All @@ -166,13 +172,9 @@ type NodeWithIndexes interface {
SetMethodIndex(methodIndex int)
}

// env method returns type of environment variable. env only lookups for
// environment variables, no builtins, no custom functions.
func (v *checker) env(node NodeWithIndexes, name string, strict bool) (reflect.Type, info) {
if fn, ok := v.config.Builtins[name]; ok {
return functionType, info{fn: fn}
}
if fn, ok := v.config.Functions[name]; ok {
return functionType, info{fn: fn}
}
if t, ok := v.config.Types[name]; ok {
if t.Ambiguous {
return v.error(node, "ambiguous identifier %v", name)
Expand Down
25 changes: 25 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1971,7 +1971,32 @@ func TestEnv_keyword(t *testing.T) {

})
}
}

func TestEnv_keyword_with_custom_functions(t *testing.T) {
fn := expr.Function("fn", func(params ...any) (any, error) {
return "ok", nil
})

var tests = []struct {
code string
error bool
}{
{`fn()`, false},
{`$env.fn()`, true},
{`$env["fn"]`, true},
}

for _, tt := range tests {
t.Run(tt.code, func(t *testing.T) {
_, err := expr.Compile(tt.code, expr.Env(mock.Env{}), fn)
if tt.error {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}

func TestIssue401(t *testing.T) {
Expand Down

0 comments on commit d7fe04b

Please sign in to comment.