From 437c0ff03e4d474e35d68dfc8b4184de7fbf7a2b Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:50:45 +0000 Subject: [PATCH 1/2] 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. --- CHANGELOG.md | 1 + db/db.go | 25 +++++++++++++++++++++++++ db/db_test.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5a2543..9dd3889 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +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. - **ask_operator image_path**: the screenshot path must resolve inside the task working directory (`/tasks/`). 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`. diff --git a/db/db.go b/db/db.go index ef9ec28..1027cd4 100644 --- a/db/db.go +++ b/db/db.go @@ -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) { diff --git a/db/db_test.go b/db/db_test.go index 41c5c05..de1e3d1 100644 --- a/db/db_test.go +++ b/db/db_test.go @@ -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 { From 8110735aa7edfde52ffc7e715e413c35ad5c95ea Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:14:07 +0100 Subject: [PATCH 2/2] 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. --- CHANGELOG.md | 2 +- db/db.go | 32 ++++++++------------------------ db/db_test.go | 31 +++++++++---------------------- 3 files changed, 18 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dd3889..74f6a55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 (`/tasks/`). 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`. diff --git a/db/db.go b/db/db.go index 1027cd4..683323e 100644 --- a/db/db.go +++ b/db/db.go @@ -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 diff --git a/db/db_test.go b/db/db_test.go index de1e3d1..445f19f 100644 --- a/db/db_test.go +++ b/db/db_test.go @@ -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) } } }