fix(db): reject unsafe CREATE DATABASE identifiers

ensureDatabase quoted the DSN path into CREATE DATABASE with no
check. A quote in the name could close the identifier. The name is
now restricted to the unquoted-identifier alphabet before quoting.
This commit is contained in:
Coff0xc
2026-11-18 22:43:20 +01:00
committed by BaaRai
parent 8f3a9a8413
commit 437c0ff03e
3 changed files with 57 additions and 0 deletions
+25
View File
@@ -142,6 +142,9 @@ func ensureDatabase(dsn string) error {
if dbName == "" || dbName == "postgres" {
return nil
}
if !validPostgresDBName(dbName) {
return fmt.Errorf("invalid database name %q", dbName)
}
// connect to the postgres maintenance database instead
adminDSN := *u
adminDSN.Path = "/postgres"
@@ -156,6 +159,8 @@ func ensureDatabase(dsn string) error {
var exists bool
_ = admin.QueryRow(`SELECT true FROM pg_database WHERE datname=$1`, dbName).Scan(&exists)
if !exists {
// dbName is a validated identifier: quoting preserves case and cannot
// be closed by the name itself.
if _, err := admin.Exec(`CREATE DATABASE "` + dbName + `"`); err != nil {
return fmt.Errorf("create database %q: %w", dbName, err)
}
@@ -163,6 +168,26 @@ func ensureDatabase(dsn string) error {
return nil
}
// validPostgresDBName reports whether name is safe to embed in a quoted
// PostgreSQL identifier (ASCII letters, digits, underscore; not starting
// with a digit; at most 63 bytes). Quotes, spaces, and punctuation are
// rejected so the name cannot close CREATE DATABASE "...".
func validPostgresDBName(name string) bool {
if name == "" || len(name) > 63 {
return false
}
for i := 0; i < len(name); i++ {
c := name[i]
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c == '_':
case i > 0 && c >= '0' && c <= '9':
default:
return false
}
}
return true
}
// Open connects, applies the schema (idempotent) and the embedded versioned
// migrations, and seeds builtin rows.
func Open(dsn string) (*DB, error) {
+31
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
"strings"
"testing"
"time"
@@ -51,6 +52,36 @@ func TestApplySchemaRetriesOnlyDeadlocks(t *testing.T) {
}
}
func TestValidPostgresDBName(t *testing.T) {
tests := []struct {
name string
ok bool
}{
{"artex", true},
{"artex_db", true},
{"artex_agent", true},
{"_tmp", true},
{"A1", true},
{"postgres", true},
{"", false},
{"1artex", false},
{"artex-db", false},
{"artex.db", false},
{"artex db", false},
{"artex$db", false},
{`x"; DROP TABLE y; --`, false},
{`artex"`, false},
{"café", false},
{strings.Repeat("a", 63), true},
{strings.Repeat("a", 64), false},
}
for _, tt := range tests {
if got := validPostgresDBName(tt.name); got != tt.ok {
t.Errorf("validPostgresDBName(%q)=%v, want %v", tt.name, got, tt.ok)
}
}
}
// testDSN returns the configured DSN, skipping the test when neither the env var
// nor a config file supplies one (DSN no longer has a built-in default).
func testDSN(t *testing.T) string {