fix(db): quote CREATE DATABASE name with pgx.Identifier

The allowlist rejected names PostgreSQL accepts, so an existing install
whose database name had a hyphen, a dot or non-ASCII characters refused
to start. pgx.Identifier escapes any name, which closes the injection
without refusing a name that already exists.
This commit is contained in:
BaaRai
2026-11-18 22:43:30 +01:00
parent 437c0ff03e
commit 8110735aa7
3 changed files with 18 additions and 47 deletions
+1 -1
View File
@@ -55,7 +55,7 @@ All notable changes to this project are documented in this file. The format is b
- **Change-password rate limit**: `POST /api/auth/change-password` uses the same limiter as login, keyed by client IP and by the session token, so a stolen session cannot guess the current password without backoff.
- **Ingested traffic headers**: `RecordExternal` rejects a method that is not an HTTP token and header names or values that contain CR, LF, or NUL, matching Replay, so ingested exchanges cannot inject extra header lines into stored evidence.
- **Browser MCP starts offline** (#329): the seeded `browser` MCP ran `npx @playwright/mcp`, which contacts the npm registry on every start even with the package installed globally, and Playwright MCP defaulted to a Chrome channel the image does not ship. It now runs the image's `playwright-mcp` binary with `--headless --browser chromium`. Existing databases that still have a stock `npx @playwright/mcp` row (including the common `-y` form) or a `playwright-mcp` row with no `--browser` are rewritten once; any other command or package is left alone. The image also installs the Chromium build `@playwright/mcp` and `@playwright/cli` expect, which is not the same build `playwright install` puts in the cache.
- **CREATE DATABASE identifiers**: `ensureDatabase` rejects a DSN database name that is not a safe PostgreSQL identifier (ASCII letters, digits and underscore, not starting with a digit, at most 63 bytes) before it runs `CREATE DATABASE`, so a quote in the name cannot close the identifier.
- **CREATE DATABASE identifiers**: `ensureDatabase` now builds the statement with `pgx.Identifier`, which quotes the DSN database name and doubles any embedded quote, so the name cannot close the identifier. No database name PostgreSQL accepts is refused, so existing installs with a hyphen, a dot or non-ASCII characters keep starting.
- **ask_operator image_path**: the screenshot path must resolve inside the task working directory (`<data>/tasks/<id>`). Absolute paths, `..` segments, and symlinks that leave that directory are refused, so the tool cannot copy an arbitrary server image into the operator transcript.
- **insert_assets fail-closed**: when intercept or task allow/block rules cannot be loaded, `insert_assets` refuses the whole call instead of evaluating an empty rule set (which allowed every asset). The tool result does not include the underlying database error.
- **BlobRange length no longer wraps int64**: `offset+length > size` overflowed when length was near MaxInt64, so the cap was skipped and `make([]byte, length)` could exhaust memory. The bound is now `length > size-offset`.
+8 -24
View File
@@ -25,6 +25,7 @@ import (
"time"
"github.com/Autumn-27/artex/config"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
_ "github.com/jackc/pgx/v5/stdlib" // pgx database/sql driver ("pgx")
)
@@ -142,9 +143,6 @@ 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"
@@ -159,33 +157,19 @@ 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 {
if _, err := admin.Exec(createDatabaseSQL(dbName)); err != nil {
return fmt.Errorf("create database %q: %w", dbName, err)
}
}
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
// createDatabaseSQL builds the CREATE DATABASE statement for a DSN-supplied
// database name. pgx.Identifier quotes it and doubles any embedded quote, so
// the name cannot close the identifier, and names PostgreSQL accepts but a
// restrictive allowlist would reject (hyphens, dots, non-ASCII) keep working.
func createDatabaseSQL(name string) string {
return "CREATE DATABASE " + pgx.Identifier{name}.Sanitize()
}
// Open connects, applies the schema (idempotent) and the embedded versioned
+9 -22
View File
@@ -4,7 +4,6 @@ import (
"context"
"database/sql"
"errors"
"strings"
"testing"
"time"
@@ -52,32 +51,20 @@ func TestApplySchemaRetriesOnlyDeadlocks(t *testing.T) {
}
}
func TestValidPostgresDBName(t *testing.T) {
func TestCreateDatabaseSQLQuotesName(t *testing.T) {
tests := []struct {
name string
ok bool
want string
}{
{"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},
{"artex", `CREATE DATABASE "artex"`},
{"artex-db", `CREATE DATABASE "artex-db"`},
{"café", `CREATE DATABASE "café"`},
{`artex"`, `CREATE DATABASE "artex"""`},
{`x"; DROP TABLE y; --`, `CREATE DATABASE "x""; DROP TABLE y; --"`},
}
for _, tt := range tests {
if got := validPostgresDBName(tt.name); got != tt.ok {
t.Errorf("validPostgresDBName(%q)=%v, want %v", tt.name, got, tt.ok)
if got := createDatabaseSQL(tt.name); got != tt.want {
t.Errorf("createDatabaseSQL(%q)=%q, want %q", tt.name, got, tt.want)
}
}
}