Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
72 changes: 66 additions & 6 deletions USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`.
Expand Down
11 changes: 6 additions & 5 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
27 changes: 8 additions & 19 deletions docs/rls.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`

Expand Down Expand Up @@ -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. ✅
Expand Down
9 changes: 8 additions & 1 deletion docs/upgrade-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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

Expand Down
9 changes: 9 additions & 0 deletions scripts/test-e2e-local.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions scripts/test-upgrade.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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

# ============================================================================
Expand Down
30 changes: 30 additions & 0 deletions scripts/test_upgrade_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading