Skip to content

Commit d4e5e9b

Browse files
committed
protect main entry point from panics
1 parent 62939c6 commit d4e5e9b

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

preview.go

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,9 @@ import (
55
"encoding/json"
66
"fmt"
77
"io/fs"
8-
"log/slog"
9-
"os"
108
"path/filepath"
119

1210
"github.com/aquasecurity/trivy/pkg/iac/scanners/terraform/parser"
13-
"github.com/aquasecurity/trivy/pkg/log"
1411
"github.com/hashicorp/hcl/v2"
1512
"github.com/zclconf/go-cty/cty"
1613

@@ -34,10 +31,27 @@ type Output struct {
3431
Files map[string]*hcl.File
3532
}
3633

37-
func Preview(ctx context.Context, input Input, dir fs.FS) (*Output, hcl.Diagnostics) {
38-
// TODO: FIX LOGGING
39-
slog.SetLogLoggerLevel(slog.LevelDebug)
40-
slog.SetDefault(slog.New(log.NewHandler(os.Stderr, nil)))
34+
func Preview(ctx context.Context, input Input, dir fs.FS) (mainOutput *Output, diagnostics hcl.Diagnostics) {
35+
// The trivy package works with `github.com/zclconf/go-cty`. This package is
36+
// similar to `reflect` in its usage. This package can panic if types are
37+
// misused. To protect the caller, a general `recover` is used to catch any
38+
// mistakes. If this happens, there is a developer bug that needs to be resolved.
39+
defer func() {
40+
if r := recover(); r != nil {
41+
diagnostics = hcl.Diagnostics{
42+
{
43+
Severity: hcl.DiagError,
44+
Summary: "Panic occurred in preview. This should not happen, please report this to Coder.",
45+
Detail: fmt.Sprintf("panic in preview: %+v", r),
46+
},
47+
}
48+
}
49+
}()
50+
51+
// TODO: Fix logging. There is no way to pass in an instanced logger to
52+
// the parser.
53+
//slog.SetLogLoggerLevel(slog.LevelDebug)
54+
//slog.SetDefault(slog.New(log.NewHandler(os.Stderr, nil)))
4155

4256
varFiles, err := tfVarFiles("", dir)
4357
if err != nil {

0 commit comments

Comments
 (0)