FilterGuard is a Go package that validates whether required filter fields are present in SQL WHERE clauses. It's particularly useful for ensuring that queries contain necessary filters like group_id for multi-tenant applications or row-level security.
- Validates GORM queries to ensure required fields are present in WHERE clauses
- Supports direct SQL string validation using SQL parser
- Handles complex WHERE conditions including AND, OR, and parentheses
- Fallback to regex-based parsing for SQLs that can't be parsed by the SQL parser
go get github.com/po3rin/filterguardpackage main
import (
"fmt"
"log"
"github.com/po3rin/filterguard"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primarykey"`
GroupID string
Name string
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
// Create a filter checker that requires 'group_id' field
checker := filterguard.New("group_id")
// Valid query - contains group_id filter
validQuery := db.Where("group_id = ? AND name = ?", "group1", "Alice")
if err := checker.CheckQuery(validQuery); err != nil {
fmt.Printf("Error: %v\n", err)
} else {
fmt.Println("✓ Query is valid")
}
// Invalid query - missing group_id filter
invalidQuery := db.Where("name = ?", "Alice")
if err := checker.CheckQuery(invalidQuery); err != nil {
fmt.Printf("Error: %v\n", err) // Will print error
}
}checker := filterguard.New("group_id")
// Valid SQL
sqlStr := "SELECT * FROM users WHERE group_id = 'group1' AND name = 'Alice'"
if err := checker.CheckSQL(sqlStr); err != nil {
fmt.Printf("Error: %v\n", err)
} else {
fmt.Println("✓ SQL is valid")
}// Require both group_id and status fields
checker := filterguard.New("group_id", "status")
query := db.Where("group_id = ? AND status = ? AND name = ?", "group1", "active", "Alice")
if err := checker.CheckQuery(query); err != nil {
fmt.Printf("Error: %v\n", err)
} else {
fmt.Println("✓ Query contains both required fields")
}Creates a new FilterChecker instance with the specified required fields.
Validates that a GORM query contains all required fields in its WHERE clause. Returns an error if any required field is missing.
Validates that a SQL string contains all required fields in its WHERE clause. Returns an error if any required field is missing or if the SQL cannot be parsed.
- Multi-tenant applications: Ensure all queries include group isolation filters
- Row-level security: Validate that queries contain necessary security filters
- Data compliance: Ensure queries follow data access policies
- Query auditing: Validate queries before execution in middleware
Run the example:
cd example
go run main.gogo test -vMIT License