@@ -13,6 +13,7 @@ import (
13
13
"strings"
14
14
"time"
15
15
16
+ "golang.org/x/mod/modfile"
16
17
"golang.org/x/tools/go/packages"
17
18
)
18
19
@@ -41,6 +42,64 @@ func NewAnalyzer(opts ...Option) *DefaultAnalyzer {
41
42
}
42
43
}
43
44
45
+ // validatePath checks if the path is safe to access
46
+ func (a * DefaultAnalyzer ) validatePath (path string ) error {
47
+ if path == "" {
48
+ return fmt .Errorf ("empty path" )
49
+ }
50
+
51
+ // Convert to absolute path
52
+ absPath := path
53
+ if ! filepath .IsAbs (path ) {
54
+ absPath = filepath .Join (a .opts .WorkDir , path )
55
+ }
56
+
57
+ // Clean the path
58
+ absPath = filepath .Clean (absPath )
59
+
60
+ // Check if the path is within workDir
61
+ workDirAbs , err := filepath .Abs (a .opts .WorkDir )
62
+ if err != nil {
63
+ return fmt .Errorf ("failed to get absolute path: %w" , err )
64
+ }
65
+
66
+ if ! strings .HasPrefix (absPath , workDirAbs ) {
67
+ return fmt .Errorf ("path is outside of working directory" )
68
+ }
69
+
70
+ return nil
71
+ }
72
+
73
+ // loadGoMod loads and parses the go.mod file
74
+ func (a * DefaultAnalyzer ) loadGoMod () (* modfile.File , error ) {
75
+ goModPath := filepath .Join (a .opts .WorkDir , "go.mod" )
76
+
77
+ if err := a .validatePath (goModPath ); err != nil {
78
+ return nil , fmt .Errorf ("invalid go.mod path: %w" , err )
79
+ }
80
+
81
+ content , err := os .ReadFile (goModPath )
82
+ if err != nil {
83
+ return nil , fmt .Errorf ("read go.mod: %w" , err )
84
+ }
85
+
86
+ // Extract module name from go.mod
87
+ var moduleName string
88
+ lines := strings .Split (string (content ), "\n " )
89
+ for _ , line := range lines {
90
+ if strings .HasPrefix (strings .TrimSpace (line ), "module " ) {
91
+ moduleName = strings .TrimSpace (strings .TrimPrefix (strings .TrimSpace (line ), "module " ))
92
+ break
93
+ }
94
+ }
95
+
96
+ if moduleName == "" {
97
+ return nil , & AnalysisError {Op : "parse go.mod" , Path : goModPath , Wrapped : fmt .Errorf ("module name not found" )}
98
+ }
99
+
100
+ return nil , nil
101
+ }
102
+
44
103
// loadPackage loads a package with basic configuration
45
104
// It supports both local and third-party packages
46
105
func (a * DefaultAnalyzer ) loadPackage (pkgPath string ) (* packages.Package , error ) {
0 commit comments