semgrep: adjust forbidden package rule for regex matches (#25904)

We have several semgrep rules forbidding imports of packages we don't
want. While testing out a new rule I discovered that the rule we have is
completely ineffective. Update the rule to detect imports using the Go language
plugin, including regex matching on some packages where it's forbidden to import
the root but fine to import a subpackage or different version.

The go-set import rule is an example of one where our `go-set/v3` imports fails
the re-written check unless we use the regex syntax. If you replace the pattern
rule with `import "=~/github.com\/hashicorp\/go-set/v3$/"` it would fail.
This commit is contained in:
Tim Gross
2025-05-20 16:39:24 -04:00
committed by GitHub
parent 13a59a57e6
commit b6d9424c4b

View File

@@ -3,20 +3,19 @@
rules:
- id: "disallow-imports"
patterns:
- pattern: '"github.com/boltdb/bolt"'
- pattern: '"github.com/pkg/errors"'
- pattern: '"github.com/hashicorp/consul"'
- pattern: '"github.com/hashicorp/consul/command/flags"'
- pattern: '"github.com/hashicorp/consul/sdk"'
- pattern: '"github.com/hashicorp/go-set"'
- pattern: '"github.com/mitchellh/cli"'
- pattern: '"golang.org/x/exp/slices"'
- pattern: '"golang.org/x/exp/maps"'
- pattern: '"golang.org/x/exp/constraints"'
pattern-either:
- pattern: import "github.com/boltdb/bolt"
- pattern: import "github.com/pkg/errors"
- pattern: import "=~/github.com\/hashicorp\/consul$/"
- pattern: import "github.com/hashicorp/consul/command/flags"
- pattern: import "=~/github.com\/hashicorp\/consul\/sdk$/"
- pattern: import "=~/github.com\/hashicorp\/go-set$/"
- pattern: import "github.com/mitchellh/cli"
- pattern: import "golang.org/x/exp/slices"
- pattern: import "golang.org/x/exp/maps"
- pattern: import "golang.org/x/exp/constraints"
message: "Import of this package has been disallowed"
languages:
- "generic"
languages: [go]
severity: "ERROR"
paths:
include: