github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/test/rules/rules.go (about) 1 //go:build gorules 2 3 package rules 4 5 import ( 6 "strings" 7 8 "github.com/quasilyte/go-ruleguard/dsl" 9 ) 10 11 // nolint:unused 12 func resourceCleanup(m dsl.Matcher) { 13 // this rule defends against use of internal.CloseAndLogError() without a defer statement 14 m.Match(`$res, $err := $resolver.FileContentsByLocation($loc); if $*_ { $*_ }; $next`). 15 Where(m["res"].Type.Implements(`io.Closer`) && 16 m["res"].Type.Implements(`io.Reader`) && 17 m["err"].Type.Implements(`error`) && 18 !m["next"].Text.Matches(`defer internal.CloseAndLogError`)). 19 Report(`please call "defer internal.CloseAndLogError($res, $loc.RealPath)" right after checking the error returned from $resolver.FileContentsByLocation.`) 20 } 21 22 // nolint:unused 23 func isPtr(ctx *dsl.VarFilterContext) bool { 24 return strings.HasPrefix(ctx.Type.String(), "*") || strings.HasPrefix(ctx.Type.Underlying().String(), "*") 25 } 26 27 // nolint:unused 28 func packagesInRelationshipsAsValues(m dsl.Matcher) { 29 m.Import("github.com/anchore/syft/syft/artifact") 30 31 isRelationship := func(m dsl.Matcher) bool { 32 return m["x"].Type.Is("artifact.Relationship") 33 } 34 35 hasPointerType := func(m dsl.Matcher) bool { 36 return m["y"].Filter(isPtr) 37 } 38 39 // this rule defends against using pointers as values in artifact.Relationship 40 m.Match( 41 `$x{$*_, From: $y, $*_}`, 42 `$x{$*_, To: $y, $*_}`, 43 `$x.From = $y`, 44 `$x.To = $y`, 45 ). 46 Where(isRelationship(m) && hasPointerType(m)). 47 Report("pointer used as a value for From/To field in artifact.Relationship (use values instead)") 48 }