Match package import in Golang
Description
A generic rule template for detecting imports of specific packages in Go source code. This rule can be customized to match any package by modifying the regex pattern, making it useful for security auditing, dependency management, and compliance checking.
This rule identifies Go import statements based on the configured regex pattern, including:
Direct imports: import "package/name"
Versioned imports: import "package/name/v4"
Subpackage imports: import "package/name/subpkg"
Grouped imports within import () blocks
YAML
yaml
id: match-package-import
language: go
rule:
kind: import_spec
has:
regex: PACKAGE_PATTERN_HERE
Example
JWT Library Detection
go
package main
import (
"fmt"
"github.com/golang-jwt/jwt" // This matches the AST rule
)
func main() {
token := jwt.New(jwt.SigningMethodHS256) // Create a new token
// Add some claims
token.Claims = jwt.MapClaims{"user": "alice", "role": "admin"}
tokenString, err := token.SignedString([]byte("my-secret")) // Sign the token
if err != nil {
fmt.Printf("Error signing token: %v\n", err)
return
}
fmt.Printf("Generated token: %s\n", tokenString)
}