diff --git a/CHANGELOG.md b/CHANGELOG.md index 5677e7e1..35f51ca6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ Pre-1.0 note: while `pg_durable` is in major version `0`, minor releases may inc ### Security +- A [dedicated non-superuser worker](USER_GUIDE.md#dedicated-worker-role) can + run with `LOGIN BYPASSRLS`, explicit metadata privileges, and ownership of the + control provider objects. The default `postgres` worker is unchanged. + **Upgrade:** the configured non-superuser worker is reserved for internal + work. Finish workflows submitted as that role before upgrading the binary + or switching worker identities; their user steps are rejected on resume. + No new extension schema is required. - **Start admission quotas (#139):** `df.max_concurrent_per_user` (default `100`) and `df.max_instances_per_user` (default `10000`) limit active and retained instances per submitting role and origin database. Both are diff --git a/README.md b/README.md index 43b2db23..1e87cf08 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,7 @@ GRANT pg_durable_user TO app_backend, etl_service; > **Note:** `GRANT EXECUTE ON ALL FUNCTIONS` only applies to functions that exist when the grant runs. After upgrading pg_durable with `ALTER EXTENSION pg_durable UPDATE`, re-run `df.grant_usage('role')` (or re-issue the manual grants) so new functions are accessible. **Key points:** -- The background worker role (`pg_durable.worker_role` GUC, default: `postgres`) **must be a superuser** — it bypasses RLS to manage all users' instances +- The worker defaults to `postgres`. To run it without `SUPERUSER`, provision a [dedicated `LOGIN BYPASSRLS` role](USER_GUIDE.md#dedicated-worker-role) with metadata grants and control-provider ownership. - Users get `SELECT` + `INSERT` on `df.instances` / `df.nodes`, column-level `UPDATE (status, updated_at)` on instances for `df.cancel()` - Identity column (`submitted_by`) cannot be modified by users - **`df.vars` uses per-user scoping** — each user has their own variable namespace via an `owner` column and RLS. Superusers bypass RLS but DSL functions still scope to the calling user via explicit filters. Avoid storing secrets in plain text diff --git a/USER_GUIDE.md b/USER_GUIDE.md index e9a5fe70..3208b4e5 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -2048,11 +2048,9 @@ All SQL nodes in the function execute against the specified database. The DSL it ### Worker Access and Lifecycle -The default `pg_durable.worker_role` is the `postgres` superuser. A custom worker -role needs `CONNECT` and the required local `df` metadata privileges in each -origin, plus access for origin-local HTTP privilege lookup. `BYPASSRLS` alone -grants none of these privileges. Application grants, including HTTP access, are -also database-local. A satellite admin granted `with_grant => true` can read +The default worker is the `postgres` superuser. Alternatively, provision a +[dedicated non-superuser worker](#dedicated-worker-role). Application grants, +including HTTP access, are database-local. A satellite admin granted `with_grant => true` can read `df.metrics()` totals for **all** users and origins in the shared engine. Dropping a satellite removes its local metadata. Identity validation and metadata @@ -2789,12 +2787,74 @@ own statement logging. Keep credentials out of SQL even when this setting is off ### Security Best Practices -1. **Worker role must be superuser** — The background worker role (`pg_durable.worker_role`) must be a superuser to bypass RLS and manage all instances +1. **Separate the worker from application logins.** Use the [dedicated worker role](#dedicated-worker-role) to manage workflow metadata without `SUPERUSER`. Never grant its membership or provider write access to application roles. 2. **Do not put credentials in `df.vars`** — Variables are scoped per-user via RLS, but they are stored as plaintext and are copied into durable execution history. See [Variables and secrets](#variables-and-secrets) 3. **Use labels carefully** — Instance labels are visible only to the submitting user (RLS-filtered) and superusers 4. **Monitor instances** — Superusers can use `df.list_instances()` to see all users' instances; regular users see only their own 5. **Avoid unsafe `SECURITY DEFINER` wrappers around `df.start()`** — Never allow untrusted callers to supply SQL or futures to `df.start()` from a `SECURITY DEFINER` context unless definer-level execution is intentional. +### Dedicated worker role + +`pg_durable.worker_role` defaults to `postgres`. To run the worker without +`SUPERUSER`, use a dedicated `LOGIN BYPASSRLS` role. It needs no role +memberships, `CREATEDB`, or `CREATEROLE`. `BYPASSRLS` lets the worker see all +users' workflow metadata; it does not grant access to any objects. + +For example, for a fresh control installation in `postgres`, first create the +role as an administrator: + +```sql +CREATE ROLE durable_worker LOGIN NOSUPERUSER BYPASSRLS NOINHERIT; +-- PostgreSQL 17+: prevent login and DDL event triggers in worker sessions. +ALTER ROLE durable_worker SET event_triggers = off; +``` + +Set `pg_durable.worker_role = 'durable_worker'` in `postgresql.conf` and restart. +Connect as the extension installer, **not** as the worker, and run: + +```sql +BEGIN; +CREATE EXTENSION pg_durable; +GRANT CONNECT, CREATE ON DATABASE postgres TO durable_worker; +GRANT USAGE ON SCHEMA df TO durable_worker; +GRANT SELECT, DELETE ON df.instances, df.nodes TO durable_worker; +GRANT UPDATE (status, updated_at, completed_at) ON df.instances TO durable_worker; +GRANT UPDATE (status, result, status_details, updated_at) ON df.nodes TO durable_worker; +GRANT SELECT ON df._installation TO durable_worker; +GRANT SELECT, INSERT, UPDATE, DELETE ON df._worker_epoch TO durable_worker; +ALTER SCHEMA _duroxide OWNER TO durable_worker; +COMMIT; +``` + +The worker creates the engine tables **after** this transaction commits. The +current provider needs database-level `CREATE` even if its schema already +exists. On each satellite, grant `CONNECT` and the same `df` schema and +metadata privileges, but omit database `CREATE`, the epoch-table grants, and +the provider-schema ownership change. Explicitly grant `CONNECT` again when +cloning a database whose `PUBLIC` connection privilege will be revoked. +If you revoke the default `PUBLIC EXECUTE` on `df.duroxide_schema()`, also +grant the worker `EXECUTE` on that function in control. + +**Converting an existing installation:** keep the existing extension and data. +As the installer, grant the metadata privileges above (skip `_installation` or +`status_details` on older schemas where absent). In control, transfer ownership +of the **verified pg_durable provider namespace and its existing tables, +sequences and functions** to the new worker, including its readiness, origins +and submission-ledger tables when present. Fresh installs use `_duroxide`; +upgraded installations may use `duroxide`. Do not reassign the installer's +unrelated objects, the extension itself, or the `df` schema. Then switch the GUC +and restart. Reapply the relevant grants when an extension update adds columns +or tables. No `ALTER EXTENSION UPDATE` is needed just to change worker identity. +The worker logs missing privileges and retries after a grant is repaired. + +Keep the worker login, its schemas, provider objects, and database DDL under +trusted administration: control over engine state can direct work as other +users. Configure local authentication for the worker and submitters without +weakening remote authentication. SQL steps still connect as the submitter, +with that user's normal settings. A configured **non-superuser** worker cannot +submit workflows or execute their user steps. Finish or resubmit any workflows +under that identity before converting. The existing superuser opt-in is unchanged. + ### Privilege Grants `CREATE EXTENSION pg_durable` does **not** grant general `df` usage to `PUBLIC`. diff --git a/docs/api-reference.md b/docs/api-reference.md index b747a36f..21a949ab 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1006,11 +1006,12 @@ This setting is not the default SQL target for satellite starts; their origin is ### pg_durable.worker_role Connection role for worker management, origin routing, and provider operations -(default `postgres`, a superuser; Postmaster context, restart required). A custom -role needs `CONNECT` and required `df` metadata rights in each origin, plus -access for origin-local HTTP privilege lookup. `BYPASSRLS` grants no database, -schema, table, or function privileges by itself. SQL nodes still authenticate as -the captured submitting role in the execution database. +(default `postgres`, also used for an empty setting; Postmaster context, restart +required). A non-superuser worker needs `LOGIN BYPASSRLS`, `CONNECT` and `df` +metadata grants in each origin, plus database `CREATE` and provider ownership +in control. See [Dedicated worker role](../USER_GUIDE.md#dedicated-worker-role) +for the grants and conversion procedure. SQL nodes still authenticate as +the captured submitting role, never as the dedicated non-superuser worker. ### pg_durable.max_origin_connections diff --git a/docs/rls.md b/docs/rls.md index 3d2d1f88..871754c4 100644 --- a/docs/rls.md +++ b/docs/rls.md @@ -196,17 +196,11 @@ CREATE POLICY vars_user_isolation ON df.vars ...; ### Decision 6: Worker role RLS bypass -The background worker must read/write all users' instances and nodes. It also needs to connect as arbitrary users for `execute_sql`, access duroxide schema tables, and perform other privileged operations. - -**Decision**: The worker role **must be a superuser**. ✅ Decided. - -Superusers bypass all permission checks in PostgreSQL, including RLS. This means: -- No `BYPASSRLS` attribute needed (superusers bypass RLS automatically) -- No per-table worker policies needed -- No additional GRANTs to the worker role needed -- Consistent with the existing trust model: the extension is installed by a superuser, and the worker is trusted code - -The worker role is configured via `pg_durable.worker_role` GUC (defaults to `postgres`). The extension should document that this role must be a superuser. +The worker must read and maintain metadata for all submitters. The default +`postgres` superuser bypasses RLS automatically. A dedicated non-superuser worker +instead needs `BYPASSRLS` and [explicit object privileges](../USER_GUIDE.md#dedicated-worker-role). +Neither case needs per-user RLS policy exceptions. Business SQL runs on a +separate connection authenticated as the submitter. ### Decision 7: `df.cancel()` and `df.signal()` ownership checks @@ -294,13 +288,8 @@ The `owner` column defaults to `current_user::regrole` on INSERT, so `df.setvar( ### 4.4 Worker bypass -The worker role must be a superuser (see Decision 6). Superusers bypass RLS automatically — no additional configuration needed. - -```sql --- No RLS bypass configuration needed. --- The worker role (pg_durable.worker_role GUC, default: postgres) must be a superuser. --- Superusers bypass all permission checks including RLS. -``` +Superusers bypass RLS automatically. For a `NOSUPERUSER` worker, see +[Dedicated worker role](../USER_GUIDE.md#dedicated-worker-role). ### 4.5 `FORCE ROW LEVEL SECURITY` @@ -367,7 +356,7 @@ All decisions have been resolved. No open questions remain. ### Resolved decisions - **Decision 5 (vars scoping)**: Option A implemented — per-user scoping with `owner` column + RLS. ✅ Implemented in v0.2.0. -- **Decision 6 (worker bypass)**: Worker role must be a superuser → bypasses RLS automatically. ✅ +- **Decision 6 (worker bypass)**: The worker requires `SUPERUSER` or `BYPASSRLS` with explicit privileges. - **Decision 7 (cancel/signal ownership)**: Explicit ownership check before duroxide client call. ✅ - **Decision 8 (auto-grants)**: No automatic grants to PUBLIC. Admins must explicitly grant privileges to application roles after `CREATE EXTENSION`. ✅ Revised (was auto-grant to PUBLIC in v0.1.1). - **Monitoring functions**: Rework `df.list_instances()`, `df.instance_info()`, `df.instance_executions()`, and `df.instance_nodes()` to only show the calling user's own instances. Currently these functions fetch instance IDs from the duroxide client (which returns ALL instances via the worker's connection), then join with `df.instances` for labels. With RLS, the SPI label query is already filtered — but the duroxide client still returns other users' instance IDs, causing a mismatch. Fix: query `df.instances` via SPI first (RLS-filtered), then use only those IDs when calling the duroxide client. ✅ diff --git a/docs/upgrade-testing.md b/docs/upgrade-testing.md index 73e62319..cd382e3d 100644 --- a/docs/upgrade-testing.md +++ b/docs/upgrade-testing.md @@ -98,6 +98,12 @@ previous compatible release. Unlike the reconstructed-schema tests above, this test builds and runs the tagged **previous binary** to produce real instances, results and durable histories before installing the candidate. +The harness exercises both the default superuser and conversion to a dedicated +non-superuser worker. In the conversion run (`--non-superuser-worker`), it +provisions the old installation, restarts with the new identity **before** +`ALTER EXTENSION UPDATE`, waits for a new worker epoch, and resumes the same +histories. After the schema upgrade it reapplies the metadata grants. + The same database is retained through three phases: | Phase | Binary | Extension schema | Assertions | @@ -109,7 +115,8 @@ The same database is retained through three phases: The additional `seq-binary-b2` instance preserves the original lifecycle's new-binary/old-schema to new-binary/new-schema scenario. Together with the N-1 family instances, it verifies that histories created both before and after -the binary swap survive the schema upgrade. The final phase validates 18 instances. +the binary swap survive the schema upgrade. Including the SQL quoting cases, +the final phase validates 21 instances in each worker configuration. #### Behavior-family coverage diff --git a/scripts/test-e2e-local.sh b/scripts/test-e2e-local.sh index 7f3515e1..43398fe5 100755 --- a/scripts/test-e2e-local.sh +++ b/scripts/test-e2e-local.sh @@ -1122,6 +1122,15 @@ for run in $(seq 1 "$REPEAT_COUNT"); do run_phase "$phase" done + if [ -z "$TEST_FILTER" ] && contains_value "standard" "${ACTIVE_PHASES[@]}"; then + echo -e "${CYAN}=== non-superuser worker lifecycle ===${NC}" + if python3 "$SCRIPT_DIR/worker_role_lifecycle.py" --pg-config "$PG_CONFIG"; then + TOTAL_PASSED=$((TOTAL_PASSED + 1)) + else + TOTAL_FAILED=$((TOTAL_FAILED + 1)) + fi + fi + if [ "$REPEAT_COUNT" -gt 1 ]; then echo "" fi diff --git a/scripts/test-upgrade.sh b/scripts/test-upgrade.sh index 5eb91683..0d8f0c25 100755 --- a/scripts/test-upgrade.sh +++ b/scripts/test-upgrade.sh @@ -333,10 +333,10 @@ TESTS_RUN=0 run_test() { local test_name="$1" - local test_func="$2" + shift TESTS_RUN=$((TESTS_RUN + 1)) echo -n " $test_name ... " - if eval "$test_func"; then + if "$@"; then echo -e "${GREEN}PASSED${NC}" PASSED=$((PASSED + 1)) else @@ -1434,7 +1434,7 @@ test_b2_endpoint_catalog_after_upgrade() { test_previous_binary_lifecycle() { python3 "$SCRIPT_DIR/upgrade_lifecycle.py" --pg-config "$PG_CONFIG" \ - --previous-version "$PREV_VERSION" + --previous-version "$PREV_VERSION" "$@" } if [ "$HAS_COMPAT_PREV" = true ]; then @@ -1447,6 +1447,8 @@ if [ "$HAS_COMPAT_PREV" = true ]; then run_test "B2: HTTP OIDs, grants and dependent views survive upgrade" test_b2_http_api_after_upgrade run_test "B2: Endpoint FDW, validator and delegated catalog DDL work after upgrade" test_b2_endpoint_catalog_after_upgrade run_test "B1/B2: Real previous-binary instances survive both upgrade stages" test_previous_binary_lifecycle + run_test "B1/B2: Previous-binary instances survive worker role conversion" \ + test_previous_binary_lifecycle --non-superuser-worker fi # ============================================================================ diff --git a/scripts/test_upgrade_lifecycle.py b/scripts/test_upgrade_lifecycle.py index d9b49d8b..0b447738 100644 --- a/scripts/test_upgrade_lifecycle.py +++ b/scripts/test_upgrade_lifecycle.py @@ -228,6 +228,36 @@ def test_failed_instance_is_not_retried_until_timeout(self): class LifecycleTests(unittest.TestCase): + @patch.object(lifecycle, "run", return_value="") + def test_worker_role_controls_startup(self, run): + with tempfile.TemporaryDirectory() as directory: + cluster = lifecycle.Cluster(Path(directory), Path(directory), 1) + cluster.worker_role = lifecycle.WORKER_ROLE + cluster.start() + arguments = run.call_args.args + self.assertIn(f"pg_durable.worker_role={lifecycle.WORKER_ROLE}", + arguments[arguments.index("-o") + 1]) + + @patch.object(lifecycle, "install") + def test_non_superuser_conversion_precedes_binary_upgrade(self, install): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) + cluster = Mock(prefix=output, schema="_duroxide") + cluster.sql.side_effect = lambda query, **kwargs: ( + "t" if "FROM pg_stat_activity" in query else "999") + cluster.validate.return_value = [] + events = Mock() + events.attach_mock(cluster, "cluster") + events.attach_mock(install, "install") + lifecycle.exercise(cluster, "0.2.9", "0.2.10", "old", "new", output, + non_superuser_worker=True) + calls = events.mock_calls + self.assertLess(calls.index(unittest.mock.call.cluster.provision_worker()), + calls.index(unittest.mock.call.install("new", output))) + self.assertEqual(cluster.provision_worker.call_count, 2) + cluster.wait_for_new_epoch.assert_called_once_with("999") + self.assertEqual(cluster.worker_role, lifecycle.WORKER_ROLE) + def test_start_sequence_captures_variables_then_changes_live_values(self): for waiting in (True, False): with tempfile.TemporaryDirectory() as directory, self.subTest(waiting=waiting): diff --git a/scripts/upgrade_lifecycle.py b/scripts/upgrade_lifecycle.py index c9a4ad28..0ca4e5e7 100644 --- a/scripts/upgrade_lifecycle.py +++ b/scripts/upgrade_lifecycle.py @@ -20,6 +20,7 @@ PROJECT = Path(__file__).resolve().parents[1] ROLE = "upgrade_lifecycle_user" +WORKER_ROLE = "pgd_nonsuper_worker" # Behavior families, each exercised by an N-1 instance suspended inside that # structure and resumed under both the B1 (new binary / old schema) and B2 @@ -80,7 +81,7 @@ def build(source, output, pg_config, pg_major): before = lock.read_bytes() # Both versions emit libpg_durable.so; never share their final build artifacts. target = PROJECT / "target" if source == PROJECT else PROJECT / f"target/upgrade-previous-pg{pg_major}" - env = dict(os.environ, CARGO_TARGET_DIR=str(target)) + env = dict(os.environ, CARGO_TARGET_DIR=str(target), PGRX_PG_CONFIG_PATH=str(pg_config)) features = ["--no-default-features", "--features", f"pg{pg_major}"] manifest = ["--manifest-path", str(source / "Cargo.toml")] print(f"Building {source}; log: {output / 'build.log'}", flush=True) @@ -123,6 +124,7 @@ def __init__(self, prefix, output, timeout): self.log = output / "postgres.log" self.timeout = timeout self.schema = None + self.worker_role = "postgres" with socket.socket() as listener: listener.bind(("127.0.0.1", 0)) self.port = listener.getsockname()[1] @@ -134,7 +136,7 @@ def initialize(self): def start(self): options = ( f"-p {self.port} -c listen_addresses=127.0.0.1 -c unix_socket_directories='' " - "-c shared_preload_libraries=pg_durable -c pg_durable.worker_role=postgres " + f"-c shared_preload_libraries=pg_durable -c pg_durable.worker_role={self.worker_role} " "-c pg_durable.database=postgres" ) run(self.prefix / "bin/pg_ctl", "-D", self.data, "-l", self.log, @@ -146,20 +148,38 @@ def stop(self): run(self.prefix / "bin/pg_ctl", "-D", self.data, "-m", "fast", "-w", "-t", "60", "stop") - def sql(self, query, role=None): - if role: - query = 'SET ROLE "' + role.replace('"', '""') + '"; ' + query + def psql(self, *arguments, database="postgres"): return run(self.prefix / "bin/psql", "-X", "-qAt", "-h", "127.0.0.1", - "-p", self.port, "-U", "postgres", "-d", "postgres", - "-v", "ON_ERROR_STOP=1", "-c", query, + "-p", self.port, "-U", "postgres", "-d", database, + "-v", "ON_ERROR_STOP=1", *arguments, env=dict(os.environ, PGCONNECT_TIMEOUT=str(max(1, math.ceil(self.timeout))), PGOPTIONS=f"-c statement_timeout={max(1, math.ceil(self.timeout * 1000))}")) + def sql(self, query, role=None, database="postgres"): + if role: + query = 'SET ROLE "' + role.replace('"', '""') + '"; ' + query + return self.psql("-c", query, database=database) + + def provision_worker(self, database="postgres"): + self.sql("SET LOCAL search_path = pg_catalog, pg_temp; " + f"SELECT pg_catalog.set_config('pg_durable_test.worker_role', {literal(WORKER_ROLE)}, true); " + + (PROJECT / "tests/e2e/worker_role.sql").read_text(), + database=database) + def versions(self, binary, schema): require_equal(self.sql("SELECT split_part(df.version(), ' ', 1);"), binary) require_equal(self.sql( "SELECT extversion FROM pg_extension WHERE extname='pg_durable';"), schema) + def wait_for_new_epoch(self, previous): + deadline = time.monotonic() + self.timeout + while time.monotonic() < deadline: + if self.sql("SELECT EXISTS (SELECT FROM df._worker_epoch " + f"WHERE epoch_id::text <> {literal(previous)})") == "t": + return + time.sleep(0.1) + raise RuntimeError(f"No new worker epoch after conversion; see {self.log}") + def ready(self): self.schema = ( self.sql("SELECT df.duroxide_schema();") @@ -327,7 +347,8 @@ def case_problems(case, completed): return problems -def exercise(cluster, previous, current, old_package, new_package, output): +def exercise(cluster, previous, current, old_package, new_package, output, + non_superuser_worker=False): completed = {} names = [f"{family}-b1" for family in FAMILIES] + [f"{family}-b2" for family in FAMILIES] @@ -358,10 +379,21 @@ def check(phase, binary, schema): check("baseline", previous, previous) # B1: also create new-binary history to resume across the schema upgrade. + if non_superuser_worker: + old_epoch = cluster.sql("SELECT epoch_id::text FROM df._worker_epoch") + cluster.provision_worker() + cluster.worker_role = WORKER_ROLE cluster.stop() install(new_package, cluster.prefix) cluster.start() cluster.ready() + if non_superuser_worker: + # The old readiness row survives a binary-only upgrade. + cluster.wait_for_new_epoch(old_epoch) + require_equal(cluster.sql( + "SELECT count(*) > 0 AND bool_and(usename=" + f"{literal(WORKER_ROLE)}) FROM pg_stat_activity " + "WHERE application_name='pg_durable:worker:management'"), "t") check("b1-before-resume", current, previous) for family in FAMILIES: cluster.release(f"{family}-b1") @@ -373,6 +405,8 @@ def check(phase, binary, schema): # B2: new binary, new schema. Resume every -b2 case and start a fresh one. cluster.sql(f"ALTER EXTENSION pg_durable UPDATE TO {literal(current)};") + if non_superuser_worker: + cluster.provision_worker() check("b2-before-resume", current, current) for family in FAMILIES: cluster.release(f"{family}-b2") @@ -389,6 +423,8 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--pg-config", type=Path, required=True) parser.add_argument("--previous-version", required=True) + parser.add_argument("--non-superuser-worker", action="store_true", + help="Convert to a dedicated BYPASSRLS worker before the binary upgrade") parser.add_argument("--output-dir", type=Path, help="New directory for builds, logs and phase results") parser.add_argument("--timeout", type=float, default=60) args = parser.parse_args() @@ -424,12 +460,13 @@ def main(): new_package = build(PROJECT, output / "candidate", pg_config, pg_major) (output / "versions.json").write_text(json.dumps({ "previous": previous, "previous_commit": commit, "candidate": current, + "candidate_worker_role": WORKER_ROLE if args.non_superuser_worker else "postgres", "postgres": run(pg_config, "--version"), }, indent=2) + "\n") prefix = output / "postgres" shutil.copytree(pg_config.parent.parent, prefix) exercise(Cluster(prefix, output, args.timeout), previous, current, - old_package, new_package, output) + old_package, new_package, output, args.non_superuser_worker) return 0 except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: message = getattr(error, "stderr", None) or str(error) diff --git a/scripts/worker_role_lifecycle.py b/scripts/worker_role_lifecycle.py new file mode 100644 index 00000000..bd19559a --- /dev/null +++ b/scripts/worker_role_lifecycle.py @@ -0,0 +1,416 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. +# Licensed under the PostgreSQL License. +"""Exercise a minimally privileged worker, conversion, and privilege failures.""" + +import argparse +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time + +from upgrade_lifecycle import ( + Cluster, PROJECT, WORKER_ROLE, build, install, literal, require_equal, run, +) + + +def wait_for(cluster, query, expected="t", database="postgres"): + deadline = time.monotonic() + cluster.timeout + while True: + actual = cluster.sql(query, database=database) + if actual == expected: + return + if time.monotonic() >= deadline: + raise RuntimeError(f"Timed out waiting for {query!r}: {actual!r}; see {cluster.log}") + time.sleep(0.1) + + +def epoch(cluster): + return cluster.sql("SELECT epoch_id::text FROM df._worker_epoch;") + + +def restart_ready(cluster): + previous = epoch(cluster) + cluster.stop() + cluster.start() + cluster.wait_for_new_epoch(previous) + + +def assert_worker(cluster): + require_equal(cluster.sql( + f"SELECT rolsuper, rolbypassrls, rolcreatedb, rolcreaterole, rolreplication " + f"FROM pg_roles WHERE rolname={literal(WORKER_ROLE)};"), "f|t|f|f|f") + require_equal(cluster.sql( + f"SELECT has_database_privilege({literal(WORKER_ROLE)}, 'postgres', 'CREATE'), " + f"has_table_privilege({literal(WORKER_ROLE)}, 'df.instances', 'UPDATE'), " + f"has_column_privilege({literal(WORKER_ROLE)}, 'df.instances', 'submitted_by', 'UPDATE');"), + "t|f|f") + require_equal(cluster.sql( + "SELECT count(DISTINCT a.application_name) = 3 AND bool_and(r.rolname=" + f"{literal(WORKER_ROLE)} AND NOT r.rolsuper) " + "FROM pg_stat_activity a JOIN pg_roles r ON r.oid=a.usesysid " + "WHERE a.application_name IN ('pg_durable:worker:management', " + "'pg_durable:worker:poll', 'pg_durable:worker:duroxide');"), "t") + + +def expect_submission_rejected(cluster, mode): + try: + cluster.sql(f"SELECT df.start('SELECT 1', transaction_mode => {literal(mode)});", + role=WORKER_ROLE) + except subprocess.CalledProcessError as error: + if "cannot submit or execute workflows" not in error.stderr: + raise + else: + raise RuntimeError(f"Worker identity was accepted for transaction_mode={mode}") + + +def expect_startup_failure(cluster, setup, repair, message): + previous = epoch(cluster) + cluster.sql(setup) + cluster.stop() + mark = cluster.log.stat().st_size + cluster.start() + wait_for_log(cluster, message, mark) + require_equal(epoch(cluster), previous) + cluster.sql(repair) + cluster.wait_for_new_epoch(previous) + assert_worker(cluster) + + +def wait_for_log(cluster: Cluster, message: str, mark: int) -> None: + deadline = time.monotonic() + cluster.timeout + while message.encode() not in cluster.log.read_bytes()[mark:]: + if time.monotonic() >= deadline: + raise RuntimeError(f"Expected diagnostic {message!r}; see {cluster.log}") + time.sleep(0.1) + + +@contextmanager +def table_lock(cluster: Cluster, relation: str) -> Iterator[None]: + cluster.sql("UPDATE public.worker_lock_gate SET release_lock=false;") + with ThreadPoolExecutor(max_workers=1) as executor: + holder = executor.submit(cluster.sql, f""" + SET application_name = 'pg_durable:lock-test'; + BEGIN; + LOCK TABLE {relation} IN SHARE MODE; + DO $$ BEGIN + WHILE NOT (SELECT release_lock FROM public.worker_lock_gate) LOOP + PERFORM pg_sleep(0.05); + END LOOP; + END $$; + COMMIT; + """) + try: + wait_for(cluster, f""" + SELECT EXISTS ( + SELECT FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid + WHERE a.application_name='pg_durable:lock-test' + AND l.relation={literal(relation)}::regclass + AND l.mode='ShareLock' AND l.granted); + """) + yield + finally: + cluster.sql("UPDATE public.worker_lock_gate SET release_lock=true;") + holder.result(timeout=cluster.timeout) + + +def assert_write_blocked(cluster: Cluster, relation: str, application: str) -> None: + waiting = f""" + FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid + WHERE a.application_name={literal(application)} + AND l.relation={literal(relation)}::regclass + AND l.mode='RowExclusiveLock' AND NOT l.granted + """ + wait_for(cluster, f"SELECT EXISTS (SELECT {waiting});") + pid, started = cluster.sql( + f"SELECT a.pid, a.query_start {waiting} ORDER BY a.pid LIMIT 1;").split("|") + # The same write must remain blocked beyond the former 1.5-second limit, + # not fail and be replaced by another attempt on the same connection. + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + require_equal(cluster.sql( + f"SELECT EXISTS (SELECT {waiting} AND a.pid={int(pid)} " + f"AND a.query_start={literal(started)}::timestamptz);"), "t") + time.sleep(0.1) + + +def exercise_worker_lock_waits(cluster: Cluster) -> None: + cluster.sql(""" + CREATE TABLE public.worker_lock_gate (release_sql boolean, release_lock boolean); + INSERT INTO public.worker_lock_gate VALUES (false, false); + GRANT SELECT ON public.worker_lock_gate TO df_e2e_user; + CREATE TABLE public.worker_lock_effects (test_name text, actor text); + GRANT INSERT ON public.worker_lock_effects TO df_e2e_user; + CREATE FUNCTION public.worker_lock_activity(test_name text) RETURNS void + LANGUAGE plpgsql AS $$ BEGIN + PERFORM pg_advisory_xact_lock(8231, 1); + WHILE NOT (SELECT release_sql FROM public.worker_lock_gate) LOOP + PERFORM pg_sleep(0.05); + END LOOP; + INSERT INTO public.worker_lock_effects VALUES (test_name, current_user); + END $$; + """) + for relation, application in ( + (f"{cluster.schema}.history", "pg_durable:worker:duroxide"), + (f"{cluster.schema}.worker_queue", "pg_durable:worker:duroxide"), + ("df.instances", "pg_durable:worker:management"), + ("df.nodes", "pg_durable:worker:management"), + ("df._worker_epoch", "pg_durable:worker:poll"), + ): + previous_epoch = epoch(cluster) + cluster.sql("UPDATE public.worker_lock_gate SET release_sql=false;") + query = literal(f"SELECT public.worker_lock_activity({literal(relation)})") + instance = cluster.sql(f"SELECT df.start({query});", role="df_e2e_user") + wait_for(cluster, "SELECT EXISTS (SELECT FROM pg_locks " + "WHERE locktype='advisory' AND classid=8231 AND objid=1 AND granted);") + with table_lock(cluster, relation): + # Keep the SQL activity running throughout a blocked heartbeat. + if relation != "df._worker_epoch": + cluster.sql("UPDATE public.worker_lock_gate SET release_sql=true;") + assert_write_blocked(cluster, relation, application) + cluster.sql("UPDATE public.worker_lock_gate SET release_sql=true;") + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed';") + require_equal(epoch(cluster), previous_epoch) + require_equal(cluster.sql( + "SELECT count(*) > 0 AND bool_and(status='completed') FROM df.nodes " + f"WHERE instance_id={literal(instance)};"), "t") + require_equal(cluster.sql( + "SELECT count(*), bool_and(actor='df_e2e_user') FROM public.worker_lock_effects " + f"WHERE test_name={literal(relation)};"), "1|t") + print(f"PASS: {cluster.worker_role or 'postgres'} waits for {relation} " + "without losing status, resetting the epoch, or repeating SQL", flush=True) + + instance = cluster.sql("SELECT df.start(df.wait_for_signal('provider-lock'));", + role="df_e2e_user") + wait_for(cluster, f"SELECT EXISTS (SELECT FROM {cluster.schema}.history " + f"WHERE instance_id={literal(instance)} " + "AND event_data::jsonb->>'type'='ExternalSubscribed' " + "AND event_data::jsonb->>'name'='provider-lock');") + with ThreadPoolExecutor(max_workers=1) as executor: + signal = None + try: + with table_lock(cluster, f"{cluster.schema}.orchestrator_queue"): + signal = executor.submit( + cluster.sql, + f"SELECT df.signal({literal(instance)}, 'provider-lock', '{{}}');", + role="df_e2e_user") + assert_write_blocked( + cluster, f"{cluster.schema}.orchestrator_queue", + "pg_durable:backend:duroxide") + finally: + if signal is not None: + signal.result(timeout=cluster.timeout) + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed';") + cluster.sql("DROP FUNCTION public.worker_lock_activity(text); " + "DROP TABLE public.worker_lock_gate, public.worker_lock_effects;") + print(f"PASS: {cluster.worker_role or 'postgres'} backend provider waits for signal lock", + flush=True) + + +def exercise(cluster, pg_major): + cluster.initialize() + try: + cluster.worker_role = "" + cluster.start() + cluster.sql("CREATE EXTENSION pg_durable;") + cluster.ready() + require_equal(cluster.sql("SHOW pg_durable.worker_role;"), "") + require_equal(cluster.sql( + "SELECT count(*) > 0 AND bool_and(usename='postgres') FROM pg_stat_activity " + "WHERE application_name='pg_durable:worker:management';"), "t") + cluster.sql( + "CREATE ROLE df_e2e_user LOGIN; " + "GRANT USAGE, CREATE ON SCHEMA public TO df_e2e_user; " + "SELECT df.grant_usage('df_e2e_user', include_http => true); " + "CREATE TABLE public.worker_role_effects (phase text, actor text); " + "GRANT SELECT, INSERT ON public.worker_role_effects TO df_e2e_user;") + exercise_worker_lock_waits(cluster) + instance = cluster.sql( + "SELECT df.start(df.seq(" + "'INSERT INTO public.worker_role_effects VALUES (''before'', current_user)', " + "df.seq(df.wait_for_signal('worker-conversion'), " + "'INSERT INTO public.worker_role_effects VALUES (''after'', current_user)')));", + role="df_e2e_user") + wait_for(cluster, f"SELECT EXISTS (SELECT FROM {cluster.schema}.history " + f"WHERE instance_id={literal(instance)} AND event_data::jsonb->>'type'='ExternalSubscribed' " + "AND event_data::jsonb->>'name'='worker-conversion');") + # A workflow admitted before the role switch must not acquire worker rights on resume. + cluster.sql(f"CREATE ROLE {WORKER_ROLE} LOGIN BYPASSRLS NOINHERIT; " + f"SELECT df.grant_usage({literal(WORKER_ROLE)}); " + f"GRANT INSERT ON public.worker_role_effects TO {WORKER_ROLE}") + reserved = cluster.sql( + "SELECT df.start(df.seq(df.wait_for_signal('resume'), " + "'INSERT INTO public.worker_role_effects VALUES (''reserved'', current_user)'))", + role=WORKER_ROLE) + wait_for(cluster, f"SELECT EXISTS (SELECT FROM {cluster.schema}.history " + f"WHERE instance_id={literal(reserved)} AND event_data::jsonb->>'type'='ExternalSubscribed')") + cluster.sql(f"SELECT df.revoke_usage({literal(WORKER_ROLE)})") + cluster.provision_worker() + cluster.worker_role = WORKER_ROLE + restart_ready(cluster) + assert_worker(cluster) + cluster.sql(f"SELECT df.signal({literal(instance)}, 'worker-conversion', '{{}}');", + role="df_e2e_user") + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed';") + require_equal(cluster.sql( + "SELECT phase, actor FROM public.worker_role_effects ORDER BY phase;"), + "after|df_e2e_user\nbefore|df_e2e_user") + cluster.sql(f"SELECT df.signal({literal(reserved)}, 'resume', '{{}}')") + wait_for(cluster, f"SELECT df.status({literal(reserved)})='failed'") + require_equal(cluster.sql("SELECT count(*) FROM public.worker_role_effects " + "WHERE phase='reserved'"), "0") + print("PASS: superuser-to-non-superuser conversion preserved suspended work", flush=True) + + cluster.sql("CREATE DATABASE worker_role_origin;") + cluster.sql("CREATE EXTENSION pg_durable; " + "SELECT df.grant_usage('df_e2e_user');", database="worker_role_origin") + cluster.provision_worker(database="worker_role_origin") + instance = cluster.sql("SELECT df.start('SELECT current_user AS identity');", + role="df_e2e_user", database="worker_role_origin") + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed';", + database="worker_role_origin") + require_equal(cluster.sql( + f"SELECT df.result({literal(instance)})::jsonb->'rows'->0->>'identity';", + database="worker_role_origin"), "df_e2e_user") + require_equal(cluster.sql( + f"SELECT has_table_privilege({literal(WORKER_ROLE)}, 'df._worker_epoch', " + "'INSERT,UPDATE,DELETE');", database="worker_role_origin"), "f") + print("PASS: satellite execution uses the submitter and minimum metadata grants", flush=True) + + mark = cluster.log.stat().st_size + cluster.sql(f"REVOKE DELETE ON df.nodes FROM {WORKER_ROLE};", + database="worker_role_origin") + instance = cluster.sql("SELECT df.start('SELECT current_user');", + role="df_e2e_user", database="worker_role_origin") + wait_for_log(cluster, "Origin worker preflight failed: Worker role requires DELETE on df.nodes", + mark) + cluster.sql(f"GRANT DELETE ON df.nodes TO {WORKER_ROLE};", + database="worker_role_origin") + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed';", + database="worker_role_origin") + print("PASS: missing satellite privileges are diagnosed and recover after repair", flush=True) + + for mode in ("caller", "new"): + expect_submission_rejected(cluster, mode) + print("PASS: worker identity rejected at both submission entry points", flush=True) + + # A non-superuser worker still maintains the quota ledger. The public + # client must not require table access to that ledger as the submitter. + cluster.sql("SET df.max_instances_per_user=1; SET ROLE df_e2e_user; " + "DO $$ BEGIN " + "PERFORM df.start('SELECT 1'); " + "RAISE EXCEPTION 'expected retained-instance quota rejection'; " + "EXCEPTION WHEN configuration_limit_exceeded THEN NULL; END $$") + print("PASS: submission quotas still apply with a non-superuser worker", flush=True) + + cluster.sql( + "CREATE ROLE worker_role_decoy; " + f"GRANT worker_role_decoy TO {WORKER_ROLE}; " + "CREATE SCHEMA worker_role_hostile; " + "GRANT USAGE ON SCHEMA worker_role_hostile TO PUBLIC; " + "CREATE FUNCTION worker_role_hostile.hashtext(text) RETURNS integer " + "LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'UNSAFE_WORKER_SEARCH_PATH'; END $$;") + settings = { + "search_path": "worker_role_hostile,pg_catalog", + "role": "worker_role_decoy", + "default_transaction_read_only": "on", + "default_transaction_isolation": "serializable", + "default_tablespace": "pg_default", + "statement_timeout": "1ms", + "lock_timeout": "1ms", + "idle_in_transaction_session_timeout": "1ms", + } + if pg_major >= 14: + settings["idle_session_timeout"] = "1ms" + if pg_major >= 17: + settings["transaction_timeout"] = "1ms" + for name, value in settings.items(): + cluster.sql(f"ALTER ROLE {WORKER_ROLE} IN DATABASE postgres SET {name}={literal(value)};") + restart_ready(cluster) + instance = cluster.sql("SELECT df.start('SELECT 1');", role="df_e2e_user") + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed';") + exercise_worker_lock_waits(cluster) + cluster.sql(f"ALTER ROLE {WORKER_ROLE} IN DATABASE postgres RESET ALL;") + cluster.sql(f"REVOKE worker_role_decoy FROM {WORKER_ROLE}; DROP ROLE worker_role_decoy;") + print("PASS: worker startup options override hostile role/database defaults", flush=True) + + for setup, repair, message in ( + (f"ALTER ROLE {WORKER_ROLE} NOLOGIN;", + f"ALTER ROLE {WORKER_ROLE} LOGIN;", "is not permitted to log in"), + (f"ALTER ROLE {WORKER_ROLE} NOBYPASSRLS;", + f"ALTER ROLE {WORKER_ROLE} BYPASSRLS;", "requires BYPASSRLS or SUPERUSER"), + (f"REVOKE USAGE ON SCHEMA df FROM {WORKER_ROLE};", + f"GRANT USAGE ON SCHEMA df TO {WORKER_ROLE};", "requires USAGE on schema df"), + (f"REVOKE CREATE ON DATABASE postgres FROM {WORKER_ROLE};", + f"GRANT CREATE ON DATABASE postgres TO {WORKER_ROLE};", + "requires CREATE on the control database"), + ("REVOKE EXECUTE ON FUNCTION df.duroxide_schema() FROM PUBLIC;", + "GRANT EXECUTE ON FUNCTION df.duroxide_schema() TO PUBLIC;", + "permission denied for function duroxide_schema"), + (f"REVOKE DELETE ON df.nodes FROM {WORKER_ROLE};", + f"GRANT DELETE ON df.nodes TO {WORKER_ROLE};", "requires DELETE on df.nodes"), + (f"REVOKE UPDATE (status_details) ON df.nodes FROM {WORKER_ROLE};", + f"GRANT UPDATE (status_details) ON df.nodes TO {WORKER_ROLE};", + "requires UPDATE (status_details) on df.nodes"), + (f"ALTER SCHEMA {cluster.schema} OWNER TO postgres;", + f"ALTER SCHEMA {cluster.schema} OWNER TO {WORKER_ROLE};", + "requires ownership of provider schema"), + (f"ALTER TABLE {cluster.schema}._worker_ready OWNER TO postgres;", + f"ALTER TABLE {cluster.schema}._worker_ready OWNER TO {WORKER_ROLE};", + "requires ownership of provider object"), + ): + expect_startup_failure(cluster, setup, repair, message) + print(f"PASS: {message}", flush=True) + + # A fresh control install must not depend on engine tables that only + # the worker can create after the install transaction is visible. + cluster.sql("DROP EXTENSION pg_durable CASCADE") + cluster.sql("CREATE EXTENSION pg_durable") + cluster.provision_worker() + cluster.ready() + wait_for(cluster, "SELECT EXISTS (SELECT FROM df._worker_epoch)") + cluster.sql("SELECT df.grant_usage('df_e2e_user')") + instance = cluster.sql("SELECT df.start('SELECT current_user AS actor')", role="df_e2e_user") + wait_for(cluster, f"SELECT df.status({literal(instance)})='completed'") + require_equal(cluster.sql( + f"SELECT df.result({literal(instance)})::jsonb->'rows'->0->>'actor'"), "df_e2e_user") + assert_worker(cluster) + print("PASS: fresh provider and submission ledger initialized by non-superuser", flush=True) + finally: + cluster.stop() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--pg-config", type=Path, required=True) + parser.add_argument("--timeout", type=int, default=60) + args = parser.parse_args() + if args.timeout <= 0: + parser.error("--timeout must be positive") + parent = PROJECT / "target/worker-role-lifecycle" + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(dir=parent)) + print(f"Worker-role lifecycle evidence: {output}", flush=True) + try: + pg_config = args.pg_config.resolve() + pg_major = int(run(pg_config, "--version").split()[1].split(".")[0]) + package = build(PROJECT, output / "candidate", pg_config, pg_major) + prefix = output / "postgres" + shutil.copytree(pg_config.parent.parent, prefix) + install(package, prefix) + exercise(Cluster(prefix, output, args.timeout), pg_major) + return 0 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: + message = getattr(error, "stderr", None) or str(error) + (output / "error.txt").write_text(message + "\n") + print(f"Worker-role lifecycle FAILED: {message}\nSee {output}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/activities/execute_http.rs b/src/activities/execute_http.rs index a91b1736..47362c30 100644 --- a/src/activities/execute_http.rs +++ b/src/activities/execute_http.rs @@ -62,8 +62,8 @@ pub(crate) async fn check_http_privilege( } else { "df.http" }; - let has_priv: Option = sqlx::query_scalar( - "SELECT COALESCE(pg_catalog.has_function_privilege( + let role: Option<(bool, bool)> = sqlx::query_as( + "SELECT role.rolsuper, COALESCE(pg_catalog.has_function_privilege( role.oid, pg_catalog.to_regprocedure($2)::pg_catalog.oid, 'EXECUTE'), false) FROM pg_catalog.pg_roles AS role WHERE role.rolname OPERATOR(pg_catalog.=) $1", ) @@ -76,13 +76,16 @@ pub(crate) async fn check_http_privilege( .await .map_err(|error| format!("HTTP privilege check close failed: {error}"))?; - match has_priv { - Some(true) => Ok(()), - _ => Err(format!( - "Blocked: role '{submitted_by}' does not have EXECUTE privilege on {function}() for this request. \ - Required function: {signature}. Use df.grant_usage with include_http => true to allow HTTP requests." - )), + if let Some((is_super, has_priv)) = role { + crate::types::reject_worker_execution_role(submitted_by, is_super)?; + if has_priv { + return Ok(()); + } } + Err(format!( + "Blocked: role '{submitted_by}' does not have EXECUTE privilege on {function}() for this request. \ + Required function: {signature}. Use df.grant_usage with include_http => true to allow HTTP requests." + )) } /// Build a reqwest Client with optional SSRF-safe DNS resolver. diff --git a/src/activities/load_function_graph.rs b/src/activities/load_function_graph.rs index e5156227..7899c9d8 100644 --- a/src/activities/load_function_graph.rs +++ b/src/activities/load_function_graph.rs @@ -318,21 +318,23 @@ async fn load_visible_graph( // Worker-side superuser guard: reject before executing any user SQL. // This closes the forgery path where a BYPASSRLS role inserts rows with // submitted_by = directly, bypassing the df.start() check. - if !superuser_instances_enabled() { - match is_role_superuser_name(pool, &instance_submitted_by).await { - Ok(true) => { - return Err(LoadGraphError::Permanent(format!( - "pg_durable blocked instance {instance_id}: submitted_by role \ + let allow_super = superuser_instances_enabled(); + if !allow_super || instance_submitted_by == crate::types::get_worker_role() { + let is_super = is_role_superuser_name(pool, &instance_submitted_by) + .await + .map_err(|e| { + LoadGraphError::Retryable(format!( + "pg_durable: superuser check failed for instance {instance_id}: {e}" + )) + })?; + crate::types::reject_worker_execution_role(&instance_submitted_by, is_super) + .map_err(LoadGraphError::Permanent)?; + if is_super && !allow_super { + return Err(LoadGraphError::Permanent(format!( + "pg_durable blocked instance {instance_id}: submitted_by role \ \"{instance_submitted_by}\" is a superuser, but \ pg_durable.enable_superuser_instances is off" - ))); - } - Ok(false) => {} - Err(e) => { - return Err(LoadGraphError::Retryable(format!( - "pg_durable: superuser check failed for instance {instance_id}: {e}" - ))); - } + ))); } } diff --git a/src/activities/update_instance_status.rs b/src/activities/update_instance_status.rs index 2a5288d0..a8ca5f20 100644 --- a/src/activities/update_instance_status.rs +++ b/src/activities/update_instance_status.rs @@ -10,6 +10,13 @@ use std::sync::Arc; /// Activity name for registration and scheduling pub const NAME: &str = "pg_durable::activity::update-instance-status"; +#[derive(Debug, PartialEq, Eq)] +enum StatusUpdate { + Updated, + AlreadyTerminal, + Missing, +} + /// Update the status of an instance in df.instances pub async fn execute( ctx: ActivityContext, @@ -30,6 +37,35 @@ pub async fn execute( "Updating instance {instance_id} status to {status}" )); + let updated = update_status(&mut tx, instance_id, status) + .await + .inspect_err(|error| ctx.trace_info(error))?; + tx.commit() + .await + .map_err(|error| format!("Instance status commit failed: {error}"))?; + match updated { + StatusUpdate::Updated => { + ctx.trace_info(format!("Instance {instance_id} status updated to {status}")); + Ok(format!("Status updated to {status}")) + } + StatusUpdate::AlreadyTerminal => { + ctx.trace_info(format!("Instance {instance_id} is already terminal")); + Ok("Instance is already terminal".to_string()) + } + StatusUpdate::Missing => { + ctx.trace_info(format!( + "Instance {instance_id} metadata is absent; no status update" + )); + Ok("Instance metadata is absent".to_string()) + } + } +} + +async fn update_status( + connection: &mut sqlx::PgConnection, + instance_id: &str, + status: &str, +) -> Result { // Never overwrite a terminal state ('completed', 'failed', 'cancelled') with any status. // This prevents a race where an in-flight activity (scheduled just before cancel was // processed) tries to flip the status back from 'cancelled' to 'running'/'completed'. @@ -53,18 +89,135 @@ pub async fn execute( .bind(instance_id) }; - match query.execute(&mut *tx).await { - Ok(_) => { - tx.commit() + let result = query + .execute(&mut *connection) + .await + .map_err(|error| format!("Failed to update instance status: {error}"))?; + if result.rows_affected() != 0 { + return Ok(StatusUpdate::Updated); + } + let (rls_active, exists, existing): (bool, bool, Option) = sqlx::query_as( + "SELECT pg_catalog.row_security_active('df.instances'::pg_catalog.regclass), + EXISTS (SELECT FROM df.instances WHERE id OPERATOR(pg_catalog.=) $1), + (SELECT status FROM df.instances WHERE id OPERATOR(pg_catalog.=) $1)", + ) + .bind(instance_id) + .fetch_one(&mut *connection) + .await + .map_err(|error| format!("Instance status visibility check failed: {error}"))?; + if rls_active { + return Err( + "pg_durable worker cannot bypass row-level security on df.instances".to_string(), + ); + } + // A rolled-back df.start() legitimately leaves no metadata. The + // engine must still finish that instance rather than retry forever. + if !exists { + return Ok(StatusUpdate::Missing); + } + match existing.as_deref() { + Some("completed" | "failed" | "cancelled") => Ok(StatusUpdate::AlreadyTerminal), + _ => Err(format!( + "Instance {instance_id} status update affected no row (current status: {existing:?})" + )), + } +} + +#[cfg(any(test, feature = "pg_test"))] +#[pgrx::pg_schema] +mod tests { + use super::*; + use pgrx::prelude::*; + use sqlx::Connection; + + /// Distinguish terminal/rolled-back instances from metadata hidden by RLS. + #[pg_test] + fn instance_status_visibility_test() { + let admin = Spi::get_one::("SELECT current_user::text") + .unwrap() + .unwrap(); + let database = Spi::get_one::("SELECT current_database()::text") + .unwrap() + .unwrap(); + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + let mut connection = + crate::origin::metadata_test_connection(&admin, &database).await; + let mut tx = connection.begin().await.unwrap(); + let id = crate::types::short_id(); + sqlx::query( + "INSERT INTO df.instances (id, root_node, submitted_by) + VALUES ($1, $1, CURRENT_USER::pg_catalog.regrole)", + ) + .bind(&id) + .execute(&mut *tx) .await - .map_err(|error| format!("Instance status commit failed: {error}"))?; - ctx.trace_info(format!("Instance {instance_id} status updated to {status}")); - Ok(format!("Status updated to {status}")) - } - Err(e) => { - let err_msg = format!("Failed to update instance status: {e}"); - ctx.trace_info(&err_msg); - Err(err_msg) - } + .unwrap(); + assert_eq!( + update_status(&mut tx, &id, "running").await.unwrap(), + StatusUpdate::Updated + ); + for terminal in ["completed", "failed", "cancelled"] { + sqlx::query("UPDATE df.instances SET status=$1 WHERE id=$2") + .bind(terminal) + .bind(&id) + .execute(&mut *tx) + .await + .unwrap(); + assert_eq!( + update_status(&mut tx, &id, "running").await.unwrap(), + StatusUpdate::AlreadyTerminal + ); + let stored: String = + sqlx::query_scalar("SELECT status FROM df.instances WHERE id=$1") + .bind(&id) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(stored, terminal); + } + sqlx::query("UPDATE df.instances SET status=NULL WHERE id=$1") + .bind(&id) + .execute(&mut *tx) + .await + .unwrap(); + assert!(update_status(&mut tx, &id, "running") + .await + .unwrap_err() + .contains("current status")); + sqlx::raw_sql( + "CREATE ROLE pgd_status_visibility_test NOLOGIN; + GRANT USAGE ON SCHEMA df TO pgd_status_visibility_test; + GRANT SELECT, UPDATE ON df.instances TO pgd_status_visibility_test; + SAVEPOINT visibility_check; + SET LOCAL row_security = on; + SET LOCAL ROLE pgd_status_visibility_test;", + ) + .execute(&mut *tx) + .await + .unwrap(); + assert!(update_status(&mut tx, &id, "running") + .await + .unwrap_err() + .contains("row-level security")); + sqlx::query("ROLLBACK TO SAVEPOINT visibility_check") + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("DELETE FROM df.instances WHERE id=$1") + .bind(&id) + .execute(&mut *tx) + .await + .unwrap(); + assert_eq!( + update_status(&mut tx, &id, "completed").await.unwrap(), + StatusUpdate::Missing + ); + tx.rollback().await.unwrap(); + connection.close().await.unwrap(); + }); } } diff --git a/src/dsl.rs b/src/dsl.rs index e2e32890..b1c698ba 100644 --- a/src/dsl.rs +++ b/src/dsl.rs @@ -1396,6 +1396,9 @@ fn start_in_caller_transaction(fut: &str, label: Option<&str>, database: Option< Ok(v) => v, Err(e) => pgrx::error!("pg_durable: superuser check failed: {}", e), }; + if let Err(error) = crate::types::reject_worker_execution_role(¤t_user_name, is_super) { + pgrx::error!("{error}"); + } if is_super && !crate::types::superuser_instances_enabled() { pgrx::error!( "pg_durable: superuser instances are disabled. \ diff --git a/src/lib.rs b/src/lib.rs index 8270f91c..6563046e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -759,25 +759,23 @@ BEGIN END; $fn$; --- Validate that the worker role is a superuser. --- The background worker must bypass RLS to manage all users' instances/nodes. --- If the worker role is not a superuser, workflows will silently fail because --- RLS will filter out rows the worker needs to read/update. +-- Without RLS bypass, the worker cannot manage other users' metadata. DO $$ DECLARE - wrole TEXT; - is_super BOOLEAN; + wrole pg_catalog.text; + bypasses_rls pg_catalog.bool; BEGIN wrole := pg_catalog.current_setting('pg_durable.worker_role', true); IF wrole IS NULL OR wrole OPERATOR(pg_catalog.=) '' THEN wrole := 'postgres'; END IF; - SELECT rolsuper INTO is_super FROM pg_catalog.pg_roles WHERE rolname OPERATOR(pg_catalog.=) wrole; - IF is_super IS NULL THEN - RAISE WARNING 'pg_durable: worker role "%" does not exist. The background worker will not be able to process workflows. Create the role as a superuser before using pg_durable.', wrole; - ELSIF NOT is_super THEN - RAISE WARNING 'pg_durable: worker role "%" is not a superuser. The background worker must be a superuser to bypass RLS and manage all users'' instances. Grant superuser or BYPASSRLS to this role.', wrole; + SELECT rolsuper OR rolbypassrls INTO bypasses_rls + FROM pg_catalog.pg_roles WHERE rolname OPERATOR(pg_catalog.=) wrole; + IF bypasses_rls IS NULL THEN + RAISE WARNING 'pg_durable: worker role "%" does not exist. Processing cannot start until the role is created with LOGIN, RLS bypass, and the required object permissions.', wrole; + ELSIF NOT bypasses_rls THEN + RAISE WARNING 'pg_durable: worker role "%" cannot bypass row-level security. Configure BYPASSRLS and the required object permissions, or use a superuser worker.', wrole; END IF; END $$; diff --git a/src/origin.rs b/src/origin.rs index 5af02173..e474a9ab 100644 --- a/src/origin.rs +++ b/src/origin.rs @@ -22,7 +22,11 @@ pub(crate) enum RoutingError { impl RoutingError { fn database(operation: &str, error: sqlx::Error) -> Self { let message = format!("{operation}: {error}"); - if crate::activities::load_function_graph::is_retryable_database_error(&error) { + // Only worker metadata routing uses this classification. Missing + // CONNECT/USAGE can be repaired during the graph probe's retry window. + if error.as_database_error().and_then(|e| e.code()).as_deref() == Some("42501") + || crate::activities::load_function_graph::is_retryable_database_error(&error) + { Self::Retryable(message) } else { Self::Permanent(message) @@ -330,10 +334,10 @@ pub(crate) struct Route { impl Route { pub async fn validate(&self) -> Result<(), String> { - self.validate_typed().await.map_err(String::from) + self.validate_typed(false).await.map_err(String::from) } - async fn validate_typed(&self) -> Result<(), RoutingError> { + async fn validate_typed(&self, check_worker_grants: bool) -> Result<(), RoutingError> { if let Some(origin) = self.origin.as_ref() { let mut tx = self.pool.begin().await.map_err(|error| { @@ -349,6 +353,13 @@ impl Route { lock_and_validate(&mut tx, origin) .await .map_err(|error| RoutingError::database("Origin admission unavailable", error))?; + if check_worker_grants { + crate::worker::validate_worker_privileges(&mut tx, false) + .await + .map_err(|e| { + RoutingError::Retryable(format!("Origin worker preflight failed: {e}")) + })?; + } tx.rollback() .await .map_err(|error| RoutingError::database("Origin admission close failed", error))?; @@ -449,7 +460,7 @@ impl Router { origin: Some(origin.clone()), permit: Some(permit), }; - route.validate_typed().await?; + route.validate_typed(true).await?; Ok(route) } } diff --git a/src/types.rs b/src/types.rs index dd7da3f7..ca252b4c 100644 --- a/src/types.rs +++ b/src/types.rs @@ -27,19 +27,51 @@ pub(crate) const BACKEND_MONITORING_APPLICATION_NAME: &str = "pg_durable:backend pub(crate) const BACKEND_NEW_TRANSACTION_APPLICATION_NAME: &str = "pg_durable:backend:new-transaction"; +const WORKER_SESSION_OPTIONS: &[(&str, &str)] = &[ + ("search_path", "pg_catalog,pg_temp"), + ("role", "none"), + ("row_security", "off"), + ("default_transaction_read_only", "off"), + ("default_transaction_isolation", r"read\ committed"), + ("default_tablespace", ""), + ("statement_timeout", "0"), + // The provider treats lock timeouts as permanent failures, not retries. + ("lock_timeout", "0"), + #[cfg(not(feature = "pg13"))] + ("idle_session_timeout", "0"), + ("idle_in_transaction_session_timeout", "0"), + #[cfg(any(feature = "pg17", feature = "pg18"))] + ("transaction_timeout", "0"), +]; + // ============================================================================ // Configuration Functions // ============================================================================ /// Get the worker role from the `pg_durable.worker_role` GUC. -/// Falls back to `"postgres"` if the GUC is not set. +/// Falls back to `"postgres"` if the GUC is unset or empty. pub fn get_worker_role() -> String { crate::WORKER_ROLE .get() .map(|cs: CString| cs.to_string_lossy().into_owned()) + .filter(|role| !role.is_empty()) .unwrap_or_else(|| "postgres".to_string()) } +pub(crate) fn reject_worker_execution_role( + role_name: &str, + is_superuser: bool, +) -> Result<(), String> { + // Preserve the explicit superuser-instance opt-in, but never let the + // non-superuser worker become a workflow execution identity. + if !is_superuser && role_name == get_worker_role() { + return Err(format!( + "pg_durable worker role {role_name:?} cannot submit or execute workflows" + )); + } + Ok(()) +} + /// Get the database from the `pg_durable.database` GUC. /// Falls back to `"postgres"` if the GUC is not set. pub fn get_database() -> String { @@ -208,11 +240,20 @@ pub fn postgres_connection_string() -> String { let user = get_worker_role(); let database = get_database(); - build_connection_url(&user, &host, port, &database) + worker_connection_url(&build_connection_url(&user, &host, port, &database)) } -pub(crate) fn postgres_connection_string_with_application_name(application_name: &str) -> String { - connection_url_with_application_name(&postgres_connection_string(), application_name) +fn worker_connection_url(database_url: &str) -> String { + // Startup options outrank database/role defaults. row_security=off raises + // an error instead of silently hiding metadata if BYPASSRLS is revoked. + let options = WORKER_SESSION_OPTIONS + .iter() + .map(|(name, value)| format!("-c {name}={value}")) + .collect::>() + .join(" "); + let separator = if database_url.contains('?') { '&' } else { '?' }; + let encoded = utf8_percent_encode(&options, NON_ALPHANUMERIC); + format!("{database_url}{separator}options={encoded}") } pub(crate) fn connection_url_with_application_name( @@ -247,6 +288,8 @@ fn host_is_url_safe(host: &str) -> bool { /// metacharacters stays inert and fails to resolve instead of injecting a /// different host or extra connection parameters. fn build_connection_url(user: &str, host: &str, port: i32, database: &str) -> String { + let user = utf8_percent_encode(user, NON_ALPHANUMERIC); + let database = utf8_percent_encode(database, NON_ALPHANUMERIC); if host_is_url_safe(host) { format!("postgres://{user}@{host}:{port}/{database}") } else { @@ -350,14 +393,26 @@ async fn connect_as_user_with_application_name( ) })?; - // Mark this connection as running inside a workflow. - // Currently used to prevent variable mutations (setvar/unsetvar/clearvars) - // during execution. Could also be checked in df.start() to prevent - // recursive workflow invocation in a future improvement. - sqlx::query("SET df.in_workflow = 'true'") - .execute(&mut conn) - .await - .map_err(|e| format!("SET df.in_workflow failed: {}", e))?; + // Old histories may already carry the worker's name. Check the actual + // session before handing it to user SQL; don't override user GUCs here. + let worker = get_worker_role(); + let marked = sqlx::query( + "SELECT pg_catalog.set_config('df.in_workflow', 'true', false) + WHERE NOT EXISTS ( + SELECT FROM pg_catalog.pg_roles + WHERE rolname OPERATOR(pg_catalog.=) $1 AND NOT rolsuper + AND (rolname OPERATOR(pg_catalog.=) SESSION_USER + OR rolname OPERATOR(pg_catalog.=) CURRENT_USER))", + ) + .bind(&worker) + .fetch_optional(&mut conn) + .await + .map_err(|e| format!("SET df.in_workflow failed: {}", e))?; + if marked.is_none() { + return Err(format!( + "pg_durable worker role {worker:?} cannot submit or execute workflows" + )); + } Ok(conn) } @@ -567,7 +622,7 @@ pub(crate) async fn read_backend_control_state( /// The BGW resolves this once per epoch (after the extension is detected) rather /// than caching for the process lifetime, because drop+recreate can switch the /// provider schema within a single worker lifetime. -pub async fn resolve_duroxide_schema_pool(pool: &sqlx::PgPool) -> String { +pub async fn resolve_duroxide_schema_pool(pool: &sqlx::PgPool) -> Result { let helper_exists: bool = sqlx::query_scalar( "SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_proc p \ JOIN pg_catalog.pg_namespace n ON n.oid OPERATOR(pg_catalog.=) p.pronamespace \ @@ -576,20 +631,18 @@ pub async fn resolve_duroxide_schema_pool(pool: &sqlx::PgPool) -> String { AND p.pronargs OPERATOR(pg_catalog.=) 0)", ) .fetch_one(pool) - .await - .unwrap_or(false); + .await?; if !helper_exists { - return LEGACY_DUROXIDE_SCHEMA.to_string(); + return Ok(LEGACY_DUROXIDE_SCHEMA.to_string()); } - match sqlx::query_scalar::<_, String>("SELECT df.duroxide_schema()") + let schema = sqlx::query_scalar::<_, String>("SELECT df.duroxide_schema()") .fetch_one(pool) - .await - { - Ok(s) if !s.is_empty() => s, - _ => LEGACY_DUROXIDE_SCHEMA.to_string(), - } + .await?; + backend_schema_name(&schema) + .map(str::to_owned) + .map_err(sqlx::Error::Protocol) } /// Create a `ProviderConfig` for backend (request/response) operations. @@ -2802,6 +2855,44 @@ mod tests { ); } + #[test] + fn worker_url_preserves_role_and_database_names() { + let url = worker_connection_url(&build_connection_url( + "Worker @ops", + "/tmp", + 5432, + "control?db/name", + )); + let options = sqlx::postgres::PgConnectOptions::from_str(&url).unwrap(); + assert_eq!(options.get_username(), "Worker @ops"); + assert_eq!(options.get_database(), Some("control?db/name")); + assert!(options.get_options().unwrap().contains("-c role=none")); + } + + #[test] + fn worker_connection_options_test() { + let url = worker_connection_url("postgres://worker@localhost/app?sslmode=disable"); + let options = sqlx::postgres::PgConnectOptions::from_str(&url).unwrap(); + let settings = options.get_options().unwrap(); + for (name, value) in WORKER_SESSION_OPTIONS { + assert!(settings.contains(&format!("-c {name}={value}"))); + } + assert!(settings.contains("-c lock_timeout=0")); + assert!(!settings.contains("-c lock_timeout=1500ms")); + assert_eq!(options.get_username(), "worker"); + assert_eq!(options.get_database(), Some("app")); + assert!(matches!( + options.get_ssl_mode(), + sqlx::postgres::PgSslMode::Disable + )); + + let backend = backend_control_connection_options(&url).unwrap(); + assert!(backend + .get_options() + .unwrap() + .ends_with("-c statement_timeout=1500ms -c lock_timeout=1500ms")); + } + #[test] fn application_names_are_valid_postgresql_names() { for application_name in [ @@ -2825,12 +2916,18 @@ mod tests { let opts = sqlx::postgres::PgConnectOptions::from_str(&url).expect("provider URL should parse"); assert_eq!(opts.get_application_name(), Some(expected)); + let settings = opts.get_options().unwrap(); + assert!(settings.contains("-c lock_timeout=0")); + assert!(!settings.contains("-c lock_timeout=1500ms")); } #[test] fn backend_provider_uses_backend_application_name() { assert_provider_application_name( - backend_provider_config("postgres://worker@localhost/app", "_duroxide"), + backend_provider_config( + &worker_connection_url("postgres://worker@localhost/app"), + "_duroxide", + ), BACKEND_DUROXIDE_APPLICATION_NAME, ); } @@ -2838,7 +2935,10 @@ mod tests { #[test] fn worker_provider_uses_worker_application_name() { assert_provider_application_name( - worker_provider_config("postgres://worker@localhost/app", "_duroxide"), + worker_provider_config( + &worker_connection_url("postgres://worker@localhost/app"), + "_duroxide", + ), WORKER_DUROXIDE_APPLICATION_NAME, ); } diff --git a/src/worker.rs b/src/worker.rs index 4bdbca18..2e308d90 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -25,8 +25,8 @@ use crate::ssrf::{DomainAllowlist, HttpPolicy}; use crate::types::{ get_max_duroxide_connections, get_max_management_connections, get_max_user_connections, get_reconcile_interval, get_retention_days, postgres_connection_string, - postgres_connection_string_with_application_name, resolve_duroxide_schema_pool, - worker_provider_config, WORKER_MANAGEMENT_APPLICATION_NAME, WORKER_POLL_APPLICATION_NAME, + resolve_duroxide_schema_pool, worker_provider_config, WORKER_MANAGEMENT_APPLICATION_NAME, + WORKER_POLL_APPLICATION_NAME, }; // Retention policy for terminal ('completed'/'failed'/'cancelled') instances. @@ -149,10 +149,6 @@ async fn run_duroxide_runtime(http_policy: Arc) { const STALE_RUNTIME_RETRY_INTERVAL: Duration = Duration::from_secs(1); let pg_conn_str = postgres_connection_string(); - let management_conn_str = - postgres_connection_string_with_application_name(WORKER_MANAGEMENT_APPLICATION_NAME); - let poll_conn_str = - postgres_connection_string_with_application_name(WORKER_POLL_APPLICATION_NAME); log!( "pg_durable: background worker connected to PostgreSQL at {}", pg_conn_str, @@ -186,75 +182,23 @@ async fn run_duroxide_runtime(http_policy: Arc) { user_conns ); - // Management pool: consolidates former polling and activity pools into one. - // Used for graph loading and status updates. Sized by the max_management_connections GUC. - // Retry in a loop so the worker survives the target database not yet existing - // (e.g. pg_regress creates `contrib_regression` after PostgreSQL starts). - // - // The connect() call uses acquire_timeout so a slow or shutting-down - // PostgreSQL does not block indefinitely on the first attempt. - let mgmt_pool = loop { - if is_shutdown_requested() { - log!("pg_durable: shutdown requested before management pool created, exiting"); - return; - } - match sqlx::postgres::PgPoolOptions::new() - .max_connections(mgmt_conns) - .acquire_timeout(Duration::from_secs(5)) - .connect(&management_conn_str) - .await - { - Ok(pool) => break pool, - Err(e) => { - log!( - "pg_durable: failed to create management pool (will retry in 5s): {}", - e - ); - // Sleep interruptibly so shutdown does not wait a full 5s. - tokio::select! { - _ = tokio::time::sleep(Duration::from_secs(5)) => {} - _ = wait_for_shutdown() => { - log!("pg_durable: shutdown requested during management pool retry, exiting"); - return; - } - } - } - } + let Some(mgmt_pool) = + connect_worker_pool(&pg_conn_str, WORKER_MANAGEMENT_APPLICATION_NAME, mgmt_conns).await + else { + return; }; // Dedicated polling pool: a separate 1-connection pool used exclusively for // extension-existence checks and epoch sentinel heartbeats. This isolation // prevents activity work (graph loading, status updates) from starving the // health-check loop and causing spurious runtime shutdowns under high load. - let poll_pool = loop { - if is_shutdown_requested() { - log!("pg_durable: shutdown requested before poll pool created, exiting"); - return; - } - match sqlx::postgres::PgPoolOptions::new() - .max_connections(1) - .acquire_timeout(Duration::from_secs(5)) - .connect(&poll_conn_str) - .await - { - Ok(pool) => break pool, - Err(e) => { - log!( - "pg_durable: failed to create poll pool (will retry in 5s): {}", - e - ); - // Sleep interruptibly so shutdown does not wait a full 5s. - tokio::select! { - _ = tokio::time::sleep(Duration::from_secs(5)) => {} - _ = wait_for_shutdown() => { - log!("pg_durable: shutdown requested during poll pool retry, exiting"); - return; - } - } - } - } + let Some(poll_pool) = connect_worker_pool(&pg_conn_str, WORKER_POLL_APPLICATION_NAME, 1).await + else { + mgmt_pool.close().await; + return; }; + let mut readiness_retry_interval = INIT_RETRY_INTERVAL; loop { if is_shutdown_requested() { log!("pg_durable: shutdown requested, exiting"); @@ -288,29 +232,25 @@ async fn run_duroxide_runtime(http_policy: Arc) { } }; - // Resolve the duroxide provider schema for this epoch. The extension may - // have been dropped and recreated with a different schema version (e.g. - // a fresh `_duroxide` install vs. a legacy `duroxide` install), so we - // must re-resolve after every CREATE EXTENSION rather than once at startup. - let duroxide_schema = resolve_duroxide_schema_pool(&mgmt_pool).await; - log!( - "pg_durable: using duroxide provider schema '{}' for this epoch", - duroxide_schema - ); - - let Some((duroxide_runtime, duroxide_store)) = initialize_duroxide_runtime( - &pg_conn_str, - INIT_RETRY_INTERVAL, - &mgmt_pool, - &duroxide_schema, - epoch_oid, - &http_policy, - ) - .await - else { - // Shutdown or the installation changed while initializing. - continue; - }; + let (duroxide_runtime, duroxide_store) = + match initialize_duroxide_runtime(&pg_conn_str, &mgmt_pool, epoch_oid, &http_policy) + .await + { + Ok(runtime) => runtime, + Err(error) => { + log!( + "pg_durable: worker initialization failed (will retry in {}s): {}", + readiness_retry_interval.as_secs(), + error + ); + if !sleep_or_shutdown(readiness_retry_interval).await { + break; + } + readiness_retry_interval = next_initialization_retry(readiness_retry_interval); + continue; + } + }; + readiness_retry_interval = INIT_RETRY_INTERVAL; // Test-only pause that widens the window between runtime initialization // and epoch revalidation so a regression test can drop/recreate the @@ -470,6 +410,38 @@ async fn sleep_or_shutdown(duration: Duration) -> bool { } } +fn next_initialization_retry(current: Duration) -> Duration { + current.saturating_mul(2).min(Duration::from_secs(60)) +} + +async fn connect_worker_pool( + database_url: &str, + application_name: &str, + max_connections: u32, +) -> Option { + let url = crate::types::connection_url_with_application_name(database_url, application_name); + let mut delay = Duration::from_secs(1); + while !is_shutdown_requested() { + match sqlx::postgres::PgPoolOptions::new() + .max_connections(max_connections) + .acquire_timeout(Duration::from_secs(5)) + .connect(&url) + .await + { + Ok(pool) => return Some(pool), + Err(error) => log!( + "pg_durable: failed to create {application_name} pool (will retry in {}s): {error}", + delay.as_secs() + ), + } + if !sleep_or_shutdown(delay).await { + break; + } + delay = next_initialization_retry(delay); + } + None +} + /// Test-only hook: when the `PG_DURABLE_TEST_PAUSE_BEFORE_READY_MS` environment /// variable is set to a positive integer, sleep that many milliseconds between /// runtime initialization and epoch revalidation. This creates a deterministic @@ -644,7 +616,10 @@ END $$"#, /// schema namespace entry itself) is still registered as an extension member. /// Used to short-circuit `release_extension_owned_duroxide_objects` on the /// common path (fresh 0.2.0 installs and all restarts after the first upgrade). -async fn has_extension_owned_duroxide_objects(pool: &sqlx::PgPool, schema_name: &str) -> bool { +async fn has_extension_owned_duroxide_objects( + pool: &sqlx::PgPool, + schema_name: &str, +) -> Result { let result: Result<(bool,), sqlx::Error> = sqlx::query_as( "SELECT EXISTS ( SELECT 1 @@ -673,17 +648,175 @@ async fn has_extension_owned_duroxide_objects(pool: &sqlx::PgPool, schema_name: .bind(schema_name) .fetch_one(pool) .await; - result.map(|(b,)| b).unwrap_or(false) + result.map(|(owned,)| owned) +} + +/// Return whether the session is a superuser after checking its login, identity and access. +async fn validate_worker_identity( + conn: &mut sqlx::PgConnection, + expected: &str, +) -> Result { + let (name, can_login, superuser, bypass_rls, can_connect): (String, bool, bool, bool, bool) = + sqlx::query_as( + "SELECT rolname, rolcanlogin, rolsuper, rolbypassrls, + pg_catalog.has_database_privilege(CURRENT_USER, pg_catalog.current_database(), 'CONNECT') + FROM pg_catalog.pg_roles WHERE rolname OPERATOR(pg_catalog.=) CURRENT_USER + AND rolname OPERATOR(pg_catalog.=) SESSION_USER", + ) + .fetch_one(conn) + .await + .map_err(|error| format!("Worker identity check failed: {error}"))?; + if name != expected { + return Err(format!( + "Worker session uses role {name:?}, expected {expected:?}" + )); + } + if !can_login { + return Err(format!("Worker role {name:?} requires LOGIN")); + } + if !superuser && !bypass_rls { + return Err(format!( + "Worker role {name:?} requires BYPASSRLS or SUPERUSER" + )); + } + if !can_connect { + return Err(format!( + "Worker role {name:?} requires CONNECT on its database" + )); + } + Ok(superuser) +} + +pub(crate) async fn validate_worker_privileges( + conn: &mut sqlx::PgConnection, + control: bool, +) -> Result<(), String> { + // Avoid a table/column ACL scan on every origin connection when the + // operator uses the default superuser, which bypasses those checks. + if validate_worker_identity(conn, &crate::types::get_worker_role()).await? { + return Ok(()); + } + let query_error = |error| format!("Worker privilege check failed: {error}"); + let usage: bool = + sqlx::query_scalar("SELECT pg_catalog.has_schema_privilege(CURRENT_USER, 'df', 'USAGE')") + .fetch_one(&mut *conn) + .await + .map_err(query_error)?; + if !usage { + return Err("Worker role requires USAGE on schema df".to_string()); + } + let missing: Option = sqlx::query_scalar( + "SELECT pg_catalog.format('%s on %s', privilege, relation) + FROM (VALUES + ('df.instances', 'SELECT'), ('df.instances', 'DELETE'), + ('df.nodes', 'SELECT'), ('df.nodes', 'DELETE'), + ('df._worker_epoch', 'SELECT'), ('df._worker_epoch', 'INSERT'), + ('df._worker_epoch', 'UPDATE'), ('df._worker_epoch', 'DELETE'), + ('df._installation', 'SELECT') + ) AS required(relation, privilege) + WHERE ($1 OR relation OPERATOR(pg_catalog.<>) 'df._worker_epoch') + AND (relation OPERATOR(pg_catalog.<>) 'df._installation' + OR pg_catalog.to_regclass(relation) IS NOT NULL) + AND NOT COALESCE(pg_catalog.has_table_privilege( + CURRENT_USER, pg_catalog.to_regclass(relation), privilege), false) + LIMIT 1", + ) + .bind(control) + .fetch_optional(&mut *conn) + .await + .map_err(query_error)?; + if let Some(missing) = missing { + return Err(format!("Worker role requires {missing}")); + } + // Only status_details is optional: it was added in 0.2.4. + let missing: Option = sqlx::query_scalar( + "SELECT pg_catalog.format('UPDATE (%I) on %s', required.column_name, required.relation) + FROM (VALUES + ('df.instances', 'status'), ('df.instances', 'updated_at'), + ('df.instances', 'completed_at'), ('df.nodes', 'status'), + ('df.nodes', 'result'), ('df.nodes', 'status_details'), ('df.nodes', 'updated_at') + ) AS required(relation, column_name) + LEFT JOIN pg_catalog.pg_attribute AS attribute + ON attribute.attrelid OPERATOR(pg_catalog.=) pg_catalog.to_regclass(required.relation) + AND attribute.attname OPERATOR(pg_catalog.=) required.column_name + AND NOT attribute.attisdropped + WHERE (attribute.attnum IS NULL AND required.column_name OPERATOR(pg_catalog.<>) 'status_details') + OR NOT pg_catalog.has_column_privilege( + CURRENT_USER, attribute.attrelid, attribute.attnum, 'UPDATE') + LIMIT 1", + ) + .fetch_optional(conn) + .await + .map_err(query_error)?; + if let Some(missing) = missing { + return Err(format!("Worker role requires {missing}")); + } + Ok(()) +} + +async fn validate_provider_privileges( + pool: &sqlx::PgPool, + schema_name: &str, +) -> Result<(), String> { + let query_error = |error| format!("Worker privilege check failed: {error}"); + let can_create: bool = sqlx::query_scalar( + "SELECT pg_catalog.has_database_privilege(CURRENT_USER, pg_catalog.current_database(), 'CREATE')", + ) + .fetch_one(pool) + .await + .map_err(query_error)?; + if !can_create { + return Err("Worker role requires CREATE on the control database".to_string()); + } + let owns_schema: Option = sqlx::query_scalar( + "SELECT pg_catalog.pg_has_role(CURRENT_USER, nspowner, 'USAGE') + FROM pg_catalog.pg_namespace WHERE nspname OPERATOR(pg_catalog.=) $1", + ) + .bind(schema_name) + .fetch_optional(pool) + .await + .map_err(query_error)?; + if owns_schema != Some(true) { + return Err(format!( + "Worker role requires ownership of provider schema {schema_name:?}" + )); + } + let missing_owner: Option = sqlx::query_scalar( + "SELECT object_name FROM ( + SELECT pg_catalog.format('%I.%I', namespace.nspname, relation.relname) AS object_name, + relation.relowner AS owner + FROM pg_catalog.pg_class AS relation + JOIN pg_catalog.pg_namespace AS namespace + ON namespace.oid OPERATOR(pg_catalog.=) relation.relnamespace + WHERE namespace.nspname OPERATOR(pg_catalog.=) $1 + UNION ALL + SELECT function.oid::pg_catalog.regprocedure::pg_catalog.text, function.proowner + FROM pg_catalog.pg_proc AS function + JOIN pg_catalog.pg_namespace AS namespace + ON namespace.oid OPERATOR(pg_catalog.=) function.pronamespace + WHERE namespace.nspname OPERATOR(pg_catalog.=) $1 + ) AS provider_objects + WHERE NOT pg_catalog.pg_has_role(CURRENT_USER, owner, 'USAGE') + LIMIT 1", + ) + .bind(schema_name) + .fetch_optional(pool) + .await + .map_err(query_error)?; + if let Some(object) = missing_owner { + return Err(format!( + "Worker role requires ownership of provider object {object}" + )); + } + Ok(()) } async fn initialize_duroxide_runtime( pg_conn_str: &str, - retry_interval: Duration, mgmt_pool: &sqlx::PgPool, - schema_name: &str, epoch_oid: i64, http_policy: &Arc, -) -> Option<(Arc, Arc)> { +) -> Result<(Arc, Arc), String> { log!("pg_durable: initializing duroxide runtime..."); // Control duroxide provider pool size via env var (the only mechanism @@ -704,100 +837,56 @@ async fn initialize_duroxide_runtime( let user_semaphore = Arc::new(tokio::sync::Semaphore::new( get_max_user_connections() as usize )); - - loop { - if is_shutdown_requested() { - log!("pg_durable: shutdown requested during initialization"); - return None; - } - - if !check_extension_exists(mgmt_pool).await { - log!("pg_durable: extension no longer exists; returning to wait state"); - return None; - } - - if !check_duroxide_schema_owned(mgmt_pool, schema_name).await { - log!( - "pg_durable: duroxide schema missing or not extension-owned \ - (CREATE EXTENSION may still be in progress) — will retry" - ); - tokio::select! { - _ = tokio::time::sleep(retry_interval) => {} - _ = wait_for_shutdown() => { return None; } - } - continue; - } - - // Release any duroxide objects still owned by the extension so migration - // scripts (which use DROP/CREATE FUNCTION) can run freely. This is a - // no-op on fresh installs; on upgrades from ≤0.1.1 it de-registers the - // embedded DDL from the extension before ApplyAll runs. - // The existence check avoids executing the five-loop DO block on every - // clean restart once the upgrade has already been applied. - if has_extension_owned_duroxide_objects(mgmt_pool, schema_name).await { - if let Err(e) = release_extension_owned_duroxide_objects(mgmt_pool, schema_name).await { - log!( - "pg_durable: failed to release extension-owned duroxide objects (will retry): {}", - e - ); - tokio::select! { - _ = tokio::time::sleep(retry_interval) => {} - _ = wait_for_shutdown() => { return None; } - } - continue; - } - } - - let store = match PostgresProvider::new_with_config(worker_provider_config( - pg_conn_str, - schema_name, - )) + { + let mut conn = mgmt_pool.acquire().await.map_err(|e| e.to_string())?; + validate_worker_privileges(&mut conn, true).await?; + } + let schema = resolve_duroxide_schema_pool(mgmt_pool) .await - { - Ok(s) => Arc::new(s), - Err(e) => { - log!( - "pg_durable: failed to create PostgreSQL store (will retry): {}", - e - ); - tokio::select! { - _ = tokio::time::sleep(retry_interval) => {} - _ = wait_for_shutdown() => { return None; } - } - continue; - } - }; + .map_err(|e| format!("cannot resolve the control provider schema: {e}"))?; + if !check_duroxide_schema_owned(mgmt_pool, &schema).await { + return Err(format!( + "provider schema {schema:?} is missing or not an extension member" + )); + } + validate_provider_privileges(mgmt_pool, &schema).await?; + if has_extension_owned_duroxide_objects(mgmt_pool, &schema) + .await + .map_err(|e| e.to_string())? + { + release_extension_owned_duroxide_objects(mgmt_pool, &schema).await.map_err(|e| + format!("cannot release legacy provider extension members; initialize with the extension installer before changing worker roles: {e}"))?; + } + let store = Arc::new( + PostgresProvider::new_with_config(worker_provider_config(pg_conn_str, &schema)) + .await + .map_err(|e| format!("failed to create PostgreSQL store: {e}"))?, + ); - // Resumed workflow SQL can call df.start(), which requires both the - // submission ledger and current readiness before dispatch begins. - if let Err(error) = write_worker_ready(mgmt_pool, schema_name, epoch_oid).await { - log!( - "pg_durable: failed to write worker readiness record: {}", - error - ); - store.pool().close().await; - sleep_or_shutdown(retry_interval).await; - return None; - } + // Resumed workflow SQL can call df.start(), which requires both the + // submission ledger and current readiness before dispatch begins. + if let Err(error) = write_worker_ready(mgmt_pool, &schema, epoch_oid).await { + store.pool().close().await; + return Err(format!("failed to write worker readiness record: {error}")); + } - // Reuse the management pool for activities (graph loading, status updates). - // The former dedicated activity pool with its df.in_workflow hook is no - // longer needed — connect_as_user() sets that flag independently. - let activities = create_activity_registry( - Arc::new(mgmt_pool.clone()), - user_semaphore.clone(), - http_policy.clone(), - ); - let orchestrations = create_orchestration_registry(); + // Reuse the management pool for activities (graph loading, status updates). + // The former dedicated activity pool with its df.in_workflow hook is no + // longer needed — connect_as_user() sets that flag independently. + let activities = create_activity_registry( + Arc::new(mgmt_pool.clone()), + user_semaphore.clone(), + http_policy.clone(), + ); + let orchestrations = create_orchestration_registry(); - let store_for_client = store.clone(); + let store_for_client = store.clone(); - let duroxide_runtime = - runtime::Runtime::start_with_store(store, activities, orchestrations).await; + let duroxide_runtime = + runtime::Runtime::start_with_store(store, activities, orchestrations).await; - log!("pg_durable: duroxide runtime started"); - return Some((duroxide_runtime, store_for_client)); - } + log!("pg_durable: duroxide runtime started"); + Ok((duroxide_runtime, store_for_client)) } /// Write the epoch sentinel after a successful runtime init. @@ -927,7 +1016,7 @@ pub(crate) async fn register_origin( pool: &sqlx::PgPool, origin: &Origin, ) -> Result<(), sqlx::Error> { - let schema = resolve_duroxide_schema_pool(pool).await; + let schema = resolve_duroxide_schema_pool(pool).await?; let schema = format!("\"{}\"", schema.replace('"', "\"\"")); register_origin_in_schema(pool, &schema, origin).await } @@ -957,19 +1046,38 @@ async fn register_origin_in_schema( /// Check whether our epoch sentinel still exists. /// /// Returns `true` when the sentinel row is intact (keep running), -/// `false` when it is missing or the query fails (extension dropped -/// or drop+recreated). +/// `false` when the identity is unusable, the row is missing, or the query fails. async fn check_epoch_sentinel(pool: &sqlx::PgPool, epoch_id: &str) -> bool { + let mut conn = match pool.acquire().await { + Ok(conn) => conn, + Err(error) => { + log!("pg_durable: cannot acquire heartbeat connection: {error}"); + return false; + } + }; + if let Err(error) = validate_worker_identity(&mut conn, &crate::types::get_worker_role()).await + { + log!("pg_durable: worker identity is no longer usable: {error}"); + return false; + } let result = sqlx::query( "UPDATE df._worker_epoch SET last_seen_at = pg_catalog.now() WHERE epoch_id OPERATOR(pg_catalog.=) $1::pg_catalog.uuid RETURNING epoch_id", ) .bind(epoch_id) - .fetch_optional(pool) + .fetch_optional(&mut *conn) .await; - // Query error (table/schema gone) ⇒ treat as "dropped" - // None ⇒ row missing (drop+recreated) - matches!(result, Ok(Some(_))) + match result { + Ok(Some(_)) => true, + Ok(None) => { + log!("pg_durable: epoch sentinel gone — extension dropped or recreated"); + false + } + Err(error) => { + log!("pg_durable: epoch sentinel check failed: {error}"); + false + } + } } /// Expired terminal instances: those beyond the newest `max_keep` (a hard cap @@ -1183,14 +1291,20 @@ async fn run_until_extension_dropped_or_shutdown( None => check_extension_exists(poll_pool).await, }; if !still_valid { - log!("pg_durable: epoch sentinel gone — extension dropped or recreated"); + log!("pg_durable: worker health check failed; stopping runtime"); break; } } _ = &mut reconcile_check, if reconcile_enabled => { let maintenance = async { let retention_days = get_retention_days(); - let schema = resolve_duroxide_schema_pool(maintenance_pool).await; + let schema = match resolve_duroxide_schema_pool(maintenance_pool).await { + Ok(schema) => schema, + Err(error) => { + log!("pg_durable: cannot resolve provider schema for reconciliation: {error}"); + return false; + } + }; let schema = format!("\"{}\"", schema.replace('"', "\"\"")); // Engine-first: retire the engine record before the df row, so a @@ -1288,7 +1402,7 @@ async fn run_until_extension_dropped_or_shutdown( None => check_extension_exists(poll_pool).await, }; if !still_valid { - log!("pg_durable: control extension removed during maintenance"); + log!("pg_durable: worker health check failed during maintenance"); break 'processing; } } @@ -1767,12 +1881,14 @@ async fn origin_is_removed(pool: &sqlx::PgPool, origin: &Origin) -> Result("SELECT current_user::text") @@ -2409,13 +2538,14 @@ mod tests { assert!(check_extension_exists(&pool).await); let epoch = capture_extension_epoch(&pool).await.unwrap().unwrap(); assert!(!extension_epoch_replaced(&pool, epoch).await); - assert_eq!(resolve_duroxide_schema_pool(&pool).await, "_duroxide"); + assert_eq!(resolve_duroxide_schema_pool(&pool).await.unwrap(), "_duroxide"); assert!( check_duroxide_schema_owned(&pool, "worker_qualification_objects").await ); assert!( has_extension_owned_duroxide_objects(&pool, "worker_qualification_objects") .await + .unwrap() ); release_extension_owned_duroxide_objects(&pool, "worker_qualification_objects") .await @@ -2423,6 +2553,7 @@ mod tests { assert!( !has_extension_owned_duroxide_objects(&pool, "worker_qualification_objects") .await + .unwrap() ); write_worker_ready(&pool, "worker_qualification_objects", epoch) .await @@ -2756,15 +2887,21 @@ mod tests { let quoted_database = format!("\"{}\"", database.replace('"', "\"\"")); let quoted_worker = format!("\"{}\"", crate::types::get_worker_role().replace('"', "\"\"")); // pgrx may initialize its private cluster with the OS user, without - // the configured worker login. Supply only test metadata read rights. + // the configured worker login. Supply the origin metadata contract + // without making the test worker a superuser. + // let worker_exists: bool = sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = $1)", ).bind(crate::types::get_worker_role()).fetch_one(&mut connection).await.unwrap(); if !worker_exists { sqlx::raw_sql(&format!( - "CREATE ROLE {quoted_worker} LOGIN; + "CREATE ROLE {quoted_worker} LOGIN BYPASSRLS NOINHERIT; + GRANT CONNECT ON DATABASE {quoted_database} TO {quoted_worker}; GRANT USAGE ON SCHEMA df, origin_path_trap TO {quoted_worker}; - GRANT SELECT ON ALL TABLES IN SCHEMA df, origin_path_trap TO {quoted_worker}" + GRANT SELECT ON ALL TABLES IN SCHEMA df, origin_path_trap TO {quoted_worker}; + GRANT DELETE ON df.instances, df.nodes TO {quoted_worker}; + GRANT UPDATE (status, updated_at, completed_at) ON df.instances TO {quoted_worker}; + GRANT UPDATE (status, result, status_details, updated_at) ON df.nodes TO {quoted_worker}" )).execute(&mut connection).await.unwrap(); } let control = Arc::new(sqlx::postgres::PgPoolOptions::new().max_connections(1) @@ -2777,8 +2914,13 @@ mod tests { format!("ALTER ROLE {quoted_worker} IN DATABASE {quoted_database} SET search_path = origin_path_trap, pg_catalog"), ] { sqlx::query(&setting).execute(&mut connection).await.unwrap(); - let mut unsafe_connection = crate::types::connect_as_user( - &crate::types::get_worker_role(), Some(&database), + // This probe intentionally observes unmodified login defaults, + // without using the reserved worker as a workflow executor. + let mut unsafe_connection = sqlx::PgConnection::connect_with( + &sqlx::postgres::PgConnectOptions::new() + .username(&crate::types::get_worker_role()) + .host(&crate::types::get_host()).port(crate::types::get_port()) + .database(&database) ).await.unwrap(); let marker = sqlx::query("SELECT '1'::oid = '1'::oid") .fetch_one(&mut unsafe_connection).await.unwrap_err(); @@ -2834,8 +2976,7 @@ mod tests { sqlx::query("DROP SCHEMA origin_path_trap CASCADE").execute(&mut connection).await.unwrap(); if !worker_exists { sqlx::raw_sql(&format!( - "REVOKE ALL ON SCHEMA df FROM {quoted_worker}; - REVOKE ALL ON ALL TABLES IN SCHEMA df FROM {quoted_worker}; + "DROP OWNED BY {quoted_worker}; DROP ROLE {quoted_worker}" )).execute(&mut connection).await.unwrap(); } diff --git a/tests/e2e/worker_role.sql b/tests/e2e/worker_role.sql new file mode 100644 index 00000000..7c07b17b --- /dev/null +++ b/tests/e2e/worker_role.sql @@ -0,0 +1,71 @@ +-- Copyright (c) Microsoft Corporation. +-- Licensed under the PostgreSQL License. +-- +-- Test the minimum worker contract, including old installed schemas. The +-- caller sets pg_durable_test.worker_role and executes this as the installer. +DO $worker$ +DECLARE + worker_name text := current_setting('pg_durable_test.worker_role'); + provider_schema name; + item record; + columns text; +BEGIN + IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = worker_name) THEN + EXECUTE format('CREATE ROLE %I LOGIN NOSUPERUSER BYPASSRLS NOINHERIT + NOCREATEDB NOCREATEROLE NOREPLICATION', worker_name); + END IF; + IF NOT EXISTS ( + SELECT FROM pg_catalog.pg_roles WHERE rolname = worker_name + AND rolcanlogin AND NOT rolsuper AND rolbypassrls AND NOT rolinherit + AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication + ) THEN + RAISE EXCEPTION 'unexpected test worker attributes'; + END IF; + IF current_setting('server_version_num')::integer >= 170000 THEN + EXECUTE format('ALTER ROLE %I SET event_triggers = off', worker_name); + END IF; + + EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I', current_database(), worker_name); + EXECUTE format('GRANT USAGE ON SCHEMA df TO %I', worker_name); + EXECUTE format('GRANT SELECT, DELETE ON df.instances, df.nodes TO %I', worker_name); + EXECUTE format('GRANT UPDATE (status, updated_at, completed_at) ON df.instances TO %I', worker_name); + SELECT string_agg(quote_ident(attname), ', ' ORDER BY attnum) INTO columns + FROM pg_catalog.pg_attribute + WHERE attrelid = 'df.nodes'::regclass AND NOT attisdropped + AND attname IN ('status', 'result', 'status_details', 'updated_at'); + EXECUTE format('GRANT UPDATE (%s) ON df.nodes TO %I', columns, worker_name); + IF to_regclass('df._installation') IS NOT NULL THEN + EXECUTE format('GRANT SELECT ON df._installation TO %I', worker_name); + END IF; + + IF current_database() <> current_setting('pg_durable.database') THEN + RETURN; + END IF; + EXECUTE format('GRANT CREATE ON DATABASE %I TO %I', current_database(), worker_name); + EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON df._worker_epoch TO %I', worker_name); + SELECT n.nspname INTO STRICT provider_schema + FROM pg_namespace n JOIN pg_depend d ON d.objid=n.oid AND d.classid='pg_namespace'::regclass + JOIN pg_extension e ON e.oid=d.refobjid AND d.refclassid='pg_extension'::regclass + WHERE e.extname='pg_durable' AND d.deptype='e' AND n.nspname IN ('duroxide', '_duroxide'); + EXECUTE format('ALTER SCHEMA %I OWNER TO %I', provider_schema, worker_name); + FOR item IN + SELECT n.nspname, c.relname, c.relkind + FROM pg_catalog.pg_class c + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = provider_schema AND c.relkind IN ('r', 'p', 'S') + ORDER BY c.relkind = 'S', c.oid + LOOP + EXECUTE format('ALTER %s %I.%I OWNER TO %I', + CASE WHEN item.relkind = 'S' THEN 'SEQUENCE' ELSE 'TABLE' END, + item.nspname, item.relname, worker_name); + END LOOP; + FOR item IN + SELECT p.oid::regprocedure AS signature + FROM pg_catalog.pg_proc p + JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = provider_schema AND p.prokind = 'f' + LOOP + EXECUTE format('ALTER FUNCTION %s OWNER TO %I', item.signature, worker_name); + END LOOP; +END +$worker$;