Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(misconf): log causes of HCL file parsing errors #7634

Merged
merged 4 commits into from
Nov 25, 2024
Merged
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
61 changes: 57 additions & 4 deletions pkg/iac/scanners/terraform/parser/parser.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package parser

import (
"bufio"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
Expand Down Expand Up @@ -166,18 +168,69 @@ func (p *Parser) ParseFS(ctx context.Context, dir string) error {
}
sort.Strings(paths)
for _, path := range paths {
if err := p.ParseFile(ctx, path); err != nil {
if p.stopOnHCLError {
var err error
if err = p.ParseFile(ctx, path); err == nil {
continue
}

if p.stopOnHCLError {
return err
}
var diags hcl.Diagnostics
if errors.As(err, &diags) {
errc := p.showParseErrors(p.moduleFS, path, diags)
if errc == nil {
continue
}
p.logger.Error("Failed to get the causes of the parsing error", log.Err(errc))
}
p.logger.Error("Error parsing file", log.FilePath(path), log.Err(err))
continue
}

return nil
}

func (p *Parser) showParseErrors(fsys fs.FS, filePath string, diags hcl.Diagnostics) error {
file, err := fsys.Open(filePath)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
defer file.Close()

for _, diag := range diags {
if subj := diag.Subject; subj != nil {
lines, err := readLinesFromFile(file, subj.Start.Line, subj.End.Line)
if err != nil {
return err
}
p.logger.Error("Error parsing file", log.FilePath(path), log.Err(err))
continue

cause := strings.Join(lines, "\n")
p.logger.Error("Error parsing file", log.FilePath(filePath),
log.String("cause", cause), log.Err(diag))
}
}

return nil
}

func readLinesFromFile(f io.Reader, from, to int) ([]string, error) {
scanner := bufio.NewScanner(f)
rawLines := make([]string, 0, to-from+1)

for lineNum := 0; scanner.Scan() && lineNum < to; lineNum++ {
if lineNum >= from-1 {
rawLines = append(rawLines, scanner.Text())
}
}

if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to scan file: %w", err)
}

return rawLines, nil
}

var ErrNoFiles = errors.New("no files found")

func (p *Parser) Load(ctx context.Context) (*evaluator, error) {
Expand Down
21 changes: 21 additions & 0 deletions pkg/iac/scanners/terraform/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2010,6 +2010,27 @@ variable "baz" {}
assert.Contains(t, buf.String(), "variables=\"foo\"")
}

func TestLogParseErrors(t *testing.T) {
var buf bytes.Buffer
slog.SetDefault(slog.New(log.NewHandler(&buf, nil)))

src := `resource "aws-s3-bucket" "name" {
bucket = <
}`

fsys := fstest.MapFS{
"main.tf": &fstest.MapFile{
Data: []byte(src),
},
}

parser := New(fsys, "")
err := parser.ParseFS(context.TODO(), ".")
require.NoError(t, err)

assert.Contains(t, buf.String(), `cause=" bucket = <"`)
}

func Test_PassingNullToChildModule_DoesNotEraseType(t *testing.T) {
tests := []struct {
name string
Expand Down