Repository navigation
Support one-shot guest exec through Proxmox termproxy - #546
runleveldev wants to merge 11 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Unbounded WebSocket handshakes can leave guests permanently busy, partial script delivery can bypass execution timeouts, and output races can misclassify successful commands.
3 open issues
1 file not reviewed
create-a-container/package-lock.json: Generated file
What changed in this PR
Adds owner/admin one-shot guest execution through the Proxmox console API, enabling mieweb exec without SSH access or host-installed runners.
Changes:
- Adds the authenticated Manager endpoint and OS provider integration.
- Implements console transport, command wrapping, output parsing, and shell-mode configuration.
- Adds tests, CI coverage, and administrator documentation.
| File | Description |
|---|---|
packages/os-cloud-provider/test/provider.test.ts |
Tests exec requests, results, and errors. |
packages/os-cloud-provider/test/exec-guest.e2e.mjs |
Adds CLI verification against real guests. |
packages/os-cloud-provider/src/index.ts |
Exposes the exec capability. |
packages/os-cloud-provider/src/exec.ts |
Implements Manager-backed execution. |
packages/os-cloud-provider/src/deploy.ts |
Exports the shared client factory. |
packages/os-cloud-provider/src/client.ts |
Preserves exec permission errors. |
packages/os-cloud-provider/README.md |
Documents CLI usage. |
mie-opensource-landing/zensical.toml |
Links administrator documentation. |
mie-opensource-landing/docs/admins/guest-exec.md |
Documents requirements, limits, and console risks. |
create-a-container/utils/proxmox-api.js |
Adds console API and WebSocket methods. |
create-a-container/utils/guest-exec.js |
Implements guest execution and result parsing. |
create-a-container/utils/container-state.js |
Configures shell console mode. |
create-a-container/utils/__tests__/guest-exec.test.js |
Tests wrappers and console execution. |
create-a-container/utils/__tests__/container-state.test.js |
Tests shell-mode configuration. |
create-a-container/routers/api/v1/containers.js |
Adds authorization, validation, and auditing. |
create-a-container/routers/api/v1/__tests__/containers.exec.test.js |
Tests endpoint access and responses. |
create-a-container/package.json |
Adds the WebSocket dependency. |
create-a-container/package-lock.json |
Locks the WebSocket dependency. |
create-a-container/openapi.v1.yaml |
Defines the exec API contract. |
.github/workflows/os-cloud-provider.yml |
Includes exec changes and tests in CI. |
Review effort: Balanced
| const INPUT_CHUNK = 4096; | ||
|
|
||
| // Proxmox runs one shared `dtach` console session per guest, so commands on | ||
| // the same guest would interleave. This only serializes within one process. |
There was a problem hiding this comment.
This is a strong limitation. Is there a mitigation for multiple load balanced processes?
There was a problem hiding this comment.
Fixed in a48b465. The lock now lives in the database instead of process memory, so it works across load-balanced Manager processes.
- How it works: a new nullable
Containers.execLeaseUntilcolumn, plusContainer#claimExecLease/releaseExecLease. A claim is a conditionalUPDATE ... WHERE execLeaseUntil IS NULL OR execLeaseUntil < now. Only one process can win it, and the loser getsexec_busy(409). - Crash recovery: the lease lasts 2 minutes, longer than the exec's own deadlines. A process that dies mid-exec only blocks the container until the lease expires.
- Release: it matches on the exact expiry the claim set, so a slow process can't clear a lease that a later exec has since taken.
- Where it moved: the route now claims and releases the lease.
executeGuestno longer tracks busy guests.
I tested it against both SQLite and Postgres (migration, claim, busy, release, reclaiming an expired lease, and ignoring a release with the wrong expiry). The route tests now cover a concurrent exec that sees the lease through the database.
| - 'create-a-container/routers/api/v1/__tests__/containers.exec.test.js' | ||
| - 'create-a-container/utils/guest-exec.js' | ||
| - 'create-a-container/utils/__tests__/guest-exec.test.js' | ||
| - 'create-a-container/utils/proxmox-api.js' |
There was a problem hiding this comment.
Seems this is just gonna grow. At what point do we stop caring about path restrictions?
There was a problem hiding this comment.
Agreed, we stop now. As of a48b465 the workflow runs on any change under create-a-container/** except create-a-container/client/**, so the list no longer grows. The React client can't affect the API the provider calls. The job takes under a minute.
There was a problem hiding this comment.
🟡 Changes recommended
Incomplete watchdog delivery and unsafe lease handling can leave commands running while another request gains access to the shared console.
6 open issues
Mock only executeGuest to preserve EXEC_LEASE_SECONDS · New Retain the lease when execution outcome is unknown · New Bound setup I/O and verify the lease before dispatch · New Set a timeout for the WebSocket opening handshake Prevent partial script delivery from bypassing the watchdog Snapshot output streams before counting and encoding
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
Addresses the Copilot review on #546. * The wrapper is one brace group, so the shell runs nothing until it has read the whole script. A connection that drops mid-script can no longer start the command without its time limit. The bootstrap line starts a timer that kills the shell unless a complete wrapper cancels it within 10 seconds, so a half-received script can't hold the shared console session. * Each output stream is copied (up to 64 KiB + 1 byte) before it is measured and encoded, so background jobs that are still writing can't make the reported size disagree with the bytes sent. * Bound every step before dispatch: Proxmox requests (including the ticket login) and the WebSocket handshake time out after 10 s. executeGuest takes the lease expiry and refuses to open the console, or to send the wrapper, unless the lease outlasts the remaining deadlines. The lease is now 150 s to cover them. * Keep the lease when the outcome is unknown, since the command may still be running in the shared session. It expires after the guest-side limits have stopped the command. * The route test mock keeps the real EXEC_LEASE_SECONDS.
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because the inherited restrictive umask can make command-created files and directories inaccessible to non-root applications.
No open issues 🎉
6 resolved since last review
Bound setup I/O and verify the lease before dispatch Retain the lease when execution outcome is unknown Mock only executeGuest to preserve EXEC_LEASE_SECONDS Set a timeout for the WebSocket opening handshake Prevent partial script delivery from bypassing the watchdog Snapshot output streams before counting and encoding
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because lease release may precede session teardown, allowing subsequent executions to attach to a dying console and fail.
No open issues 🎉
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Enabling cmode:shell grants existing VM.Console holders passwordless guest root, requiring human confirmation of deployment ACLs and the trust-boundary change that repository context cannot establish.
No open issues 🎉
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because the wrapper alters SIGINT/SIGQUIT handling, potentially suppressing cancellation and masking signal-related exit statuses.
No open issues 🎉
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because detached processes may retain deleted capture files, allowing continued logging to exhaust guest disk space.
No open issues 🎉
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because an undocumented watchdog dependency and missing timeout coverage leave the 30-second execution limit unreliable.
No open issues 🎉
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced
Carry over the parts of #543 that don't depend on how a command reaches the guest. These are the exec_container OpenAPI contract, the owner/admin route with its argument limits, error mapping and audit logging, the route tests, the OS provider exec verb with its tests, and the CI triggers. The SSH node runner, its installer and fixtures, and the setup docs are intentionally left behind (see the review on #543). The route still imports utils/guest-exec. A Proxmox termproxy backend replaces it in a follow-up commit. Co-authored-by: Doug Horner <horner@mieweb.com>
Replace the SSH node runner from #543 with the Proxmox API alone. Nothing is installed on the Proxmox hosts and Manager needs no SSH access to them. With cmode: shell, the console that termproxy opens for a container is a root shell with no login. Manager connects to it with the existing node credentials over vncwebsocket and types a bootstrap line that puts the terminal into raw mode and switches to a non-interactive sh -s. It then sends a POSIX wrapper that runs the quoted argv with stdout and stderr redirected to files and a 30-second limit, and prints the exit code and hex-encoded streams between markers that contain a per-request nonce. * Containers get cmode: shell at create and reconfigure. On a running container the change waits for a restart, so the first exec on an older container sets it and returns exec_restart_required. * Commands run as guest root. The UID 1000 default and root grants are gone. * When the command returns, the shell exits, so plain background jobs get SIGHUP. Processes started with setsid or nohup keep running. * Only one exec runs per container at a time (exec_busy), because Proxmox shares a single dtach console session per container. * The live hostname and running state are checked through the API before the console is opened. Adds ws, because the WebSocket built into Node can't take the node's TLS agent or auth headers.
Running guest exec against the Proxmox in the compose stack turned up four problems that the fake termproxy did not show. * lxc-attach's host-side terminal keeps output processing on, so every \n arrives as \r\n and the ready marker never matched. Drop \r from console output. Markers and hex never contain it. * dash treats `sh -s` on a terminal as interactive and gives background jobs their own process group, so they never got SIGHUP and the timeout watcher outlived the exec. Turn job control off and hang up the shell's own group at the end, which gives SSH-like cleanup in any shell. * Input typed before the login shell starts is discarded. Wait for output other than termproxy's OK and dtach's clear-screen, and start the bootstrap line with ^U to clear any partial line. * A `sh -s` left in the shared session by an interrupted exec only runs lines that end in LF. End the bootstrap line with CR LF, with a trailing `:` to absorb the CR. The fake termproxy now translates \n to \r\n like the real console, and a new test covers background job cleanup. The admin docs list the privileges confirmed with an API token: VM.Audit, VM.Console and VM.Config.Options.
Commands on one container share a single Proxmox console session, so only one exec may run per container at a time. The in-memory set only enforced that within one Manager process. Replace it with a lease on the Container row (execLeaseUntil, set by a conditional update), so the claim holds across load-balanced Manager processes. The lease expires after 2 minutes, so a process that dies mid-exec doesn't block the container for good. The os-cloud-provider workflow listed more create-a-container files with each change. Trigger it on any server change instead, excluding the React client.
Addresses the Copilot review on #546. * The wrapper is one brace group, so the shell runs nothing until it has read the whole script. A connection that drops mid-script can no longer start the command without its time limit. The bootstrap line starts a timer that kills the shell unless a complete wrapper cancels it within 10 seconds, so a half-received script can't hold the shared console session. * Each output stream is copied (up to 64 KiB + 1 byte) before it is measured and encoded, so background jobs that are still writing can't make the reported size disagree with the bytes sent. * Bound every step before dispatch: Proxmox requests (including the ticket login) and the WebSocket handshake time out after 10 s. executeGuest takes the lease expiry and refuses to open the console, or to send the wrapper, unless the lease outlasts the remaining deadlines. The lease is now 150 s to cover them. * Keep the lease when the outcome is unknown, since the command may still be running in the shared session. It expires after the guest-side limits have stopped the command. * The route test mock keeps the real EXEC_LEASE_SECONDS.
The wrapper set umask 077 to make its scratch directory private, and the command inherited it, so files a command created (an installed config, a web root) were unreadable to non-root services. Create the directory with mkdir -m 700 instead and leave the umask alone.
The wrapper exits after printing its result, which ends the shared dtach session, but the lease was released as soon as the result was parsed. An exec admitted in that gap could attach to the dying session and fail. Wait up to 5 s for termproxy to close the console first.
CodeQL flagged String#replace with a string pattern, which removes only the first match.
Shells start background jobs with SIGINT and SIGQUIT ignored, and the command ran as one, so a daemon it started kept ignoring them. Run the command in the foreground through a small sh -c that records its pid, and let the background time limit kill that pid.
The time limit can be shortened in wrapperScript for a test that checks a command running past it is killed with exit 137, the timed-out flag set, and its partial output kept. The watchdog reads the command's pid with cat, so the admin docs now list it.
faff729 to
db9f81a
Compare
There was a problem hiding this comment.
🔵 Needs a closer look
The final bootstrap, watchdog, and cleanup changes need human validation through real Proxmox termproxy/dtach because existing fixtures do not establish session cleanup and lease safety in that topology.
No open issues 🎉
1 file not reviewed
create-a-container/package-lock.json: Generated file
Review effort: Balanced


Part of #541. Replaces #543.
Owners and admins can run one command as root in a running Proxmox container with
mieweb exec. Manager uses only the node's existing Proxmox API (termproxy+vncwebsocket). Nothing is installed on the Proxmox hosts or in the guest, Manager needs no SSH access to the nodes, and the guest needs no SSH. The design follows the review on #543.How it works
With
cmode: shell, the Proxmox console of a container is a root shell (lxc-attach) with no login prompt.sh -s.</dev/null, sends stdout and stderr to files in a private temp directory, and enforces a 30-second limit. The wrapper is one brace group, so the shell runs nothing until all of it has arrived. A timer started by the bootstrap line kills the shell if a complete wrapper doesn't arrive within 10 seconds.od) between markers that contain a per-request nonce.Changes
POST /api/v1/sites/{siteId}/containers/{id}/execOpenAPI contractexecverb and its testsutils/guest-exec.js: the console client, bootstrap, wrapper and result parser.ProxmoxApimethods:lxcTermproxy()andopenLxcTermSocket(), plus acurrentoption onlxcConfig().wsdependency: Node's built-in WebSocket can't use the node's TLS agent or auth headers.cmode: shellat create and reconfigure. Proxmox applies acmodechange to a running container only after it restarts, so the first exec on an older container sets it and returnsexec_restart_required(409).&jobs are hung up. Processes started withsetsid,nohupor a service manager keep running.exec_busy(409), because Proxmox shares onedtachconsole session per container. The claim is a 150-second lease on the Container row (new nullableexecLeaseUntilcolumn, set with a conditional update), so it holds across load-balanced Manager processes and expires on its own if a process dies mid-exec. If the outcome is unknown, the lease is kept until it expires, because the command may still be running in the shared session.executeGuestwon't write to the console unless the lease outlasts the remaining deadlines.timeoutoption onNode#api), the WebSocket handshake and termproxy'sOKeach time out after 10 s. After the result, Manager waits up to 5 s for the console to close before releasing the lease.exec_forbiddenis removed.create-a-container/**except the React client, instead of a growing list of files.docs/admins/guest-exec.mdcovering the required privileges (VM.Audit,VM.Console,VM.Config.Options), console mode, restarting older containers, limits, and the shared console session.Testing
Real Proxmox (compose stack, PVE 9.2.20). The test guest was created through Manager from
ghcr.io/mieweb/opensource-server/base:latest.cmode: shellat create, and the first exec worked without a restart.id; uname -n; printf err >&2; exit 23returned root, the hostname,erron stderr and exit 23, in about 0.5 s.^\,^U,^C,^D), a 10 KB argument, quotes, unicode and CR/LF.kill -TERM $$gave 143.sleep &was hung up, whilesetsid sleep &andnohup sleep &kept running. No timeout watcher, temp directory or console session was left behind.exec_busy(with the earlier in-memory lock; the lease that replaced it was tested on SQLite and Postgres).sleep 45gotexec_timeoutafter 30.5 s.guest_not_running. A running guest inttymode gotexec_restart_requiredwithcmode: shellpending, and worked after a reboot.sh -sleft in the shared console session by an interrupted exec was recovered on the next exec.VM.Audit,VM.ConsoleandVM.Config.Optionsworked throughvncwebsocket, including the restart-required path.The real-Proxmox results above were taken before the review hardening (brace-group wrapper, bootstrap timer, foreground command, stream copies). Those changes were checked through a real terminal with interactive bash and dash, but not yet re-run on Proxmox.
Automated tests
utils/__tests__/guest-exec.test.jsruns the wrapper through a realsh(bash, and dash innode:24-bookworm-slim). It covers literal argv, binary streams, truncation, exit codes and background-job cleanup.executeGuestagainst a faketermproxyserver that frames input and turns\ninto\r\nlike the real console. It covers the success path plus the hostname, stopped, restart-required, busy, dropped-connection and refused-ticket cases.create-a-containersuite: 325/325 tests pass, excludingmcp-proxyandagents.checkin, which also fail onmain. The OS provider typecheck passes, and all 126 provider tests pass.Diff stats
Against
main, including comments. Lines are shown as+added −removed.create-a-container)packages/os-cloud-provider)mie-opensource-landing).github/workflows)package-lock.json(generated)Manager breakdown:
utils/guest-exec.js,utils/proxmox-api.jsguest-exec.test.js)routers/api/v1/containers.js,openapi.v1.yamlcontainers.exec.test.js)models/container.js, migrationcontainers.exec.test.js)models/node.jsutils/container-state.jscontainer-state.test.js)wsdependencypackage.jsonKnown limitations
cmode: shell, any Proxmox user withVM.Consoleon the container gets a root shell from the web console without logging in.sh,stty,mkdir,sleep,cat,wc,ddandod. Images with no shell (distroless) are unsupported.The CLI companion, mieweb/cloud#30, is already merged and doesn't depend on specific error codes.