Skip to content
This repository has been archived by the owner on Jan 23, 2025. It is now read-only.

fix(terraform): hcl object expressions to return references #1543

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkg/terraform/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,10 @@ func (a *Attribute) AllReferences(blocks ...*Block) []*Reference {
func (a *Attribute) referencesFromExpression(expression hcl.Expression) []*Reference {
var refs []*Reference
switch t := expression.(type) {
case *hclsyntax.ObjectConsExpr:
for _, item := range t.Items {
refs = append(refs, a.referencesFromExpression(item.ValueExpr)...)
}
case *hclsyntax.ConditionalExpr:
if ref, err := createDotReferenceFromTraversal(a.module, t.TrueResult.Variables()...); err == nil {
refs = append(refs, ref)
Expand Down
73 changes: 73 additions & 0 deletions pkg/terraform/attribute_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package terraform

import (
"testing"

"github.com/aquasecurity/defsec/pkg/terraform/context"
"github.com/aquasecurity/defsec/pkg/types"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/stretchr/testify/require"
)

func Test_AllReferences(t *testing.T) {
cases := []struct {
input string
refs []string
}{
{
input: "42", // literal
refs: []string{},
},
{
input: "5 == 5", // comparison
refs: []string{},
},
{
input: "var.foo",
refs: []string{"variable.foo"},
},
{
input: "resource.aws_instance.id",
refs: []string{"aws_instance.id"},
},
{
input: "data.aws_ami.ubuntu.most_recent",
refs: []string{"data.aws_ami.ubuntu.most_recent"},
},
{
input: `{x = 1, y = data.aws_ami.ubuntu.most_recent}`,
refs: []string{"data.aws_ami.ubuntu.most_recent"},
},
{
input: `{foo = 1 == 1 ? true : data.aws_ami.ubuntu.most_recent}`,
refs: []string{"data.aws_ami.ubuntu.most_recent"},
},
}

for _, test := range cases {
t.Run(test.input, func(t *testing.T) {
ctx := context.NewContext(&hcl.EvalContext{}, nil)

exp, diags := hclsyntax.ParseExpression([]byte(test.input), "", hcl.Pos{Line: 1, Column: 1})
if diags != nil && diags.HasErrors() {
t.Fatal(diags.Error())
}

a := NewAttribute(&hcl.Attribute{
Name: "test",
Expr: exp,
Range: hcl.Range{},
NameRange: hcl.Range{},
}, ctx, "", types.Metadata{}, Reference{}, "", nil)

refs := a.AllReferences()
humanRefs := make([]string, 0, len(refs))
for _, ref := range refs {
humanRefs = append(humanRefs, ref.HumanReadable())
}

require.ElementsMatch(t, test.refs, humanRefs)
})
}
}