pg-embed-setup-unpriv 0.5.1

Initialises postgresql_embedded clusters as root while handing off filesystem work to nobody
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Dispatches `PostgreSQL` lifecycle operations either in-process or via the privileged worker binary.
use std::future::Future;

use color_eyre::eyre::{Context, eyre};
use tokio::runtime::Runtime;

use crate::error::{BootstrapError, BootstrapResult};
use crate::observability::LOG_TARGET;
use crate::worker_process::{self, WorkerRequest, WorkerRequestArgs};
use crate::{ExecutionMode, ExecutionPrivileges, TestBootstrapSettings};

use super::WorkerOperation;
use super::panic_utils::nested_runtime_thread_panic;
use tracing::{error, info, info_span};

// ============================================================================
// Shared helper functions
// ============================================================================

/// Creates a tracing span for lifecycle operations.
///
/// Used by both sync and async invokers to maintain consistent observability.
/// The `async_mode` field is only recorded when `true` to maintain backward
/// compatibility with existing sync span format.
fn create_lifecycle_span(
    operation: WorkerOperation,
    bootstrap: &TestBootstrapSettings,
    async_mode: bool,
) -> tracing::Span {
    let span = info_span!(
        target: LOG_TARGET,
        "lifecycle_operation",
        operation = operation.as_str(),
        privileges = ?bootstrap.privileges,
        mode = ?bootstrap.execution_mode,
        async_mode = tracing::field::Empty
    );
    if async_mode {
        span.record("async_mode", true);
    }
    span
}

/// Executes a root operation, handling test hooks, execution mode validation,
/// and platform-specific constraints.
///
/// This is the shared implementation used by both sync (`WorkerInvoker::invoke_as_root`)
/// and async (`AsyncInvoker::run_root_async`) code paths.
fn execute_root_operation(
    bootstrap: &TestBootstrapSettings,
    env_vars: &[(String, Option<String>)],
    operation: WorkerOperation,
) -> BootstrapResult<()> {
    #[cfg(any(test, feature = "cluster-unit-tests"))]
    {
        let hook_slot = crate::test_support::run_root_operation_hook()
            .lock()
            .unwrap_or_else(|poison| poison.into_inner())
            .clone();
        if let Some(hook) = hook_slot {
            return hook(bootstrap, env_vars, operation);
        }
    }

    match bootstrap.execution_mode {
        ExecutionMode::InProcess => Err(BootstrapError::from(eyre!(concat!(
            "ExecutionMode::InProcess is unsafe for root because process-wide ",
            "UID/GID changes race in multi-threaded tests; switch to ",
            "ExecutionMode::Subprocess"
        )))),
        ExecutionMode::Subprocess => spawn_worker_inner(bootstrap, env_vars, operation),
    }
}

/// Spawns the worker subprocess to execute a privileged operation.
///
/// This is the shared implementation for worker spawning, used by both sync and
/// async code paths. Contains platform-specific guards for privilege dropping.
fn spawn_worker_inner(
    bootstrap: &TestBootstrapSettings,
    env_vars: &[(String, Option<String>)],
    operation: WorkerOperation,
) -> BootstrapResult<()> {
    #[cfg(not(all(
        unix,
        any(
            target_os = "linux",
            target_os = "android",
            target_os = "freebsd",
            target_os = "openbsd",
            target_os = "dragonfly",
        ),
    )))]
    {
        return Err(BootstrapError::from(eyre!(
            "privilege drop not supported on this target; refusing to run as root: {}",
            operation.error_context()
        )));
    }

    #[cfg(all(
        unix,
        any(
            target_os = "linux",
            target_os = "android",
            target_os = "freebsd",
            target_os = "openbsd",
            target_os = "dragonfly",
        ),
    ))]
    {
        let worker = bootstrap.worker_binary.as_ref().ok_or_else(|| {
            BootstrapError::from(eyre!(concat!(
                "pg_worker binary not found. Install it with 'cargo install --path . --bin pg_worker' ",
                "and ensure it is in PATH, or set PG_EMBEDDED_WORKER to its absolute path"
            )))
        })?;

        let args = WorkerRequestArgs {
            worker,
            settings: &bootstrap.settings,
            env_vars,
            operation,
            timeout: operation.timeout(bootstrap),
        };
        let request = WorkerRequest::new(args);
        return worker_process::run(&request);
    }

    #[expect(unreachable_code, reason = "cfg guard ensures all targets handled")]
    Err(BootstrapError::from(eyre!(
        "privilege drop support unexpectedly unavailable"
    )))
}

fn log_failure(operation: WorkerOperation, err: &BootstrapError) {
    error!(
        target: LOG_TARGET,
        operation = operation.as_str(),
        error = %err,
        "lifecycle operation failed"
    );
}

fn log_success(operation: WorkerOperation) {
    info!(
        target: LOG_TARGET,
        operation = operation.as_str(),
        "lifecycle operation completed"
    );
}

/// Logs the start of an in-process lifecycle operation.
///
/// Used by both sync and async invokers. When `async_mode` is true, appends
/// " (async)" to the message to distinguish async execution paths in logs.
fn log_in_process_start(operation: WorkerOperation, async_mode: bool) {
    let suffix = if async_mode { " (async)" } else { "" };
    info!(
        target: LOG_TARGET,
        operation = operation.as_str(),
        "running lifecycle operation in-process{suffix}"
    );
}

/// Logs the dispatch of a lifecycle operation to the worker subprocess.
///
/// Used by both sync and async invokers. When `async_mode` is true, appends
/// " (async)" to the message to distinguish async execution paths in logs.
fn log_worker_dispatch(operation: WorkerOperation, worker_binary: Option<&str>, async_mode: bool) {
    let suffix = if async_mode { " (async)" } else { "" };
    info!(
        target: LOG_TARGET,
        operation = operation.as_str(),
        worker = worker_binary,
        "dispatching lifecycle operation via worker{suffix}"
    );
}

/// Creates a timeout error with consistent formatting.
///
/// Used by both sync and async invokers to ensure consistent error messages.
fn timeout_error(ctx: &'static str, timeout: std::time::Duration) -> BootstrapError {
    BootstrapError::from(eyre!(
        "{ctx}: operation timed out after {:.1}s",
        timeout.as_secs_f64()
    ))
}

async fn run_with_timeout<Fut>(
    timeout: std::time::Duration,
    future: Fut,
) -> Result<Result<(), postgresql_embedded::Error>, tokio::time::error::Elapsed>
where
    Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
{
    tokio::time::timeout(timeout, future).await
}

// ============================================================================
// Synchronous invoker
// ============================================================================

/// Executes worker operations whilst respecting configured privileges.
#[derive(Debug)]
#[doc(hidden)]
pub struct WorkerInvoker<'a> {
    runtime: &'a Runtime,
    bootstrap: &'a TestBootstrapSettings,
    env_vars: &'a [(String, Option<String>)],
}

impl<'a> WorkerInvoker<'a> {
    /// Creates an invoker bound to a runtime, bootstrap configuration, and
    /// derived environment variables.
    ///
    /// # Examples
    /// ```ignore
    /// use pg_embedded_setup_unpriv::{ExecutionPrivileges, WorkerInvoker};
    /// use pg_embedded_setup_unpriv::test_support::{dummy_settings, test_runtime};
    ///
    /// # fn demo() -> color_eyre::eyre::Result<()> {
    /// let runtime = test_runtime()?;
    /// let bootstrap = dummy_settings(ExecutionPrivileges::Unprivileged);
    /// let env = bootstrap.environment.to_env();
    /// let invoker = WorkerInvoker::new(&runtime, &bootstrap, &env);
    /// # let _ = invoker;
    /// # Ok(())
    /// # }
    /// ```
    pub const fn new(
        runtime: &'a Runtime,
        bootstrap: &'a TestBootstrapSettings,
        env_vars: &'a [(String, Option<String>)],
    ) -> Self {
        Self {
            runtime,
            bootstrap,
            env_vars,
        }
    }

    /// Executes an operation either in-process or via the privileged worker,
    /// depending on the configured privilege level.
    ///
    /// # Errors
    ///
    /// Returns a [`BootstrapError`] when the worker invocation fails or when
    /// the in-process operation surfaces an error.
    ///
    /// # Examples
    /// ```ignore
    /// use pg_embedded_setup_unpriv::{ExecutionPrivileges, WorkerInvoker, WorkerOperation};
    /// use pg_embedded_setup_unpriv::test_support::{dummy_settings, test_runtime};
    ///
    /// # fn demo() -> pg_embedded_setup_unpriv::BootstrapResult<()> {
    /// let runtime = test_runtime()?;
    /// let bootstrap = dummy_settings(ExecutionPrivileges::Unprivileged);
    /// let env = bootstrap.environment.to_env();
    /// let invoker = WorkerInvoker::new(&runtime, &bootstrap, &env);
    /// invoker.invoke(WorkerOperation::Setup, async {
    ///     Ok::<(), postgresql_embedded::Error>(())
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn invoke<Fut>(&self, operation: WorkerOperation, in_process_op: Fut) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        let span = self.lifecycle_span(operation);
        let _entered = span.enter();

        let result = self.dispatch_operation(operation, in_process_op);
        Self::log_outcome(operation, &result);
        result
    }

    fn dispatch_operation<Fut>(
        &self,
        operation: WorkerOperation,
        in_process_op: Fut,
    ) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        match self.bootstrap.privileges {
            ExecutionPrivileges::Unprivileged => self.run_unprivileged(operation, in_process_op),
            ExecutionPrivileges::Root => self.run_root(operation),
        }
    }

    fn run_unprivileged<Fut>(
        &self,
        operation: WorkerOperation,
        in_process_op: Fut,
    ) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        log_in_process_start(operation, false);
        let timeout = operation.timeout(self.bootstrap);
        self.invoke_unprivileged(in_process_op, operation.error_context(), timeout)
    }

    fn run_root(&self, operation: WorkerOperation) -> BootstrapResult<()> {
        log_worker_dispatch(
            operation,
            self.bootstrap.worker_binary.as_ref().map(|p| p.as_str()),
            false,
        );
        self.invoke_as_root(operation)
    }

    fn log_outcome(operation: WorkerOperation, result: &BootstrapResult<()>) {
        if let Err(err) = result {
            log_failure(operation, err);
        } else {
            log_success(operation);
        }
    }

    fn invoke_unprivileged<Fut>(
        &self,
        future: Fut,
        ctx: &'static str,
        timeout: std::time::Duration,
    ) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        let result = if tokio::runtime::Handle::try_current().is_ok() {
            self.run_unprivileged_in_scoped_thread(future, ctx, timeout)?
        } else {
            self.runtime.block_on(run_with_timeout(timeout, future))
        };

        result
            .map_err(|_| timeout_error(ctx, timeout))?
            .context(ctx)
            .map_err(BootstrapError::from)
    }

    /// Executes an unprivileged operation on a helper thread when already
    /// inside a Tokio runtime.
    ///
    /// Calling `Runtime::block_on` from a runtime thread panics with
    /// "Cannot start a runtime from within a runtime". Running the operation on
    /// a scoped thread avoids the nested-runtime panic while keeping the sync
    /// API surface intact for callers such as `run()`.
    fn run_unprivileged_in_scoped_thread<Fut>(
        &self,
        future: Fut,
        ctx: &'static str,
        timeout: std::time::Duration,
    ) -> BootstrapResult<Result<Result<(), postgresql_embedded::Error>, tokio::time::error::Elapsed>>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        let runtime = self.runtime;
        std::thread::scope(|scope| {
            scope
                .spawn(move || runtime.block_on(run_with_timeout(timeout, future)))
                .join()
        })
        .map_err(|panic_payload| {
            nested_runtime_thread_panic(ctx, "nested-runtime operation", panic_payload)
        })
    }

    fn lifecycle_span(&self, operation: WorkerOperation) -> tracing::Span {
        create_lifecycle_span(operation, self.bootstrap, false)
    }

    pub(super) fn invoke_as_root(&self, operation: WorkerOperation) -> BootstrapResult<()> {
        execute_root_operation(self.bootstrap, self.env_vars, operation)
    }
}

/// Async variant of [`WorkerInvoker`] that operates on the caller's runtime.
///
/// Use this invoker when running within an existing async context (e.g., inside
/// `#[tokio::test]`). Unlike `WorkerInvoker`, this does not require an owned
/// runtime reference since it directly `.await`s futures.
#[cfg(feature = "async-api")]
#[derive(Debug)]
pub(crate) struct AsyncInvoker<'a> {
    bootstrap: &'a TestBootstrapSettings,
    env_vars: &'a [(String, Option<String>)],
}

#[cfg(feature = "async-api")]
impl<'a> AsyncInvoker<'a> {
    /// Creates an async invoker bound to bootstrap configuration and environment.
    pub(crate) const fn new(
        bootstrap: &'a TestBootstrapSettings,
        env_vars: &'a [(String, Option<String>)],
    ) -> Self {
        Self {
            bootstrap,
            env_vars,
        }
    }

    /// Executes an operation asynchronously, either in-process or via the worker.
    ///
    /// For unprivileged operations, the future is awaited directly.
    /// For root operations, the synchronous worker is spawned via `spawn_blocking`.
    ///
    /// # Errors
    ///
    /// Returns a [`BootstrapError`] when the operation fails.
    pub(crate) async fn invoke<Fut>(
        &self,
        operation: WorkerOperation,
        in_process_op: Fut,
    ) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        let span = self.lifecycle_span(operation);
        let _entered = span.enter();

        let result = self
            .dispatch_operation_async(operation, in_process_op)
            .await;
        WorkerInvoker::log_outcome(operation, &result);
        result
    }

    async fn dispatch_operation_async<Fut>(
        &self,
        operation: WorkerOperation,
        in_process_op: Fut,
    ) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        match self.bootstrap.privileges {
            ExecutionPrivileges::Unprivileged => {
                self.run_unprivileged_async(operation, in_process_op).await
            }
            ExecutionPrivileges::Root => self.run_root_async(operation).await,
        }
    }

    async fn run_unprivileged_async<Fut>(
        &self,
        operation: WorkerOperation,
        in_process_op: Fut,
    ) -> BootstrapResult<()>
    where
        Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
    {
        log_in_process_start(operation, true);
        let timeout = operation.timeout(self.bootstrap);
        invoke_unprivileged_async(in_process_op, operation.error_context(), timeout).await
    }

    async fn run_root_async(&self, operation: WorkerOperation) -> BootstrapResult<()> {
        log_worker_dispatch(
            operation,
            self.bootstrap.worker_binary.as_ref().map(|p| p.as_str()),
            true,
        );
        // Worker subprocess spawning is inherently blocking; use spawn_blocking.
        let bootstrap = (*self.bootstrap).clone();
        let env_vars = self.env_vars.to_vec();
        tokio::task::spawn_blocking(move || {
            execute_root_operation(&bootstrap, &env_vars, operation)
        })
        .await
        .map_err(|err| BootstrapError::from(eyre!("worker task panicked: {err}")))?
    }

    fn lifecycle_span(&self, operation: WorkerOperation) -> tracing::Span {
        create_lifecycle_span(operation, self.bootstrap, true)
    }
}

/// Awaits an unprivileged operation's future with timeout protection.
#[cfg(feature = "async-api")]
async fn invoke_unprivileged_async<Fut>(
    future: Fut,
    ctx: &'static str,
    timeout: std::time::Duration,
) -> BootstrapResult<()>
where
    Fut: Future<Output = Result<(), postgresql_embedded::Error>> + Send,
{
    tokio::time::timeout(timeout, future)
        .await
        .map_err(|_| timeout_error(ctx, timeout))?
        .context(ctx)
        .map_err(BootstrapError::from)
}

#[cfg(test)]
mod tests;