exec

package
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 25 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.

The session purpose is what the assessor judges each command against. An agent
should pass --purpose with each command, which skips the purpose demand entirely.

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, or --upload writes it
there first; 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.
A script that exists only on the server takes --from-server: the CLI reads the
file from the server as the account the script runs as, and submits those
bytes, so no local copy is needed. With --upload the bytes written are the bytes submitted, and the agent still
hashes the file at execution and refuses a mismatch. A file --upload wrote stays
on the server even when the submission is then refused. 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. The approver decides whether to grant reuse, and a grant
always expires: after the days --reuse-days proposed, or at the workspace
ceiling (1 to 366 days, default 90).

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.
  --upload                      Write the script to PATH on the server first, then
                                submit it, in one step. The file is written as the
                                account and group the script runs as (-u or USER@,
                                -g, or the server's default account when neither
                                is given): a new file takes that account's umask,
                                missing directories are created, and the
                                interpreter reads the file, so no execute bit is
                                needed. An existing file is refused unless
                                --overwrite is given. PATH must be clean: no
                                '.' or '..' and no repeated or trailing slash.
  --overwrite                   With --upload, replace a file already at PATH. The
                                file keeps its owner and mode.
  --from-server                 Read the script's content from PATH on the server
                                instead of a local file, as the account and group
                                the script runs as, and submit those bytes. Use it
                                for a script that already exists only on the
                                server. Cannot be combined with --upload or
                                --file-from.
  --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, and a grant expires after
                                N days or at the workspace ceiling (1 to 366 days,
                                default 90), whichever is sooner. A ceiling lower
                                than N refuses the request. Without the flag no
                                duration is proposed; the approver may still
                                grant reuse up to the ceiling.
  --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. Without a purpose it is judged again: it
                                runs, waits for a human approver (who is notified
                                then), or is refused. Pass --purpose to skip the
                                hold, or read the result with 'exec logs'; do not
                                resubmit.
  --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.

A command admitted by a standing file-execution grant is marked in the result.

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.
A command whose line carries a script body—a heredoc, a multi-line -c or -e
body, or a decoded payload piped into a shell—can be refused when the
workspace approval policy blocks script bodies, with exit code 6 and the code
use_file_execution. Then save the script to a local file and run it on the
same server as the same account with --upload --file PATH --file-from
LOCAL_PATH, which writes it to PATH and runs it in one step, or with --file
PATH --from-server when the script is already at PATH on the server. Add
--interpreter ABSOLUTE_PATH for a script /bin/bash does not run, such as a perl
-e body.
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

  # Run a script that exists only on the server; its content is read from there.
  alpacon exec --file /opt/deploy.sh --from-server root@prod-web -- --fast

  # Write a local script to the server and run it as a verified file, in one step.
  alpacon exec --upload --file /opt/deploy.sh --file-from ./deploy.sh root@prod-web -- --fast

  # 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.CliParseErrorWithExit(cmd, parsed.OutputFormat, parsed.Err)
			return
		}
		if parsed.OutputFormat != "" {
			if err := utils.SetOutputFormat(parsed.OutputFormat); err != nil {
				utils.CliUsageErrorWithExit("%s", err)
			}
		}

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

		if parsed.Command == "" && parsed.File == nil {
			utils.CliUsageErrorWithExit("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 HandleExecUserRefusal added in v1.16.0

func HandleExecUserRefusal(err error, parsed RemoteExecArgs) bool

HandleExecUserRefusal reports the missing execution user and exits 1, or returns false when err is something else. Under --output json it returns false, leaving the generic error envelope.

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, parsed RemoteExecArgs) bool

HandlePendingApproval reports a command left pending human approval and not waited on—a job the server parked at awaiting_approval (PendingApprovalError) or a sudo denial with an approval request in flight—and exits with ExitCodePendingApproval, or returns false when err is neither. The approval request id is reported only when a --wait poll picked one up (pendingWithRequestID). The sudo-denial path repeats the invoked command (reRunHint), and a held command line the server reads as a script also gets its --file --from-server form (fileSuggestionAction).

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 HandleUseFileExecutionRefusal added in v1.18.0

func HandleUseFileExecutionRefusal(err error, parsed RemoteExecArgs) bool

HandleUseFileExecutionRefusal reports a use_file_execution refusal with the file lane guidance and exits 6, or returns false when err is something else. It runs ahead of HandleCommandResult, which knows neither the server nor the account flags the guidance repeats.

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 and waitTimeout is positive, polls the command's detail until a reviewer grants or refuses the request or the timeout elapses. A job the server parked at awaiting_approval is instead streamed once approved. With no positive waitTimeout, or on a terminal denial, it returns the first err unchanged.

A poll that never reached the server is not an answer: the loop backs off. A timeout, a run of failed polls, or a fatal 4xx on the read returns the denial that opened the wait, so the caller still exits on the pending contract.

The poll reads sudo_grant_status rather than re-submitting the command, which would file a fresh approval request on every tick.

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. A non-interactive caller gets the verification link to complete out of band and the denial unchanged, so HandleCommandResult prints the static hint. 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, Command or File, and the parsed --output applied.

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
	// Upload writes the content to Path on the server before the submission,
	// so the file need not be there already.
	Upload bool
	// Overwrite lets Upload replace a file already at Path; without it the
	// agent refuses an existing file.
	Overwrite bool
	// FromServer reads the content from Path on the server instead of a local
	// file, for a script that exists only there.
	FromServer bool
}

FileExecArgs is the file lane as given on the command line: --file, --file-from, --interpreter, --reuse-days, --upload, --overwrite, --from-server and the arguments after --. From and Interpreter stay empty when their flag was not given, so a re-run hint repeats only what the user typed.

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.
	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. Flags are recognized only before the server name.

The -- separator has two roles depending on position:

  • After the server name: everything after it is the remote command, with no further flag parsing.
  • Before the server name: it ends the flags; the first arg after it is 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 --, so a command line is never mistaken for a verified file's arguments.

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