Skip to content

fix: pin search_path when extracting schemas and applying plans - #318

Draft
jtayal-stripe wants to merge 1 commit into
mainfrom
fix-search-path-pinning
Draft

jtayal-stripe wants to merge 1 commit into
mainfrom
fix-search-path-pinning

Conversation

@jtayal-stripe

Copy link
Copy Markdown
Collaborator

Description

Pins search_path to pg_catalog in two places so that a migration plan cannot resolve to objects created after it was generated:

  1. Schema extraction (internal/schema/schema.go, GetSchema). Postgres deparse functions (pg_get_indexdef, pg_get_expr, pg_get_constraintdef, pg_get_triggerdef, ...) omit the schema of any object that is visible on the session's search_path. Fetching with search_path = pg_catalog makes every non-built-in reference schema-qualified (for example public.normalize_email(email)). The caller's search_path is restored afterwards.
  2. Plan execution (cmd/pg-schema-diff/apply_cmd.go runPlan, and plan validation in pkg/diff/plan_generator.go). Statements run with SET SESSION search_path = pg_catalog, so the remaining unqualified names can only resolve to built-ins.

Both halves are needed. Pinning only at apply breaks any schema that references objects in public (user functions, extension operator classes such as pg_trgm's gin_trgm_ops). Pinning only at extraction leaves unqualified built-ins shadowable.

Two supporting changes:

  • check_function_bodies = false during apply and validation. Function bodies are stored verbatim rather than deparsed, so a LANGUAGE sql body such as INSERT INTO users ... would fail its CREATE-time check under the pinned search_path. pg_dump uses the same setting for the same reason. Run-time behavior of functions is unchanged, and the target schema's bodies were already checked when its DDL was loaded into the temporary database.
  • GetSchema reads on a single connection. search_path is a per-session setting, so a *sql.DB is no longer queried with up to 50 concurrent goroutines. Results are identical; extraction of very large schemas may be slower.

The README "Applying plan" example now shows both SET statements for library users who apply plans themselves.

Motivation

The CLI apply displays a plan, waits for confirmation, and then executes it on a new connection with the default search_path. A role that can create objects in a schema on that path (typically public) can, during that window, create an exact-type overload of a built-in referenced by the plan, for example public.array_length(text[], integer) for an index on array_length(tags, 1). Postgres prefers the best type match across all visible schemas (pg_catalog being implicitly first only breaks ties), so the planned statement binds to the planted function and runs it with the privileges of the migrating role.

This follows the same approach as pg_dump (CVE-2018-1058) and extends #298, which qualified the tool-authored pg_catalog.to_timestamp call.

Testing

All tests run in the repository's build/Dockerfile.test image with -race.

New tests

  • TestCmdTestSuite/TestRunPlanIgnoresFunctionsPlantedOnSearchPath generates a plan that adds an index on array_length(tags, 1), then plants public.array_length(text[], integer) (which writes to a log table), then calls runPlan. It asserts that the index has no dependency on the planted function and that the function never ran.
  • TestSearchPathTestCases adds two acceptance cases: an expression index on a user function in public, and a GIN index using gin_trgm_ops from pg_trgm installed in public.

Without the fix (Postgres 14), the race test fails on both assertions: the index is bound to the planted function and the function executed during the index build.

Error:      Should be zero, but was 1
Messages:   index should not depend on the planted function
Error:      Should be zero, but was 1
--- FAIL: TestCmdTestSuite/TestRunPlanIgnoresFunctionsPlantedOnSearchPath

With only the apply-side pin (extraction unchanged), both acceptance cases fail, showing they guard the extraction half:

CREATE INDEX CONCURRENTLY users_normalized_email_idx ON public.users USING btree (normalize_email(email)): ERROR: function normalize_email(text) does not exist
CREATE INDEX CONCURRENTLY users_name_trgm_idx ON public.users USING gin (name gin_trgm_ops): ERROR: operator class "gin_trgm_ops" does not exist for access method "gin"

With the fix

--- PASS: TestCmdTestSuite/TestRunPlanIgnoresFunctionsPlantedOnSearchPath
--- PASS: TestSearchPathTestCases/Create_expression_index_on_a_function_in_public
--- PASS: TestSearchPathTestCases/Create_GIN_index_with_an_operator_class_from_an_extension_in_public

Full suite passes on Postgres 14 and 17 (go test -race ./...). No acceptance-test expectedPlanDDL changed. The only updated expectations are in internal/schema/schema_test.go, where extracted definitions gain a public. qualifier (for example nextval('public.foo_id_seq'::regclass), EXECUTE FUNCTION public.increment_version()) and two stored schema hashes change accordingly.

Postgres deparse functions such as pg_get_indexdef omit the schema of any object visible on the session's search_path, and apply ran plans with the default search_path. A role able to create objects in a schema on that path (typically public) could plant a better-matching overload, such as public.array_length(text[], integer), between planning and apply, so a planned built-in call resolved to attacker code executed by the migrating role.

Schema extraction now runs with search_path = pg_catalog so every non-built-in reference is schema-qualified, and apply and plan validation run with the same pinned path, so unqualified names can only resolve to built-ins. Function bodies are stored verbatim rather than deparsed, so, like pg_dump, apply also disables check_function_bodies. GetSchema now fetches on a single connection because search_path is a per-session setting.

Co-authored-by: Cursor <cursoragent@cursor.com>
Committed-By-Agent: cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant