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

@@ -32,7 +32,6 @@ type Reference struct {
OnUpdate string `json:"on_update"`
}
// Mapping of field types to SQL types
var fieldTypeToSQLType = map[string]string{
"string": "VARCHAR",
"int": "INTEGER",
@@ -60,37 +59,68 @@ func (t *Table) JSON() ([]byte, error) {
}
func (f *Field) SQL() string {
quotedName := utils.SQLQuoteIdent(f.Name)
if !utils.IsValidIdentifier(f.Name) {
return ""
}
sqlType := fieldTypeToSQLType[f.Type]
if sqlType == "" {
return ""
}
quotedName := utils.SQLQuoteIdent(f.Name)
sql := fmt.Sprintf("%s %s", quotedName, sqlType)
if f.Nullable != nil && !*f.Nullable {
sql += " NOT NULL"
}
if f.Primary != nil && *f.Primary {
sql += " PRIMARY KEY"
if f.Default == nil && f.Type == "uuid" {
sql += " DEFAULT uuid_generate_v4()"
}
}
if f.Unique != nil && *f.Unique {
sql += " UNIQUE"
}
if f.Default != nil && f.Primary == nil {
sql += fmt.Sprintf(" DEFAULT %s", utils.SQLQuoteValue(*f.Default))
def := *f.Default
if utils.IsValidDefault(def) {
switch {
case utils.IsValidDefault(def):
if utils.IsValidDefault(def) && (def == "CURRENT_TIMESTAMP" || def == "now()" || def == "uuid_generate_v4()") {
sql += fmt.Sprintf(" DEFAULT %s", def)
} else {
sql += fmt.Sprintf(" DEFAULT %s", utils.SQLQuoteValue(def))
}
}
} else {
return ""
}
}
if f.References != nil {
sql += fmt.Sprintf(" REFERENCES %s(%s)", utils.SQLQuoteIdent(f.References.Table), utils.SQLQuoteIdent(f.References.Column))
if f.References.OnDelete != "" {
sql += fmt.Sprintf(" ON DELETE %s", f.References.OnDelete)
ref := f.References
if !utils.IsValidIdentifier(ref.Table) || !utils.IsValidIdentifier(ref.Column) {
return ""
}
if f.References.OnUpdate != "" {
sql += fmt.Sprintf(" ON UPDATE %s", f.References.OnUpdate)
sql += fmt.Sprintf(" REFERENCES %s(%s)", utils.SQLQuoteIdent(ref.Table), utils.SQLQuoteIdent(ref.Column))
if ref.OnDelete != "" {
action, err := utils.SanitizeOnAction(ref.OnDelete)
if err == nil && action != "" {
sql += fmt.Sprintf(" ON DELETE %s", action)
}
}
if ref.OnUpdate != "" {
action, err := utils.SanitizeOnAction(ref.OnUpdate)
if err == nil && action != "" {
sql += fmt.Sprintf(" ON UPDATE %s", action)
}
}
}
return sql
}
@@ -98,5 +128,11 @@ func (f *Field) SQLReferences() string {
if f.References == nil {
return ""
}
return fmt.Sprintf(" REFERENCES %s(%s)", utils.SQLQuoteIdent(f.References.Table), utils.SQLQuoteIdent(f.References.Column))
ref := f.References
if !utils.IsValidIdentifier(ref.Table) || !utils.IsValidIdentifier(ref.Column) {
return ""
}
return fmt.Sprintf(" REFERENCES %s(%s)", utils.SQLQuoteIdent(ref.Table), utils.SQLQuoteIdent(ref.Column))
}