feat(sql): SQL Injection

This commit is contained in:
Björn Benouarets
2025-11-06 11:16:01 +01:00
parent 1f5f07e624
commit 10110071eb
7 changed files with 206 additions and 26 deletions

View File

@@ -9,19 +9,27 @@ import (
)
func InsertManySQL(s *schema.Table, data []map[string]any, returning bool) (string, error) {
// Keep unquoted column names for data access
if s == nil || len(data) == 0 {
return "", fmt.Errorf("invalid input: no table or data provided")
}
if !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
columnNames := make([]string, 0, len(data[0]))
for column := range data[0] {
if !utils.IsValidIdentifier(column) {
return "", fmt.Errorf("invalid column name: %q", column)
}
columnNames = append(columnNames, column)
}
// Create quoted column names for SQL
columns := make([]string, len(columnNames))
for i, col := range columnNames {
columns[i] = utils.SQLQuoteIdent(col)
}
// Create a map for quick field lookup
fieldMap := make(map[string]*schema.Field)
for i := range s.Schema {
fieldMap[s.Schema[i].Name] = &s.Schema[i]
@@ -37,7 +45,7 @@ func InsertManySQL(s *schema.Table, data []map[string]any, returning bool) (stri
valueStr := fmt.Sprintf("%v", value)
hashed, err := utils.Hash(valueStr, *field.Algorithm)
if err != nil {
return "", err
return "", fmt.Errorf("hashing error for column %q: %w", colName, err)
}
value = hashed
}
@@ -49,9 +57,12 @@ func InsertManySQL(s *schema.Table, data []map[string]any, returning bool) (stri
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", utils.SQLQuoteIdent(s.Name), strings.Join(columns, ", "), strings.Join(values, ", "))
if returning {
// RETURNING the primary key
if !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key column: %q", s.PrimaryKey)
}
query += " RETURNING " + utils.SQLQuoteIdent(s.PrimaryKey)
}
return query, nil
}