Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/native-mariadb-runtime-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Before resolving or executing any host tool, the provider requires available real/effective UID and GID APIs, rejects every root-valued identity, and requires real/effective IDs to match. It then resolves and validates `mariadbd`, `mariadb-install-db`, `mariadb`, util-linux `prlimit`, `truncate`, `mkfs.ext4`, `fuse2fs`, and `fusermount3` identities before allocation. The MariaDB username must resolve back to the same proven UID and GID.
- Default executable discovery ignores the caller's `PATH`, searches fixed system directories, resolves symlinks, and requires every executable and ancestor to be UID-0-owned and not group/other writable. Child processes receive a fixed minimal `PATH`.
- Every run gets a mode-`0700` `mkdtemp` root. MariaDB's data directory, temporary directory, socket, PID file, error log, plugin directory, secure-file directory, home, and working directory are all inside the bounded image.
- The root is created under the canonical `os.tmpdir()` unless that would push `<root>/storage/runtime/server.sock` past a 100-byte budget (below the 108-byte Linux and 104-byte macOS `sun_path` limits). Long per-run `TMPDIR` values, such as Homeboy's, then fall back to the canonical `/tmp`; the same `mkdtemp`, `0700`, realpath, and lstat ownership proofs apply to whichever base is chosen. If no base is short enough, provisioning fails before allocating a root, evidence carries `diagnostic.cause.code: "socket-path-too-long"`, and descriptor readiness reports `socket-path-too-long`.
- Initialization and the daemon run as the verified unprivileged FUSE mount owner through fixed hard rlimits; administrative clients retain the provider identity and each database command itself begins with `--no-defaults`. No shell or default socket is used.
- Administration uses only the private Unix socket. Workloads receive a generated least-privilege `runtime` account over loopback TCP through the existing ephemeral connector-secret channel.
- Initialization, FUSE, and daemon commands each run in a new owned process group. Cleanup addresses the retained group, not a PID file; it waits for the complete group to disappear after graceful shutdown, then applies group-wide `SIGTERM` and `SIGKILL` as needed. Linux captures the leader start-time token and revalidates it while the leader is alive. Root device/inode identity and a symlink-free tree are revalidated before recursive removal.
Expand Down
85 changes: 80 additions & 5 deletions packages/cli/src/runtime-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ export interface RuntimeServiceDependencies {
verifyNativeFilesystem?: (root: string, datadir: string) => Promise<void>
request?: (url: string, options: { method: "GET" | "DELETE"; signal?: AbortSignal }) => Promise<{ status: number; body?: string }>
nativeIdentity?: () => NativeMariaDbHostIdentity
/** Ordered candidate bases for the owned native root; defaults to [os.tmpdir(), "/tmp"]. */
nativeRootBases?: readonly string[]
}

export interface RuntimeServiceProvider {
Expand Down Expand Up @@ -372,6 +374,15 @@ function providerUnavailableDiagnostic(error: unknown, command: string): Runtime
}

const NATIVE_MARIADB_ROOT_PREFIX = "wp-codebox-mariadb-"
// mkdtemp() replaces the template with exactly six random characters.
const NATIVE_MARIADB_ROOT_SUFFIX_LENGTH = 6
const NATIVE_MARIADB_SOCKET_SEGMENTS = ["storage", "runtime", "server.sock"] as const
// Unix-domain socket paths must fit sun_path: 108 bytes on Linux and 104 on
// macOS/BSD, including the terminating NUL. Keep a margin below both.
export const NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES = 100
// Short, conventional fallback base used only when the caller's TMPDIR would
// push the server socket past the sun_path limit.
const NATIVE_MARIADB_FALLBACK_ROOT_BASE = "/tmp"
const NATIVE_MARIADB_START_ATTEMPTS = 5
const NATIVE_MARIADB_START_TIMEOUT_MS = 30_000
const NATIVE_MARIADB_PROCESS_OUTPUT_LIMIT_BYTES = 256 * 1024
Expand Down Expand Up @@ -434,6 +445,14 @@ interface OwnedNativeProcess {
identityReady: Promise<void>
}

export class NativeMariaDbSocketPathError extends Error {
readonly reason = "socket-path-too-long"
constructor(message: string) {
super(message)
this.name = "NativeMariaDbSocketPathError"
}
}

interface OwnedNativeRoot {
path: string
device: number
Expand Down Expand Up @@ -486,7 +505,7 @@ async function provisionMysqlNativeService(service: WorkspaceRecipeRuntimeServic
const binaries = await resolveNativeMariaDbBinaries(dependencies, signal)
binariesForCleanup = binaries
evidence.version = binaries.version
root = await createOwnedNativeRoot()
root = await createOwnedNativeRoot(dependencies.nativeRootBases)
const storageRoot = ownedNativePath(root, "storage")
await mkdir(storageRoot, { mode: 0o700 })
const storageEnvironment = nativeMariaDbEnvironment(root.path)
Expand All @@ -501,6 +520,7 @@ async function provisionMysqlNativeService(service: WorkspaceRecipeRuntimeServic
const secureFileDirectory = join(storageRoot, "files")
for (const directory of [datadir, runtimeDirectory, temporaryDirectory, pluginDirectory, secureFileDirectory]) await mkdir(directory, { mode: 0o700 })
const socket = join(runtimeDirectory, "server.sock")
assertNativeMariaDbSocketPath(socket)
adminSocket = socket
const pidFile = join(runtimeDirectory, "server.pid")
const logFile = join(runtimeDirectory, "server.log")
Expand Down Expand Up @@ -591,7 +611,10 @@ async function provisionMysqlNativeService(service: WorkspaceRecipeRuntimeServic
try { await cleanup() } catch (caught) { cleanupError = caught }
evidence.readiness = "failed"
evidence.lifecycle = "failed"
evidence.diagnostic = evidence.teardown === "failed" ? { code: "teardown-failed" } : diagnostic
const socketPathError = nativeMariaDbSocketPathErrorFrom(error)
evidence.diagnostic = evidence.teardown === "failed"
? { code: "teardown-failed" }
: socketPathError ? { ...diagnostic, cause: { code: socketPathError.reason, message: socketPathError.message } } : diagnostic
throw new RuntimeServiceProvisionError(`Managed runtime service failed: ${service.id}`, evidenceList, { cause: cleanupError ?? error })
}
}
Expand Down Expand Up @@ -643,7 +666,8 @@ async function probeNativeMariaDbHostReadiness(dependencies: RuntimeServiceDepen
await retained.release()
state.retained = undefined
if (signal?.aborted) return { status: "unavailable", reason: "containment-probe-interrupted" }
return retained.evidence.readiness === "ready" ? { status: "ready" } : { status: "unavailable", reason: "bounded-filesystem-unavailable" }
if (retained.evidence.readiness === "ready") return { status: "ready" }
return { status: "unavailable", reason: retained.evidence.diagnostic?.cause?.code === "socket-path-too-long" ? "socket-path-too-long" : "bounded-filesystem-unavailable" }
} catch {
return { status: "unavailable", reason: "containment-probe-cleanup-failed" }
}
Expand Down Expand Up @@ -687,6 +711,7 @@ async function probeNativeMariaDbHostReadiness(dependencies: RuntimeServiceDepen
}
state.retained = undefined
if (signal?.aborted) return { status: "unavailable", reason: "containment-probe-interrupted" }
if (nativeMariaDbSocketPathErrorFrom(error) || evidence.some((entry) => entry.diagnostic?.cause?.code === "socket-path-too-long")) return { status: "unavailable", reason: "socket-path-too-long" }
return { status: "unavailable", reason: "bounded-filesystem-unavailable" }
}
}
Expand Down Expand Up @@ -997,8 +1022,58 @@ async function nativeExecutableIsTrusted(path: string): Promise<boolean> {
}
}

async function createOwnedNativeRoot(): Promise<OwnedNativeRoot> {
const temporaryRoot = await realpath(tmpdir())
/**
* Byte length of the MariaDB server socket path for an owned root created
* under `base` (after mkdtemp fills in its random suffix).
*/
export function nativeMariaDbSocketPathBytes(base: string): number {
return Buffer.byteLength(join(base, `${NATIVE_MARIADB_ROOT_PREFIX}${"X".repeat(NATIVE_MARIADB_ROOT_SUFFIX_LENGTH)}`, ...NATIVE_MARIADB_SOCKET_SEGMENTS))
}

export function assertNativeMariaDbSocketPath(socket: string): void {
const bytes = Buffer.byteLength(socket)
if (bytes > NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES) {
throw new NativeMariaDbSocketPathError(`Native MariaDB socket path is ${bytes} bytes; the Unix-domain socket limit is ${NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES} bytes`)
}
}

/**
* Pick the canonical base directory for the owned native root. The caller's
* TMPDIR is preferred; when its canonical path is too long for the server's
* Unix-domain socket, fall back to the short system temporary directory. The
* selected base only changes where mkdtemp() runs: the private 0700 root and
* every realpath/lstat ownership proof are applied identically afterwards.
*/
export async function selectNativeMariaDbRootBase(candidates: readonly string[] = [tmpdir(), NATIVE_MARIADB_FALLBACK_ROOT_BASE]): Promise<string> {
// Only byte counts are reported: evidence must never carry private absolute paths.
const rejectedBytes: number[] = []
for (const candidate of candidates) {
let canonical: string
try {
canonical = await realpath(candidate)
} catch {
continue
}
const bytes = nativeMariaDbSocketPathBytes(canonical)
if (bytes <= NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES) return canonical
rejectedBytes.push(bytes)
}
throw new NativeMariaDbSocketPathError(rejectedBytes.length > 0
? `Native MariaDB socket path would be ${rejectedBytes.join("/")} bytes under the available temporary bases; the Unix-domain socket limit is ${NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES} bytes`
: `Native MariaDB found no temporary base that keeps its socket path within ${NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES} bytes`)
}

function nativeMariaDbSocketPathErrorFrom(error: unknown): NativeMariaDbSocketPathError | undefined {
let current = error
for (let depth = 0; current && depth < 8; depth += 1) {
if (current instanceof NativeMariaDbSocketPathError) return current
current = current instanceof Error ? current.cause : undefined
}
return undefined
}

async function createOwnedNativeRoot(baseCandidates?: readonly string[]): Promise<OwnedNativeRoot> {
const temporaryRoot = await selectNativeMariaDbRootBase(baseCandidates)
const path = await mkdtemp(join(temporaryRoot, NATIVE_MARIADB_ROOT_PREFIX))
await chmod(path, 0o700)
const canonical = await realpath(path)
Expand Down
2 changes: 1 addition & 1 deletion tests/native-mariadb-runtime-service.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const service = (id: string, prefix = "DB"): WorkspaceRecipeRuntimeService => ({
const rootsBefore = new Set((await readdir(tmpdir())).filter((name) => name.startsWith("wp-codebox-mariadb-")))
const readiness = await nativeMariaDbHostReadiness()
if (readiness.status !== "ready") {
assert.ok(["unprivileged-host-required", "trusted-containment-tools-unavailable", "bounded-filesystem-unavailable", "containment-probe-cleanup-failed", "containment-probe-interrupted"].includes(readiness.reason ?? ""), "native discovery must return a stable fail-closed reason")
assert.ok(["unprivileged-host-required", "trusted-containment-tools-unavailable", "bounded-filesystem-unavailable", "socket-path-too-long", "containment-probe-cleanup-failed", "containment-probe-interrupted"].includes(readiness.reason ?? ""), "native discovery must return a stable fail-closed reason")
const leakedRoots = (await readdir(tmpdir())).filter((name) => name.startsWith("wp-codebox-mariadb-") && !rootsBefore.has(name))
assert.deepEqual(leakedRoots, [], "failed native discovery must not leak private roots")
console.log(`native MariaDB runtime service integration skipped: ${readiness.reason ?? "host-unavailable"}`)
Expand Down
60 changes: 58 additions & 2 deletions tests/native-mariadb-runtime-service.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import assert from "node:assert/strict"
import { EventEmitter, getEventListeners } from "node:events"
import { chmod, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises"
import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises"
import { createServer } from "node:net"
import { tmpdir, userInfo } from "node:os"
import { basename, dirname, join } from "node:path"
import { runRuntimeDescriptorCommand, RuntimeDescriptorInterruptedError, withRuntimeDescriptorInterruption } from "../packages/cli/src/commands/discovery.ts"
import { abortableDelay, assertNativeMariaDbEngines, assertNativeMariaDbFilesystemGeometry, assertNativeMariaDbFilesystemOwnership, assertNativeMariaDbMountInfo, assertNativeMariaDbUnprivilegedHost, nativeMariaDbHostReadiness, provisionRuntimeServices, RuntimeServiceProvisionError, runtimeServicePlan, settleNativeMariaDbHostReadiness, type NativeMariaDbHostIdentity, type RuntimeServiceDependencies } from "../packages/cli/src/runtime-services.ts"
import { abortableDelay, assertNativeMariaDbEngines, assertNativeMariaDbSocketPath, NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES, NativeMariaDbSocketPathError, nativeMariaDbSocketPathBytes, selectNativeMariaDbRootBase, assertNativeMariaDbFilesystemGeometry, assertNativeMariaDbFilesystemOwnership, assertNativeMariaDbMountInfo, assertNativeMariaDbUnprivilegedHost, nativeMariaDbHostReadiness, provisionRuntimeServices, RuntimeServiceProvisionError, runtimeServicePlan, settleNativeMariaDbHostReadiness, type NativeMariaDbHostIdentity, type RuntimeServiceDependencies } from "../packages/cli/src/runtime-services.ts"
import { playwrightBrowserReadiness } from "../packages/runtime-playground/src/playwright-browser-provenance.ts"
import { validateWorkspaceRecipeSemantics } from "../packages/cli/src/recipe-validation.ts"
import { validateWorkspaceRecipeJsonSchema, type WorkspaceRecipeRuntimeService } from "../packages/runtime-core/src/index.ts"
Expand Down Expand Up @@ -207,6 +207,62 @@ process.exit(1);
await settleNativeMariaDbHostReadiness(interruptedDependencies)
assert.deepEqual((await readdir(tmpdir())).filter((name) => name.startsWith("wp-codebox-mariadb-") && !interruptedRoots.has(name)), [], "interrupted descriptor discovery releases all native roots")

// Socket path selection: a long TMPDIR must not push <root>/storage/runtime/server.sock past sun_path.
assert.equal(nativeMariaDbSocketPathBytes("/tmp"), Buffer.byteLength("/tmp/wp-codebox-mariadb-XXXXXX/storage/runtime/server.sock"))
assert.doesNotThrow(() => assertNativeMariaDbSocketPath(`/${"s".repeat(NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES - 1)}`))
assert.throws(() => assertNativeMariaDbSocketPath(`/${"s".repeat(NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES)}`), (error: unknown) => error instanceof NativeMariaDbSocketPathError && error.reason === "socket-path-too-long")
const shortBase = await realpath(await mkdtemp(join("/tmp", "wpcb-sock-")))
try {
const longBase = join(fixture, "homeboy-run-df70bf63-6e8d-4494-a0e6-27a2706a628d-1794495483671992580", "runtime", "tmp")
await mkdir(longBase, { recursive: true, mode: 0o700 })
const canonicalLongBase = await realpath(longBase)
assert.ok(nativeMariaDbSocketPathBytes(canonicalLongBase) > NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES, "fixture base must be long enough to overflow the socket path")
assert.ok(nativeMariaDbSocketPathBytes(shortBase) <= NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES)
const shortAlias = join(shortBase, "l")
await symlink(canonicalLongBase, shortAlias)
assert.equal(await selectNativeMariaDbRootBase([shortBase]), shortBase, "a short TMPDIR is used unchanged")
assert.equal(await selectNativeMariaDbRootBase([longBase, shortBase]), shortBase, "a long TMPDIR falls back to the short base")
assert.equal(await selectNativeMariaDbRootBase([shortAlias, shortBase]), shortBase, "length is measured on the canonical path, not a short symlink alias")
assert.equal(await selectNativeMariaDbRootBase([join(shortBase, "missing"), shortBase]), shortBase, "unavailable candidates are skipped")
await assert.rejects(selectNativeMariaDbRootBase([longBase]), (error: unknown) => error instanceof NativeMariaDbSocketPathError && error.reason === "socket-path-too-long" && error.message.includes(`${nativeMariaDbSocketPathBytes(canonicalLongBase)} bytes`) && !error.message.includes(fixture), "the error reports byte counts without private paths")
await assert.rejects(selectNativeMariaDbRootBase([join(shortBase, "missing")]), NativeMariaDbSocketPathError)

const fallbackCallsStart = calls.length
const fallback = await provisionRuntimeServices([service], { dependencies: { ...dependencies, nativeRootBases: [longBase, shortBase] } })
try {
assert.equal(fallback.evidence[0]?.readiness, "ready", "long TMPDIR provisions through the short fallback base")
const sockets = calls.slice(fallbackCallsStart).flatMap((call) => call.args).filter((arg) => arg.startsWith("--socket=")).map((arg) => arg.slice("--socket=".length))
assert.ok(sockets.length > 0)
for (const socket of sockets) {
assert.ok(socket.startsWith(`${shortBase}/wp-codebox-mariadb-`), "the owned root lives under the short base")
assert.ok(Buffer.byteLength(socket) <= NATIVE_MARIADB_SOCKET_PATH_LIMIT_BYTES)
}
const fallbackRoot = dirname(dirname(dirname(sockets[0]!)))
const fallbackRootMetadata = await lstat(fallbackRoot)
assert.ok(fallbackRootMetadata.isDirectory() && !fallbackRootMetadata.isSymbolicLink())
assert.equal(fallbackRootMetadata.mode & 0o777, 0o700, "the fallback root keeps the private 0700 mode")
assert.equal(await realpath(fallbackRoot), fallbackRoot, "the fallback root is canonical")
assert.deepEqual(await readdir(longBase), [], "nothing is allocated under the rejected long base")
} finally {
await fallback.release()
}
assert.deepEqual((await readdir(shortBase)).filter((name) => name.startsWith("wp-codebox-mariadb-")), [], "fallback root is removed on release")

await assert.rejects(provisionRuntimeServices([service], { dependencies: { ...dependencies, nativeRootBases: [longBase] } }), (error: unknown) => {
assert.ok(error instanceof RuntimeServiceProvisionError)
assert.equal(error.evidence[0]?.readiness, "failed")
assert.equal(error.evidence[0]?.diagnostic?.code, "provision-failed")
assert.equal(error.evidence[0]?.diagnostic?.cause?.code, "socket-path-too-long")
assert.equal(JSON.stringify(error.evidence).includes(fixture), false, "evidence never carries private absolute paths")
return true
})
assert.deepEqual(await readdir(longBase), [], "an overlong socket path allocates no private root")
assert.deepEqual(await nativeMariaDbHostReadiness({ ...dependencies, nativeRootBases: [longBase] }), { status: "unavailable", reason: "socket-path-too-long" }, "readiness surfaces the socket path cause")
assert.deepEqual(await nativeMariaDbHostReadiness({ ...dependencies, nativeRootBases: [longBase, shortBase] }), { status: "ready" })
} finally {
await rm(shortBase, { recursive: true, force: true })
}

const signalTarget = new EventEmitter()
const interruptedDescriptor = withRuntimeDescriptorInterruption(async (signal) => await new Promise<boolean>((resolve) => signal.addEventListener("abort", () => resolve(signal.aborted), { once: true })), signalTarget, 10_000)
signalTarget.emit("SIGTERM")
Expand Down
Loading