Documentation
¶
Index ¶
- Constants
- Variables
- func AddListFlags(cmd *cobra.Command)
- func HandleCommandResult(err error, invokedAs Invocation)
- func HandlePendingApproval(err error, reRunHint utils.NextAction) bool
- func HandlePurposeDemand(err error) bool
- func ParseEnvArg(arg string, env map[string]string) string
- func RunCommandWithRetry(ac *client.AlpaconClient, serverName, command, username, groupname string, ...) error
- func RunExecWithApprovalWait(ac *client.AlpaconClient, serverName, command, username, groupname string, ...) error
- func RunExecWithPresenceStepUp(ac *client.AlpaconClient, serverName, command, username, groupname string, ...) error
- func RunListFromFlags(cmd *cobra.Command)
- func RunRemoteExec(parsed RemoteExecArgs)
- func ShellJoin(parts []string) string
- type Invocation
- type RemoteExecArgs
Constants ¶
const PurposeMaxLength = 2000
PurposeMaxLength is the server's ceiling on a stated purpose (ADR 0052). Checked here so an over-long one is a usage error rather than a 400 that costs a parked command its one demand.
Variables ¶
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' 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. --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; --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`, 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 == "" { utils.CliErrorWithExit("You must specify a command to execute.") return } RunRemoteExec(parsed) }, }
Functions ¶
func AddListFlags ¶ added in v1.9.2
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 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
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
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.
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 RunListFromFlags ¶ added in v1.9.2
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 Command to be non-empty.
func ShellJoin ¶ added in v1.4.8
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 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 (ADR 0052). 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
}
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...
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.