feat(sql): SQL Injection

This commit is contained in:
Björn Benouarets
2025-11-06 16:44:28 +01:00
parent 10110071eb
commit 59d6c911f9
14 changed files with 430 additions and 483 deletions

166
build/alter.go Normal file
View File

@@ -0,0 +1,166 @@
package build
import (
"fmt"
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/sql"
)
func AlterTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
var ddlParts, comments []string
for _, f := range s.Schema {
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
pgType, err := sql.ValidateType(f.Type)
if err != nil {
return nil, err
}
colParts := []string{sql.QuoteIdent(f.Name), pgType}
if f.Nullable != nil && !*f.Nullable {
colParts = append(colParts, "NOT NULL")
}
if f.Unique != nil && *f.Unique {
colParts = append(colParts, "UNIQUE")
}
if f.Default != nil && *f.Default != "" {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
if f.References != nil {
if err := sql.ValidateIdent(f.References.Table); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.References.Column); err != nil {
return nil, err
}
onDelete, err := sql.ValidateAction(f.References.OnDelete)
if err != nil {
return nil, err
}
onUpdate, err := sql.ValidateAction(f.References.OnUpdate)
if err != nil {
return nil, err
}
fk := fmt.Sprintf("REFERENCES %s(%s) ON DELETE %s ON UPDATE %s", sql.QuoteIdent(f.References.Table), sql.QuoteIdent(f.References.Column), onDelete, onUpdate)
colParts = append(colParts, fk)
}
ddlParts = append(ddlParts, strings.Join(colParts, " "))
if f.Comment != nil {
comments = append(comments, fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s'", sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name), *f.Comment))
}
}
ddl := fmt.Sprintf(sql.DDL_ALTER_TABLE, sql.QuoteIdent(s.Name), strings.Join(ddlParts, " "))
return &ddl, nil
}
func AddColumn(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_ADD_COLUMN, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func DropColumn(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_DROP_COLUMN, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func AlterColumn(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
pgType, err := sql.ValidateType(f.Type)
if err != nil {
return nil, err
}
colParts := []string{sql.QuoteIdent(f.Name), pgType}
if f.Nullable != nil && !*f.Nullable {
colParts = append(colParts, "NOT NULL")
}
ddl := fmt.Sprintf(sql.DDL_ALTER_COLUMN, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name), strings.Join(colParts, " "))
if f.Default != nil && *f.Default != "" {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
return &ddl, nil
}
func AddForeignKey(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_ADD_FOREIGN_KEY, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func DropForeignKey(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_DROP_FOREIGN_KEY, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func AddConstraint(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_ADD_CONSTRAINT, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func DropConstraint(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_DROP_CONSTRAINT, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}

View File

@@ -2,21 +2,109 @@ package build
import (
"fmt"
"log"
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func CreateSQL(s *schema.Table) (string, error) {
schemaParts := make([]string, len(s.Schema))
for i, field := range s.Schema {
schemaParts[i] = field.SQL()
func CreateTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
schemaParts = append(schemaParts, "\"created_at\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP")
schemaParts = append(schemaParts, "\"updated_at\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP")
schemaParts = append(schemaParts, "\"deleted_at\" TIMESTAMP NULL")
query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (%s)", utils.SQLQuoteIdent(s.Name), strings.Join(schemaParts, ", "))
return query, nil
var cols, comments, pks []string
for _, f := range s.Schema {
if err := sql.ValidateIdent(f.Name); err != nil {
log.Printf("Invalid identifier: %s", f.Name)
return nil, err
}
pgType, err := sql.ValidateType(f.Type)
if err != nil {
log.Printf("Invalid type: %s", f.Type)
return nil, err
}
if f.Type == "hash" {
if _, ok := sql.AlgorithmMap[strings.ToLower(*f.Algorithm)]; !ok {
log.Printf("Invalid algorithm: %s", *f.Algorithm)
return nil, fmt.Errorf("invalid algorithm: %s", *f.Algorithm)
}
}
colParts := []string{sql.QuoteIdent(f.Name), pgType}
if f.Nullable != nil && !*f.Nullable {
colParts = append(colParts, "NOT NULL")
}
if f.Unique != nil && *f.Unique {
colParts = append(colParts, "UNIQUE")
}
// Auto-generate UUID for UUID primary keys if no default is specified
if f.Primary != nil && *f.Primary && f.Type == "uuid" {
if f.Default == nil || *f.Default == "" {
colParts = append(colParts, "DEFAULT gen_random_uuid()")
} else {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
} else if f.Default != nil && *f.Default != "" {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
if f.References != nil {
if err := sql.ValidateIdent(f.References.Table); err != nil {
log.Printf("Invalid references table: %s", f.References.Table)
return nil, err
}
if err := sql.ValidateIdent(f.References.Column); err != nil {
log.Printf("Invalid references column: %s", f.References.Column)
return nil, err
}
onDelete, err := sql.ValidateAction(f.References.OnDelete)
if err != nil {
log.Printf("Invalid on delete: %s", f.References.OnDelete)
return nil, err
}
onUpdate, err := sql.ValidateAction(f.References.OnUpdate)
if err != nil {
log.Printf("Invalid on update: %s", f.References.OnUpdate)
return nil, err
}
fk := fmt.Sprintf("REFERENCES %s(%s) ON DELETE %s ON UPDATE %s", sql.QuoteIdent(f.References.Table), sql.QuoteIdent(f.References.Column), onDelete, onUpdate)
colParts = append(colParts, fk)
}
cols = append(cols, strings.Join(colParts, " "))
if f.Primary != nil && *f.Primary {
pks = append(pks, sql.QuoteIdent(f.Name))
}
if f.Comment != nil {
comments = append(comments, fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s'", sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name), *f.Comment))
}
}
if len(pks) > 0 {
cols = append(cols, "PRIMARY KEY ("+strings.Join(pks, ", ")+")")
}
ddl := fmt.Sprintf(sql.DDL_CREATE_TABLE, sql.QuoteIdent(s.Name), strings.Join(cols, ",\n "))
if len(comments) > 0 {
ddl += "\n" + strings.Join(comments, "\n")
}
log.Printf("DDL: %s", ddl)
return &ddl, nil
}

View File

@@ -1,64 +0,0 @@
package build
import (
"fmt"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
)
func DeleteSQL(s *schema.Table, where any) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
}
found := false
for i := range s.Schema {
if s.Schema[i].Name == s.PrimaryKey {
found = true
break
}
}
if !found {
return "", fmt.Errorf("primary key %q not found in schema", s.PrimaryKey)
}
return fmt.Sprintf("UPDATE %s SET deleted_at = CURRENT_TIMESTAMP WHERE %s = %s",
utils.SQLQuoteIdent(s.Name),
utils.SQLQuoteIdent(s.PrimaryKey),
utils.SQLQuoteValue(where),
), nil
}
func HardDeleteSQL(s *schema.Table, where any) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
}
found := false
for i := range s.Schema {
if s.Schema[i].Name == s.PrimaryKey {
found = true
break
}
}
if !found {
return "", fmt.Errorf("primary key %q not found in schema", s.PrimaryKey)
}
return fmt.Sprintf("DELETE FROM %s WHERE %s = %s",
utils.SQLQuoteIdent(s.Name),
utils.SQLQuoteIdent(s.PrimaryKey),
utils.SQLQuoteValue(where),
), nil
}

View File

@@ -4,15 +4,13 @@ import (
"fmt"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func DropSQL(s *schema.Table) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
func DropTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
return fmt.Sprintf("DROP TABLE IF EXISTS %s", utils.SQLQuoteIdent(s.Name)), nil
ddl := fmt.Sprintf(sql.DDL_DROP_TABLE, sql.QuoteIdent(s.Name))
return &ddl, nil
}

View File

@@ -5,67 +5,24 @@ import (
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func InsertManySQL(s *schema.Table, data []map[string]any, returning bool) (string, error) {
if s == nil || len(data) == 0 {
return "", fmt.Errorf("invalid input: no table or data provided")
func Insert(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
var cols, values []string
columnNames := make([]string, 0, len(data[0]))
for column := range data[0] {
if !utils.IsValidIdentifier(column) {
return "", fmt.Errorf("invalid column name: %q", column)
for _, f := range s.Schema {
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
columnNames = append(columnNames, column)
cols = append(cols, sql.QuoteIdent(f.Name))
values = append(values, "?")
}
columns := make([]string, len(columnNames))
for i, col := range columnNames {
columns[i] = utils.SQLQuoteIdent(col)
}
fieldMap := make(map[string]*schema.Field)
for i := range s.Schema {
fieldMap[s.Schema[i].Name] = &s.Schema[i]
}
values := make([]string, len(data))
for i, row := range data {
rowValues := make([]string, len(columnNames))
for j, colName := range columnNames {
value := row[colName]
if field, exists := fieldMap[colName]; exists && field.Type == "hash" && field.Algorithm != nil {
valueStr := fmt.Sprintf("%v", value)
hashed, err := utils.Hash(valueStr, *field.Algorithm)
if err != nil {
return "", fmt.Errorf("hashing error for column %q: %w", colName, err)
}
value = hashed
}
rowValues[j] = utils.SQLQuoteValue(value)
}
values[i] = fmt.Sprintf("(%s)", strings.Join(rowValues, ", "))
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", utils.SQLQuoteIdent(s.Name), strings.Join(columns, ", "), strings.Join(values, ", "))
if returning {
if !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key column: %q", s.PrimaryKey)
}
query += " RETURNING " + utils.SQLQuoteIdent(s.PrimaryKey)
}
return query, nil
}
func InsertSQL(s *schema.Table, data map[string]any, returning bool) (string, error) {
return InsertManySQL(s, []map[string]any{data}, returning)
dmlParts := fmt.Sprintf(sql.DML_INSERT_INTO, sql.QuoteIdent(s.Name), strings.Join(cols, ", "), strings.Join(values, ", "))
return &dmlParts, nil
}

View File

@@ -4,23 +4,13 @@ import (
"fmt"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func TruncateSQL(s *schema.Table, cascade bool, restartIdentity bool) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
func TruncateTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
query := fmt.Sprintf("TRUNCATE TABLE %s", utils.SQLQuoteIdent(s.Name))
if restartIdentity {
query += " RESTART IDENTITY"
}
if cascade {
query += " CASCADE"
}
return query, nil
ddl := fmt.Sprintf(sql.DDL_TRUNCATE_TABLE, sql.QuoteIdent(s.Name))
return &ddl, nil
}

View File

@@ -1,56 +0,0 @@
package build
import (
"fmt"
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
)
func UpdateSQL(s *schema.Table, data map[string]any, where string) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
}
fieldMap := make(map[string]*schema.Field)
for i := range s.Schema {
fieldMap[s.Schema[i].Name] = &s.Schema[i]
}
setClause := make([]string, 0, len(data))
for field, value := range data {
if !utils.IsValidIdentifier(field) {
return "", fmt.Errorf("invalid field name: %q", field)
}
if schemaField, exists := fieldMap[field]; exists && schemaField.Type == "hash" && schemaField.Algorithm != nil {
valueStr := fmt.Sprintf("%v", value)
hashed, err := utils.Hash(valueStr, *schemaField.Algorithm)
if err != nil {
return "", err
}
value = hashed
}
setClause = append(setClause, fmt.Sprintf("%s = %s", utils.SQLQuoteIdent(field), utils.SQLQuoteValue(value)))
}
setClause = append(setClause, "updated_at = CURRENT_TIMESTAMP")
query := fmt.Sprintf(
"UPDATE %s SET %s WHERE %s = %s",
utils.SQLQuoteIdent(s.Name),
strings.Join(setClause, ", "),
utils.SQLQuoteIdent(s.PrimaryKey),
utils.SQLQuoteValue(where),
)
return query, nil
}