tflint-plugin-sdk icon indicating copy to clipboard operation
tflint-plugin-sdk copied to clipboard

Failed to evaluate naked identifier map keys

Open wata727 opened this issue 1 year ago • 0 comments

Follow up of https://github.com/terraform-linters/tflint-ruleset-terraform/pull/196

Naked identifier map keys are typically not valid references, but can still be successfully evaluated. Despite this, it fails to evaluate in the TFLint plugin SDK. This is exactly the same problem that occurs in https://github.com/terraform-linters/tflint-ruleset-terraform/pull/196, where the test runner doesn't throw an error, but the actual runner does.

The cause of this is in the serialization of expressions. In the actual runner, in order to send an expression via gRPC, it is converted into a byte sequence of the expression's source code and then parsed again as an expression:

https://github.com/terraform-linters/tflint-plugin-sdk/blob/63caa056a756aad72f6a4abd322acf74568fa772/plugin/internal/toproto/toproto.go#L117-L120 https://github.com/terraform-linters/tflint-plugin-sdk/blob/63caa056a756aad72f6a4abd322acf74568fa772/plugin/internal/fromproto/fromproto.go#L154

However, expressions such as map keys are context-sensitive and when parsed in this manner the result is a different expression type.

package main

import (
        "fmt"

        "github.com/hashicorp/hcl/v2"
        "github.com/hashicorp/hcl/v2/hclsyntax"
)

func main() {
        source := []byte(`{ keys = "value" }`)
        expr, diags := hclsyntax.ParseExpression(source, "main.tf", hcl.InitialPos)
        if diags.HasErrors() {
                panic(diags)
        }
        pairs, diags := hcl.ExprMap(expr)
        if diags.HasErrors() {
                panic(diags)
        }
        originalExpr := pairs[0].Key

        fmt.Printf("original_expr=%T\n", originalExpr)
        keySource := originalExpr.Range().SliceBytes(source)
        parsedExpr, diags := hclsyntax.ParseExpression(keySource, "main.tf", originalExpr.Range().Start)
        if diags.HasErrors() {
                panic(diags)
        }
        fmt.Printf("parsed_expr=%T\n", parsedExpr)
}
$ go run main.go
original_expr=*hclsyntax.ObjectConsKeyExpr
parsed_expr=*hclsyntax.ScopeTraversalExpr

The ObjectConsKeyExpr is a wrapper expression that allows a naked identifier to be evaluated without error. https://github.com/hashicorp/hcl/blob/v2.21.0/hclsyntax/expression.go#L1286-L1292

To fix this in the SDK, we would need to include the fact that the expression was a map key in proto.Expression and restore it on the host side.

wata727 avatar Jul 28 '24 10:07 wata727