exec

package
v1.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DefaultInterpreter = "/bin/bash"

DefaultInterpreter runs a verified file when --interpreter names none.

View Source
const FileContentMaxBytes = 65536

FileContentMaxBytes is the server's ceiling on a verified file's content: 64 KB, counted in UTF-8 bytes. Checked locally so an oversized script is refused before it travels.

View Source
const PurposeMaxLength = 2000

PurposeMaxLength is the server's ceiling on a stated purpose. Checked here so an over-long one is a usage error rather than a 400 that costs a parked command its one demand.

Variables

View Source
var ExecCmd = &cobra.Command{
	Use:   "exec [flags] [USER@]SERVER [--] [COMMAND...]",
	Short: "Execute a command on a remote server",
	Long: `Execute a command on a remote server.

This command executes a specified command on a remote server and returns the output.
It supports SSH-like syntax for specifying the user and server.

Use -- to separate alpacon flags from the remote command, ensuring that flags
intended for the remote command (e.g., -U, -d) are not interpreted as alpacon flags.

All flags must be placed before the server name.

Subcommand names (ls, logs, purpose) win over a server of the same name. To reach
a server literally named 'ls', 'logs' or 'purpose', put -- before it:
alpacon exec -- ls uptime

Shell metacharacters (;, |, &, $) pass through unquoted to the remote shell.
To send a literal metacharacter, wrap the argument in quotes:
  alpacon exec server 'echo hello;world'

Verified file execution (--file) submits a script as structure instead of a
command line: the platform hashes the bytes the reviewer sees, and the agent
proves at execution time that the file it runs on the server is those bytes.
The file must already exist at that path on the target server; the CLI reads
the content from the same path locally (or from --file-from) so the reviewer
and the assessor judge what you are about to run. An approval binds exactly
those bytes, on that server, as that account, with those arguments—it does not
mean "the file is safe". Environment, libraries, the interpreter's version and
anything the script fetches at run time are yours; only the first entrypoint
is verified. Composition (pipes, redirection, &&) goes inside the script, where
it is reviewed and hashed with it; a one-off composition around a script stays
on the ordinary command line. A reviewer can mark an approval standing, and an
unchanged re-run then stops asking anyone—one changed byte re-queues review.
Standing lasts the days --reuse-days proposed; with no proposal it lasts
until the workspace ceiling, or indefinitely when the workspace has none.

Flags:
  -u, --username [USER_NAME]    Specify the username for command execution.
  -g, --groupname [GROUP_NAME]  Specify the group name for command execution.
  --env="KEY"                   Pass an environment variable to the remote command,
                                reading its value from the current shell. This keeps
                                the value off your local alpacon command line—use it
                                for secrets such as passwords or tokens.
  --env="KEY=VALUE"             Set 'KEY' to a literal value. Discouraged: the value
                                stays on your local alpacon command line, so it lands
                                in shell history, ps output, and CI job logs. Never
                                pass credentials this way.
  --file PATH                   Run the script at PATH on the server as a verified
                                file instead of a command line. PATH is absolute on
                                the target; the content is read from the same path
                                locally and sent byte-for-byte (64 KB at most). The
                                script's arguments go after --; --file takes no
                                command line and no --env. Arguments are recorded
                                with the command and shown to the reviewer, so a
                                secret goes in a file or the environment the
                                script reads at run time, never in an argument.
  --file-from LOCAL_PATH        Read the script's content from LOCAL_PATH instead of
                                PATH. The file on the server must be byte-identical,
                                or the agent refuses to run it.
  --interpreter PATH            Interpreter for --file (default /bin/bash). Must be
                                an absolute path; a bare name would let the server's
                                PATH decide what runs.
  --reuse-days N                Propose how long an approval of --file stays
                                reusable, 1 to 366 days. The approver decides
                                whether to grant reuse; a workspace ceiling lower
                                than N refuses the request. Without the flag an
                                opted-in grant lasts until the workspace ceiling,
                                or indefinitely without one.
  --work-session [UUID]         Attach this command to a work-session.
                                Overrides the workspace's active session set via
                                'alpacon work-session use'.
  --purpose "TEXT"              State what this command is for (max 2000 chars).
                                The assessor judges the command with it in hand,
                                so a command that would otherwise queue for a
                                human may clear on its own. State a fact local to
                                this host that the session description does not
                                already imply; general knowledge adds nothing the
                                assessor lacks, and a purpose cannot lower a
                                command's intrinsic risk.
  --detach                      Submit the command and return immediately without
                                waiting for completion. Prints the job ID to stdout.
                                Use 'alpacon exec logs JOB_ID' to retrieve the result.
                                Inside an agent-requester work session, a command
                                the gate holds for its purpose can sit for about a
                                minute before taking the ordinary path—nothing here
                                waits, but the command does. Pass --purpose to skip
                                the hold, or read the demand with 'exec logs'.
  --wait                        When a sudo command needs human approval, block and
                                re-attempt until a reviewer approves it in the Alpacon
                                console (web), or the wait times out (default 5m).
  --wait-approval DURATION      Like --wait with a custom wait timeout (e.g. 30m;
                                default 5m). Implies --wait.

Exit code 3 indicates a WorkSession gate denial; run with --output json to
parse a machine-readable diagnostic on stderr.
Exit code 4 indicates the sudo command is pending human approval (approve it in
the Alpacon console, then re-run, or pass --wait to block—--wait-approval
DURATION to block with a longer timeout); --output json emits
{"status":"pending_approval", ...} on stdout.
Exit code 7 indicates the verification gate held the command and is asking what
it is for. Nobody has been notified and no approval request exists: answer with
'alpacon exec purpose JOB_ID "..."' within about a minute, or pass --purpose up
front and skip the demand. --wait does not apply—the answer is yours to give,
not somebody else's to grant. --output json emits {"status":"purpose_required",
...} on stdout, carrying the command id and what makes a purpose useful.
The server rejects a command whose command line carries a credential—a
-p/--password flag, a KEY=VALUE secret such as PGPASSWORD=..., or a
user:pass@host connection string—before it runs, with exit code 1. Pass the
secret with --env="KEY" instead. A --file script that carries a credential is
refused the same way; take the secret out of the script and have the script
read it on the host at run time. --output json emits an error envelope on
stderr with error_code command_inline_credential.
Requires an active WorkSession when using Browser login (Auth0); Token auth (API token or Service token) bypasses this requirement.`,
	Example: `  # Simple command execution
  alpacon exec prod-docker docker ps
  alpacon exec root@prod-docker docker ps

  # Use -- to pass flags to the remote command
  alpacon exec root@db-server -- docker exec postgres psql -U myproject -d myproject
  alpacon exec my-server -- grep -r "pattern" /var/log

  # Specify user and group with flags
  alpacon exec -u root prod-docker systemctl status nginx
  alpacon exec -g docker user@server docker images

  # Pass a secret via the shell env; the value stays off the alpacon command line.
  # Read it in rather than typing it inline, so it stays out of shell history too.
  # psql reads PGPASSWORD from the environment, so it never reaches the remote argv.
  printf 'PGPASSWORD: ' && read -rs PGPASSWORD && export PGPASSWORD
  alpacon exec --env="PGPASSWORD" db-server -- psql -h localhost -U app -c 'SELECT 1'

  # Submit a command asynchronously and retrieve the result later
  alpacon exec --detach web-server -- apt-get update
  alpacon exec logs <JOB_ID>

  # Block up to 30 minutes for a reviewer to approve a sudo command
  alpacon exec --wait-approval 30m root@prod-docker -- systemctl restart nginx

  # State what the command is for, so it is judged with that in hand
  alpacon exec --purpose 'chronyd drifted 40s; the renewed cert reads as future-dated' \
    prod-web -- systemctl restart chronyd

  # Run a script the reviewer can read, verified byte-for-byte on the server.
  # /opt/deploy.sh must exist on prod-web; its content is read from the same path
  # locally unless --file-from names another copy. Script arguments go after --.
  alpacon exec --file /opt/deploy.sh root@prod-web -- --fast
  alpacon exec --file /opt/deploy.sh --file-from ./deploy.sh --interpreter /bin/sh prod-web

  # Propose that the approval stay reusable for 30 days; the approver decides
  alpacon exec --file /opt/deploy.sh --reuse-days 30 root@prod-web -- --fast`,

	DisableFlagParsing: true,
	Run: func(cmd *cobra.Command, args []string) {
		parsed := ParseRemoteExecArgs(args)

		if parsed.ShowHelp {
			_ = cmd.Help()
			return
		}

		if parsed.Err != "" {
			utils.CliErrorWithExit("%s", parsed.Err)
			return
		}

		if parsed.Server == "" {
			_ = cmd.Help()
			utils.CliErrorWithExit("server name is required.")
			return
		}

		if parsed.Command == "" && parsed.File == nil {
			utils.CliErrorWithExit("You must specify a command to execute, or a script with --file.")
			return
		}

		RunRemoteExec(parsed)
	},
}

Functions

func AddListFlags added in v1.9.2

func AddListFlags(cmd *cobra.Command)

AddListFlags and RunListFromFlags are exported for the deprecated 'alpacon event', which delegates here. Both live in this file so the flag names exist in exactly one place.

func HandleCommandResult added in v1.4.8

func HandleCommandResult(err error, invokedAs Invocation)

HandleCommandResult exits appropriately on error. Output is streamed to stdout during execution; on a remote failure the error carries that output, used here only to surface the sudo-denial hint (not re-printed). invokedAs names the command the user ran so a hint can quote it; empty falls back to exec.

func HandleFileExecInlineCredential added in v1.15.0

func HandleFileExecInlineCredential(err error) bool

HandleFileExecInlineCredential reports command_inline_credential with the file lane's hint and exits 1, or returns false when err is something else. Call it only on the file lane: the shell lane shares the code and answers it in HandleCommandResult with --env.

func HandleFileExecRefusal added in v1.13.1

func HandleFileExecRefusal(err error, serverName string) bool

HandleFileExecRefusal reports a file-lane refusal and exits 1, or returns false when err is something else. Under --output json the envelope carries the server's code; table mode prints the message and the hint. It runs before HandleCommandResult, which knows no server name and would print the raw code.

func HandlePendingApproval added in v1.7.2

func HandlePendingApproval(err error, reRunHint utils.NextAction) bool

HandlePendingApproval emits the structured pending-approval feedback for a command left pending human approval and not waited on—either a job the server parked at awaiting_approval (PendingApprovalError) or a sudo denial with an approval request in flight—then exits with ExitCodePendingApproval. It reports true when it handled the err; the caller skips its normal result handling on true. The status-hold path carries no approval request id; the sudo-denial path carries one only when a --wait poll picked one up along the way (pendingWithRequestID), so the machine signal reports an id when it has one and omits it otherwise. reRunHint is the exact command the caller invoked (with any --env caveat in its Description), so a human can copy-paste it once the request is approved.

func HandlePurposeDemand added in v1.12.0

func HandlePurposeDemand(err error) bool

HandlePurposeDemand reports a command the gate parked for its purpose and exits, or returns false when err is something else.

It never waits, not even under --wait. --wait exists because an approval is somebody else's to give and the caller can only block; a purpose demand is this caller's own to answer, and the window is about a minute, so blocking would spend the command's single chance on sleep. It runs ahead of HandlePendingApproval because a parked command has no approval request yet: reporting one would name a queue nobody has been added to.

func ParseEnvArg added in v1.9.0

func ParseEnvArg(arg string, env map[string]string) string

ParseEnvArg parses a --env token into env. A bare KEY reads the shell value, warning and skipping if unset; malformed input returns an error message.

func RunCommandWithRetry added in v1.3.2

func RunCommandWithRetry(ac *client.AlpaconClient, serverName, command, username, groupname string, env map[string]string, workSessionID, purpose string, out io.Writer) error

RunCommandWithRetry executes a remote command with MFA/username-required error handling and retry logic, streaming output to out. workSessionID is forwarded as the work_session field; pass "" to omit it.

The attempt and its retries share one output stream: the MFA wait retries a refused submission once a second for minutes, and a stream per attempt would open an event session and a WebSocket each time.

func RunExecWithApprovalWait added in v1.7.2

func RunExecWithApprovalWait(ac *client.AlpaconClient, serverName, command, username, groupname string, env map[string]string, workSessionID, purpose string, waitTimeout time.Duration, out io.Writer) error

RunExecWithApprovalWait runs a command via RunExecWithPresenceStepUp and, when it is denied with an approval request in flight (a pendingApproval code) and waitTimeout is positive, blocks and polls the command's detail until a reviewer grants or refuses the request out of band, or the bounded timeout elapses. When waitTimeout is zero or negative, or the denial carries a terminal code, it returns the first err unchanged so the caller's pending/denial handling runs.

A tick that never reached the server is not an answer: the loop backs off, and a timeout—or a run of failed polls long enough to give up on—reports the denial that opened the wait, so the caller still exits on the pending contract rather than as a generic failure.

The poll reads the command's own detail (sudo_grant_status) rather than re-submitting it: the denial carries the command id, and re-attempting a command still pending approval would file a fresh approval request on every tick. The poll mirrors the MFA step-up structure (api/mfa/mfa.go): a spinner, a timer, and a precise deadline.

func RunExecWithPresenceStepUp added in v1.7.2

func RunExecWithPresenceStepUp(ac *client.AlpaconClient, serverName, command, username, groupname string, env map[string]string, workSessionID, purpose string, out io.Writer) error

RunExecWithPresenceStepUp runs a command via RunCommandWithRetry and, when it is denied for a missing recent MFA (SUDO_PRESENCE_REQUIRED) on an interactive terminal, offers an MFA step-up and retries once. Non-interactive callers (scripts, CI, AI agents) fall through unchanged so HandleCommandResult prints the static denial hint; non-interactive humans additionally get the verification link they can complete out of band. Reached via RunRemoteExec by exec and websh command mode; interactive websh keeps its own sudo MFA flow.

func RunFileExecWithApprovalWait added in v1.13.1

func RunFileExecWithApprovalWait(ac *client.AlpaconClient, serverName string, file event.FileExecution, username, groupname, workSessionID, purpose string, waitTimeout time.Duration, out io.Writer) error

RunFileExecWithApprovalWait is RunExecWithApprovalWait for the verified file lane. Only the submission differs—the file object in place of a command line—so the presence step-up, the approval wait and the re-run after a grant are the same layers the generic lane runs through.

func RunListFromFlags added in v1.9.2

func RunListFromFlags(cmd *cobra.Command)

RunListFromFlags requires the flag set registered by AddListFlags.

func RunRemoteExec added in v1.9.0

func RunRemoteExec(parsed RemoteExecArgs)

RunRemoteExec is the shared post-parse execution path for exec and websh command mode. Requires Server and either Command or File to be set.

func ShellJoin added in v1.4.8

func ShellJoin(parts []string) string

ShellJoin reassembles tokenized command parts into a single string. Parts containing whitespace or single quotes are re-quoted to preserve argument boundaries; metacharacters pass through for the remote shell. A single-element slice is returned as-is (already a formed command line).

Types

type FileExecArgs added in v1.13.1

type FileExecArgs struct {
	// Path is the script's location on the target server, and by default the
	// local file the content is read from.
	Path string
	// From, when set, is the local file the content is read from instead.
	From string
	// Interpreter runs the file on the target; DefaultInterpreter when empty.
	Interpreter string
	// Args are passed to the script as given, one argv entry each.
	Args []string
	// ReuseDays is the proposed reuse duration in days; 0 means none was given.
	ReuseDays int
}

FileExecArgs is the file lane as the user asked for it on the command line: --file, --file-from, --interpreter, --reuse-days and the arguments after --. From and Interpreter are as typed, empty when the flag was not given; loadFileExecution fills the defaults, so a re-run hint can repeat only what the user said.

type Invocation added in v1.9.2

type Invocation string

Invocation names the command the user ran, so a hint can show an example they can copy without translating it first. A defined type rather than a bare string, so an arbitrary string variable cannot reach it without a conversion that names the intent. Websh command mode reaches this package through RemoteExecArgs.InvokedAs; the zero value renders as exec.

const (
	ExecInvocation  Invocation = "alpacon exec"
	WebshInvocation Invocation = "alpacon websh"
)

ExecInvocation and WebshInvocation are the two Invocation values (see the Invocation type below).

type RemoteExecArgs added in v1.3.2

type RemoteExecArgs struct {
	Username      string
	Groupname     string
	WorkSessionID string
	OutputFormat  string
	Server        string
	Command       string
	// What this command is for. Sent on submission, so the assessor judges
	// with it on the first pass and no demand is issued.
	Purpose string
	// InvokedAs selects which syntax a hint renders its example in. The caller
	// sets it, not ParseRemoteExecArgs: websh command mode marks its args
	// WebshInvocation, and exec leaves it empty, which the hint reads as exec.
	InvokedAs    Invocation
	Env          map[string]string
	WaitApproval time.Duration
	Detach       bool
	Wait         bool
	ShowHelp     bool
	Err          string
	// File is set by --file and selects the verified file lane, in which case
	// Command is empty and the words after -- are the script's arguments. Nil
	// on the generic lane, so every existing caller reads as before.
	File *FileExecArgs
}

RemoteExecArgs holds parsed arguments for remote command execution.

func ParseRemoteExecArgs added in v1.3.2

func ParseRemoteExecArgs(args []string) RemoteExecArgs

ParseRemoteExecArgs parses raw CLI arguments with manual flag handling. It recognizes -u/--username, -g/--groupname, and -h/--help flags before the server name.

The -- separator has two roles depending on position:

  • After the server name: acts as a command separator. Everything after it is the remote command, with no further flag parsing.
  • Before the server name (e.g., after flags): acts as an end-of-flags marker. The first arg after -- becomes the server, the rest is the command.

Without --, everything after the server name is the remote command.

Layout: [flags] [USER@]SERVER [--] COMMAND...

With --file the words after the server are the script's arguments and must follow --: a command line and a verified file cannot be combined, and a word list with no separator is how one would be mistaken for the other.

func (RemoteExecArgs) WaitTimeout added in v1.9.1

func (a RemoteExecArgs) WaitTimeout() time.Duration

WaitTimeout returns the effective approval-wait timeout, or 0 when not waiting.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL