queryguard

package module
v0.0.0-...-cf75f84 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2025 License: MIT Imports: 5 Imported by: 0

README

QueryGuard

QueryGuard is a Go package for validating SQL queries against security and architectural constraints. It helps protect your application by ensuring SQL queries follow safe patterns and access only allowed tables and columns.

Features

  • Validates SQL SELECT queries against defined security rules
  • Prevents SQL injection attacks
  • Restricts table and column access to approved lists
  • Enforces good SQL practices (no SELECT *, restricted JOIN types, etc.)
  • Supports two validation modes:
    • Standard mode: Basic data access with minimal constructs
    • Reporting mode: More advanced queries with GROUP BY, ORDER BY, etc.

Installation

go get github.com/marketconnect/queryguard

Usage

package main

import (
    "fmt"
    "github.com/marketconnect/queryguard"
)

func main() {
    // Basic usage - validate a simple SELECT query
    query := "SELECT product_id, quantity FROM stocks WHERE warehouse_id = 123"
    
    // Standard mode validation
    err := queryguard.IsSafeSelectQuery(query, 0, false)
    if err != nil {
        fmt.Printf("Query validation failed: %v\n", err)
        return
    }
    
    fmt.Println("Query is valid!")
    
    // For reporting queries with aggregations, sorting, limits
    reportingQuery := "SELECT product_id, COUNT(*) FROM stocks GROUP BY product_id ORDER BY COUNT(*) DESC LIMIT 10"
    
    // Use reporting mode (third parameter true)
    err = queryguard.IsSafeSelectQuery(reportingQuery, 0, true)
    if err != nil {
        fmt.Printf("Reporting query validation failed: %v\n", err)
        return
    }
    
    fmt.Println("Reporting query is valid!")
}

Configuration

The package exposes several variables that can be modified to customize validation:

// Configure allowed tables and columns
queryguard.AllowedTables["newtable"] = []string{"column1", "column2"}

// Add additional allowed functions
queryguard.AllowedFunctions["LOWER"] = true

// Adjust validation limits
queryguard.MaxQueryDepth = 5
queryguard.MaxConditions = 30

Limitations

QueryGuard is designed for validating SELECT queries only and does not support:

  • Data manipulation queries (INSERT, UPDATE, DELETE)
  • Schema modification queries (CREATE, ALTER, DROP)
  • Subqueries, CTEs, window functions
  • Certain advanced SQL features

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	MaxQueryDepth = 10
	MaxConditions = 50
	MaxJoinDepth  = 3
)

Configuration options for query validation

View Source
var AllowedFunctions = map[string]bool{
	"COUNT": true,
	"SUM":   true,
	"AVG":   true,
	"MIN":   true,
	"MAX":   true,
}

AllowedFunctions defines SQL functions that are permitted in queries

View Source
var AllowedOperators = map[string]bool{
	"=":      true,
	"<":      true,
	">":      true,
	"<=":     true,
	">=":     true,
	"!=":     true,
	"<>":     true,
	"IN":     true,
	"LIKE":   true,
	"IS":     true,
	"IS NOT": true,
}

AllowedOperators defines SQL operators that are permitted in queries

View Source
var AllowedTables = map[string][]string{
	"stocks":    {"product_id", "warehouse_id", "size_option_id", "quantity", "basic_price", "timestamp"},
	"orders":    {"product_id", "size_option_id", "warehouse_id", "price", "orders", "timestamp"},
	"orders30d": {"product_id", "subject_id", "price", "orders", "is_fbs", "total_revenue"},
}

AllowedTables defines tables and their fields that are permitted in queries

View Source
var ProhibitedPatterns = []string{
	`(?i)\bWITH\b`,
	`/\*.*\*/`,
	`--.*$`,
	`;\s*\S`,
	`\bunion\b`,
	`\bexcept\b`,
	`\bintersect\b`,
	`\bcreate\b`,
	`\bdrop\b`,
	`\balter\b`,
	`\bexec\b`,
	`\bcall\b`,
	`\bpragma\b`,
	`\binsert\b`,
	`\bupdate\b`,
	`\bdelete\b`,
	`\bwindow\b`,
	`\bpartition\b`,
	`\brecursive\b`,
	`\busing\b`,
	`\bexplain\b`,
	`\banalyze\b`,
	`\bexplain\s+analyze\b`,
	`\bcase\b`,
	`\bover\b`,
	`\bnatural\b\s+\bjoin\b`,
}

ProhibitedPatterns defines regex patterns for prohibited SQL constructs

Functions

func IsSafeSelectQuery

func IsSafeSelectQuery(sqlQuery string, currentDepth int, reportingMode bool) error

IsSafeSelectQuery validates a SQL query against security rules The reportingMode parameter changes validation behavior for reporting queries

Types

This section is empty.

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL