event

package
v1.21.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 23 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 (
	RejectionCauseApprovalExpired  = utils.ApprovalExpired
	RejectionCauseApprovalRejected = "approval_rejected"
	// RejectionCauseSignatureInvalid comes with status completed, since the agent
	// refuses the file after delivery, and IsRejected still counts it a rejection.
	RejectionCauseSignatureInvalid = "signature_invalid"
	// RejectionCauseApprovalRuleChanged closes a command held for the session's
	// assignee when the rules no longer send it there at the moment of
	// confirmation. Sent again, the command is judged under the rules then.
	RejectionCauseApprovalRuleChanged = utils.ApprovalRuleChanged
)
View Source
const (

	// Left untyped so every const stays in one block; they remain assignable and
	// comparable to EventType.
	EventTypeSudo          = "sudo"
	EventTypeCommandOutput = "command_output"
	// EventTypeCommandFin is subscribed with a server id, not a command id: that is
	// the channel the server publishes it on.
	EventTypeCommandFin = "command_fin"
)
View Source
const ApprovalLaneAssignee = "assignee"

ApprovalLaneAssignee is the approval_lane of a held command whose confirmation belongs to the session's assignee, not to an approver.

View Source
const RejectionCauseUseFileExecution = "use_file_execution"

RejectionCauseUseFileExecution is the rejection_cause of a command line that carries a script body; it covers one command on one server.

Variables

View Source
var CommandPollTick = time.Second

CommandPollTick paces a command poll with no stream behind it. A var so a test's helper process, which no in-process seam reaches, can shorten it.

Functions

func AnswerPurposeDemand added in v1.12.0

func AnswerPurposeDemand(ac *client.AlpaconClient, cmdID, purpose string) error

AnswerPurposeDemand states what a parked command is for and sends it back through verification. The server re-judges it once with the purpose in hand, and whatever that verdict is—run, hold for a human, or deny—follows the path an un-parked command takes.

The server answers a command that is not parked and an answer from anyone but the requester with the same error, so a failure here cannot be read as "the deadline passed" specifically.

func CloseEventSession added in v1.16.0

func CloseEventSession(ctx context.Context, ac *client.AlpaconClient, id string) error

CloseEventSession closes an event session. The server keeps a closed session and answers 204 for one that is already closed.

func DescribePhase added in v1.4.8

func DescribePhase(phase string) string

DescribePhase returns the human-readable description for an error_phase, or the raw identifier when the phase is unknown. An unknown file_* phase gets a generic file lane description instead of the bare code.

func GetCommandOutput added in v1.8.1

func GetCommandOutput(ac *client.AlpaconClient, cmdID string) (string, error)

GetCommandOutput reconstructs the full command output from its chunks in seq order. It returns an empty string when no chunks were produced.

func IsAwaitingApprovalStatus added in v1.7.4

func IsAwaitingApprovalStatus(status string) bool

IsAwaitingApprovalStatus reports whether status is the server's hold for a command awaiting out-of-band human approval, not yet delivered to the agent.

func IsAwaitingPurposeStatus added in v1.12.0

func IsAwaitingPurposeStatus(status string) bool

IsAwaitingPurposeStatus reports whether status is the server's hold state for a command parked while the gate asks the requester what it is for. Unlike the approval hold this one is answerable here and expires on its own in about a minute, after which the command takes the ordinary path.

func IsCompletedStatus added in v1.19.0

func IsCompletedStatus(status string) bool

IsCompletedStatus reports whether status is the server's terminal state for a command the agent finished, successfully or not.

func IsDeniedStatus added in v1.20.0

func IsDeniedStatus(status string) bool

IsDeniedStatus reports whether status is the server's terminal state for a submitted command it refused to run, with the reason in denial_code.

func IsRejectedStatus added in v1.11.1

func IsRejectedStatus(status string) bool

IsRejectedStatus reports whether status is the server's terminal state for a command refused before it ran.

func IsRunningStatus added in v1.5.0

func IsRunningStatus(status string) bool

IsRunningStatus reports whether status represents an in-progress (non-terminal) command.

func IsStatusOnlyFailure added in v1.13.1

func IsStatusOnlyFailure(status string) bool

IsStatusOnlyFailure reports the terminal failures whose whole outcome is a line about the status: the command never reached a result worth printing. A new status-only terminal state goes here, not at a caller.

func PhaseHint added in v1.16.0

func PhaseHint(phase string) string

PhaseHint returns the actionable next step for an error_phase, or "" when the phase has none. An unknown file_* phase gets a generic file lane hint.

func ResolveCommandOutput added in v1.13.1

func ResolveCommandOutput(ac *client.AlpaconClient, cmdID, result string) (string, error)

ResolveCommandOutput reconstructs a finished command's output from its chunks, falling back to the result field the command detail carries.

func RunCommandStreaming added in v1.8.1

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

RunCommandStreaming runs a command and streams its output to out over the event WebSocket, falling back to polling (runCommandFallback) when WS setup fails.

func RunFileCommandStreaming added in v1.13.1

func RunFileCommandStreaming(ac *client.AlpaconClient, serverName string, file FileExecution, username, groupname, workSessionID, purpose string, out io.Writer) error

RunFileCommandStreaming is RunCommandStreaming for the file lane. Only the submission differs: the command it creates is followed, polled and read like any other.

func SignalPendingSudoApproval added in v1.20.0

func SignalPendingSudoApproval(ac *client.AlpaconClient, details EventDetails)

SignalPendingSudoApproval signals a successful command whose sudo grant awaits approval.

func StandingGrantLine added in v1.16.0

func StandingGrantLine(details EventDetails) string

StandingGrantLine describes the grant recorded on a command detail.

func StreamApprovedCommand added in v1.8.1

func StreamApprovedCommand(ac *client.AlpaconClient, held *PendingApprovalError, out io.Writer, timeout time.Duration) error

StreamApprovedCommand resubscribes to an already-submitted command and streams its output, waiting through the awaiting_approval hold (bounded by timeout) until a reviewer approves it and it runs. A parked job has produced no output yet, so resubscribing loses nothing.

func SubscribeEvent added in v1.9.2

func SubscribeEvent(ctx context.Context, ac *client.AlpaconClient, channelID string, eventType EventType, targetID string) error

SubscribeEvent subscribes the given channel to eventType events, scoped to targetID (a websh session for sudo, a command for command_output, a work session for work_session). An empty targetID is omitted, which only some event types allow. ctx bounds the request.

Types

type AwaitingPurposeError added in v1.12.0

type AwaitingPurposeError struct {
	CommandID string
	// When the demand stops being answerable, as the server computed it; nil on an
	// older server or a command never asked. No endpoint publishes the window's
	// length, so the remaining window is stated only when this is present.
	ExpiresAt *time.Time
}

AwaitingPurposeError is returned when the server parked a command at the "awaiting_purpose" status: instead of queuing it for a human, the gate asks the requester what the command is for. Nobody has been notified, so the answer is the caller's to give, with 'alpacon exec purpose'. CommandID identifies the parked job; re-submitting would create a second command that may run twice.

func (*AwaitingPurposeError) Error added in v1.12.0

func (*AwaitingPurposeError) Error() string

type CatchUpFunc added in v1.9.2

type CatchUpFunc func(ctx context.Context) (subType string, err error)

CatchUpFunc reads the target's current state over REST and returns it in the event channel's sub_type vocabulary. It closes the window between subscribing and the server's next publish, which is otherwise unrecoverable: the channel has no history. ctx is cancelled when the wait ends, so a read still in flight stops with it.

type Chunk added in v1.8.1

type Chunk struct {
	Seq     int    `json:"seq"`
	Content string `json:"content"`
}

Chunk represents a single stdout/stderr chunk produced during command execution.

type ChunkEvent added in v1.8.1

type ChunkEvent struct {
	Seq     int
	Content string
}

ChunkEvent is a single command_output chunk emitted by the listener.

type ClientTimeoutError added in v1.4.8

type ClientTimeoutError struct {
	// contains filtered or unexported fields
}

ClientTimeoutError is returned when the CLI gave up polling for the command result before the server reported a terminal status.

hint is the server's hint of the refusal the last poll got when the wait ended on it, so it still prints. Only the hint is kept, not the refusal: its code must not turn a timeout into that refusal (a work-session gate, say).

func (*ClientTimeoutError) Error added in v1.4.8

func (*ClientTimeoutError) Error() string

func (*ClientTimeoutError) ErrorHint added in v1.18.0

func (e *ClientTimeoutError) ErrorHint() string

type CommandOutputListener added in v1.8.1

type CommandOutputListener struct {
	// contains filtered or unexported fields
}

CommandOutputListener subscribes to a single command's chunk stream over the event WebSocket, exposing chunks on Chunks() and the command's fin on Finished().

Lifecycle: NewCommandOutputListener -> Start -> subscribeTo -> (consume Chunks) -> Stop. Stop is idempotent and safe to call from any goroutine. Event channel tokens are single-use, so every dial provisions its own session and re-subscribes.

func NewCommandOutputListener added in v1.8.1

func NewCommandOutputListener(ac *client.AlpaconClient) *CommandOutputListener

NewCommandOutputListener constructs a listener without connecting. ac may be nil only for a test that never calls Start. Targets are set later by subscribeTo, because the command is submitted only once the WebSocket is connected.

func (*CommandOutputListener) Chunks added in v1.8.1

func (l *CommandOutputListener) Chunks() <-chan ChunkEvent

Chunks returns a receive-only channel of parsed chunk events.

func (*CommandOutputListener) Err added in v1.11.2

func (l *CommandOutputListener) Err() error

Err returns why the listener could not connect, so a caller that only sees WaitConnected time out can still report the server's own reason.

func (*CommandOutputListener) FinAtRisk added in v1.20.0

func (l *CommandOutputListener) FinAtRisk() <-chan struct{}

FinAtRisk closes once Finished may never fire for the targeted command.

func (*CommandOutputListener) Finished added in v1.10.0

func (l *CommandOutputListener) Finished() <-chan struct{}

Finished fires when the command reaches a terminal state, which the chunks never say: they carry no end marker.

func (CommandOutputListener) Start added in v1.8.1

func (w CommandOutputListener) Start()

Start reads events in a background goroutine, reconnecting automatically until Stop is called.

func (CommandOutputListener) Stop added in v1.8.1

func (w CommandOutputListener) Stop()

Stop shuts down the listener and closes the connection to unblock a pending ReadMessage. Safe to call from any goroutine.

func (CommandOutputListener) WaitConnected added in v1.8.1

func (w CommandOutputListener) WaitConnected(timeout time.Duration) bool

WaitConnected blocks until a dial has connected and its onConnected hook has returned, until timeout, or until shutdown; returns whether it connected. A hook with nothing to subscribe to still counts, so this promises no subscription.

type CommandPollError added in v1.20.0

type CommandPollError struct {
	CommandID string
	Err       error
}

CommandPollError is returned when the poll of a submitted command ended on a failed read. The command was not cancelled, so running it again may run it twice.

func (*CommandPollError) Error added in v1.20.0

func (e *CommandPollError) Error() string

func (*CommandPollError) Unwrap added in v1.20.0

func (e *CommandPollError) Unwrap() error

type CommandPurposeRequest added in v1.12.0

type CommandPurposeRequest struct {
	Purpose string `json:"purpose"`
}

CommandPurposeRequest is the body of the purpose-demand answer. Write-only on the server side: the 202 carries no echo of what was just sent.

type CommandRejectedError added in v1.11.1

type CommandRejectedError struct {
	Username      string
	ConsoleURL    string
	WorkSessionID string
	CommandID     string
	Expired       bool
	Denied        bool
	// DenialCode is the server's denial_code on a denied command.
	DenialCode types.SentString
	Result     string
	// Cause is the server's rejection_cause, such as approval_rejected.
	Cause string
	// Gate is the server's rejection_gate; null for the account and signature causes, so empty.
	Gate string
	// Reported says the detail sent either key; Cause and Gate are empty without it.
	Reported bool
	// SudoGrant marks an outcome read from the sudo grant this command raised; with
	// no cause and not Expired, a reviewer decided it.
	SudoGrant bool
	// Note is the reason the approver wrote, empty when they gave none.
	Note string
	// WorkSessionPaused says this denial paused its work session.
	WorkSessionPaused bool
}

CommandRejectedError is a type so the CLI can exit with ExitCode: a retry is refused again or files another approval request.

func (*CommandRejectedError) Error added in v1.11.1

func (e *CommandRejectedError) Error() string

func (*CommandRejectedError) ErrorCode added in v1.18.0

func (e *CommandRejectedError) ErrorCode() string

ErrorCode returns the denial code before the legacy rejection cause. A lapsed grant without either reports approval_expired.

func (*CommandRejectedError) ErrorFields added in v1.19.0

func (e *CommandRejectedError) ErrorFields() map[string]any

ErrorFields keeps command context and the refusal fields the server sent. Denied results can hold the only recorded reason; reported fields preserve nulls.

func (*CommandRejectedError) ErrorGate added in v1.20.0

func (e *CommandRejectedError) ErrorGate() string

func (*CommandRejectedError) ErrorSource added in v1.18.0

func (*CommandRejectedError) ErrorSource() string

ErrorSource completes the coded error the envelope reads; a rejection names no source.

func (*CommandRejectedError) ExitCode added in v1.19.0

func (e *CommandRejectedError) ExitCode() int

ExitCode is ExitCodeNotApproved for denied commands and legacy rejections. A completed command with a signature refusal keeps its historical exit 1.

func (*CommandRejectedError) LocalSignalAccount added in v1.20.0

func (e *CommandRejectedError) LocalSignalAccount() string

func (*CommandRejectedError) NextActions added in v1.19.0

func (e *CommandRejectedError) NextActions() []utils.NextAction

NextActions returns guidance for legacy rejections. Denied commands and special approval outcomes carry no generic action.

func (*CommandRejectedError) RejectedCommand added in v1.20.0

func (e *CommandRejectedError) RejectedCommand() bool

func (*CommandRejectedError) SubmittedCommandDenied added in v1.20.0

func (e *CommandRejectedError) SubmittedCommandDenied() bool

SubmittedCommandDenied keeps a denied command out of the WorkSession gate diagnostic.

func (*CommandRejectedError) TriggeredPause added in v1.20.2

func (e *CommandRejectedError) TriggeredPause() bool

TriggeredPause reports that this denial paused its work session.

func (*CommandRejectedError) WantsFileExecution added in v1.20.0

func (e *CommandRejectedError) WantsFileExecution() bool

WantsFileExecution says the refusal is a script-body one with guidance of its own; a denied command never gets it, whatever its rejection_cause.

type CommandRejection added in v1.19.0

type CommandRejection struct {
	RejectionCause types.SentString `json:"rejection_cause,omitzero"`
	RejectionGate  types.SentString `json:"rejection_gate,omitzero"`
}

CommandRejection carries the server's two rejection fields, each null when the command was not rejected and absent on an older server.

func (CommandRejection) Label added in v1.19.0

func (r CommandRejection) Label() string

Label is the short cell a list row shows in place of its status.

func (CommandRejection) Reported added in v1.19.0

func (r CommandRejection) Reported() bool

Reported says either key was sent, which an older server never does.

type CommandRequest

type CommandRequest struct {
	Shell       string            `json:"shell"`
	Line        string            `json:"line"`
	Env         map[string]string `json:"env"`
	Data        string            `json:"data"`
	Username    string            `json:"username"`
	Groupname   string            `json:"groupname"`
	ScheduledAt *time.Time        `json:"scheduled_at"`
	Server      string            `json:"server"`
	RunAfter    []string          `json:"run_after"`
	WorkSession string            `json:"work_session,omitempty"`
	// What this one command is for. Sent only when the caller supplied it;
	// with it in hand the assessor judges on the first pass and the demand
	// round trip never happens.
	Purpose string `json:"purpose,omitempty"`
	// Declares that this client answers a purpose demand; the gate does not arm
	// without it. Unconditional because every exec path surfaces the demand to its
	// caller instead of stalling on it.
	PurposeDemandSupported bool `json:"purpose_demand_supported,omitempty"`
	// File selects the verified file lane. Its presence is what the server
	// switches on, so it is omitted from every generic-lane request and no
	// existing request changes shape. When set, MarshalJSON leaves shell,
	// line, env and data out of the body entirely—see fileLaneRequest.
	File *FileExecution `json:"file,omitempty"`
}

func (CommandRequest) MarshalJSON added in v1.13.1

func (r CommandRequest) MarshalJSON() ([]byte, error)

MarshalJSON renders a generic-lane request as its fields stand and a file-lane request as fileLaneRequest, so the keys the server refuses on that lane are absent rather than empty.

type CommandResponse

type CommandResponse struct {
	ID          string              `json:"id"`
	Shell       string              `json:"shell"`
	Line        string              `json:"line"`
	Data        string              `json:"data"`
	Username    string              `json:"username"`
	Groupname   string              `json:"groupname"`
	AddedAt     time.Time           `json:"added_at"`
	ScheduledAt time.Time           `json:"scheduled_at"`
	Server      types.ServerSummary `json:"server"`
	RequestedBy types.UserSummary   `json:"requested_by"`
	RunAfter    []any               `json:"run_after"`
	// contains filtered or unexported fields
}

func SubmitCommand added in v1.5.0

func SubmitCommand(ac *client.AlpaconClient, serverName, command string, username, groupname string, env map[string]string, workSessionID, purpose string) (CommandResponse, error)

func SubmitFileCommand added in v1.13.1

func SubmitFileCommand(ac *client.AlpaconClient, serverName string, file FileExecution, username, groupname, workSessionID, purpose string) (CommandResponse, error)

SubmitFileCommand submits a verified file execution: the same endpoint as SubmitCommand, selected onto the file lane by the file object. The body carries no line, data or env—the server derives the first two and refuses all three by key presence. A nil Args is sent as an empty list, which is the server's default and the shape the contract names.

type CommandStatusError added in v1.20.2

type CommandStatusError struct {
	Status           string
	ErrorPhase       string
	Output           string
	ReportedExitCode *int // the server's exit_code, nil when it sent none
}

CommandStatusError is returned when a command ended in a status that is its whole outcome.

func (*CommandStatusError) Error added in v1.20.2

func (e *CommandStatusError) Error() string

type CommandStream added in v1.15.0

type CommandStream struct {
	// contains filtered or unexported fields
}

CommandStream runs submissions over one output listener. A submission the server refuses leaves the listener connected for the next one, so a caller that retries a refused command, as the MFA wait does once a second, opens one event session rather than one per attempt. A listener that could not connect is not dialed again: later submissions go straight to polling. Close releases a listener no submission used. A CommandStream is not safe for concurrent use.

func NewCommandStream added in v1.15.0

func NewCommandStream(ac *client.AlpaconClient) *CommandStream

NewCommandStream returns a CommandStream that connects on its first submission.

func (*CommandStream) Close added in v1.15.0

func (s *CommandStream) Close()

Close stops a listener that no submission went on to use.

func (*CommandStream) RunCommand added in v1.15.0

func (s *CommandStream) RunCommand(serverName, command, username, groupname string, env map[string]string, workSessionID, purpose string, out io.Writer) error

RunCommand is RunCommandStreaming over this stream's listener.

func (*CommandStream) RunFileCommand added in v1.15.0

func (s *CommandStream) RunFileCommand(serverName string, file FileExecution, username, groupname, workSessionID, purpose string, out io.Writer) error

RunFileCommand is RunFileCommandStreaming over this stream's listener.

type CommandWorkSession added in v1.18.0

type CommandWorkSession struct {
	ID     string `json:"id"`
	Status string `json:"status,omitempty"`
}

CommandWorkSession is the work session a command detail names.

type EventAttributes

type EventAttributes struct {
	ID                    string              `json:"id"`
	Server                string              `json:"server"`
	Shell                 string              `json:"shell"`
	Command               string              `json:"command"`
	Result                utils.TruncatedText `json:"result"`
	Status                string              `json:"status" table:"-"`
	StatusCell            string              `json:"-" table:"Status"`
	ExitCode              *int                `json:"exit_code" table:"-"`
	ErrorPhase            *string             `json:"error_phase" table:"-"`
	Operator              string              `json:"operator"`
	RequestedAt           utils.Timestamp     `json:"requested_at" table:"Requested At"`
	ApprovedFileExecution *json.RawMessage    `json:"approved_file_execution,omitempty" table:"-"`
	DenialCode            types.SentString    `json:"denial_code,omitzero" table:"-"`
	CommandRejection      `table:"-"`
}

func GetEventList

func GetEventList(ac *client.AlpaconClient, tail int, serverName string, userName string) ([]EventAttributes, error)

GetEventList returns the newest tail commands. The endpoint sorts -scheduled_at, so the newest ones arrive first and the walk stops as soon as tail is reached.

type EventDetails

type EventDetails struct {
	ID                    string              `json:"id"`
	Shell                 string              `json:"shell"`
	Line                  string              `json:"line"`
	Success               *bool               `json:"success"`
	ExitCode              *int                `json:"exit_code"`
	ErrorPhase            *string             `json:"error_phase"`
	Result                string              `json:"result"`
	Status                string              `json:"status"`
	DenialCode            types.SentString    `json:"denial_code,omitzero"`
	Cancellable           bool                `json:"cancellable"`
	ResponseDelay         float64             `json:"response_delay"`
	ElapsedTime           float64             `json:"elapsed_time"`
	AddedAt               time.Time           `json:"added_at"`
	Server                types.ServerSummary `json:"server"`
	RequestedBy           types.UserSummary   `json:"requested_by"`
	ApprovedFileExecution *json.RawMessage    `json:"approved_file_execution,omitempty"`
	// What the requester said this command is for, and when the ask expires. Both are
	// absent on an older server and on any command nobody was asked, so nil and empty
	// are ordinary here. The expiry is read rather than purpose_requested_at because no
	// endpoint publishes the window's length; purpose_requested_at is deliberately not
	// parsed: nothing shows it.
	Purpose          string     `json:"purpose"`
	PurposeExpiresAt *time.Time `json:"purpose_expires_at"`
	// The server fills these only on the command detail; the list response omits
	// them, and this struct decodes both. Pointers so an absent field stays
	// distinguishable from a status the server deliberately left empty.
	SudoApprovalRequestID *string `json:"sudo_approval_request_id"`
	SudoGrantStatus       *string `json:"sudo_grant_status"`
	// Held is the open approval deciding this command's sudo. Null, or absent on
	// an older server, says nothing about whether a wait has ended.
	Held *utils.HeldRequest `json:"held"`
	// FileExecutionSuggestion is set on a held command line the server reads as
	// a script on the target; absent otherwise and on older servers.
	FileExecutionSuggestion *FileExecutionSuggestion `json:"file_execution_suggestion"`
	// ScriptBodySuggestion is set on a held command line that carries a script
	// body the file lane could take; absent otherwise and on older servers.
	ScriptBodySuggestion *ScriptBodySuggestion `json:"script_body_suggestion"`
	// ApprovalLane names who decides the open approval holding the command:
	// "assignee" is the session's assignee, any other lane an approver. Null
	// unless the command awaits approval, and absent on an older server.
	ApprovalLane string `json:"approval_lane"`
	ConsoleURL   string `json:"console_url,omitempty"`
	CommandRejection
	// RejectionNote is what the approver wrote when rejecting the hold: null unless a
	// person rejected it, sent only to the requester and the approvers, and absent on
	// an older server.
	RejectionNote *string `json:"rejection_note"`
	// The account the command ran as and the work session it ran under, so a
	// re-run printed from the detail repeats them. WorkSession is null when the
	// command ran under none.
	Username    string              `json:"username"`
	Groupname   string              `json:"groupname"`
	WorkSession *CommandWorkSession `json:"work_session"`
	// WorkSessionPaused marks the denial or hold that paused its work session.
	// FlatWorkSessionID is the flat work_session_id the server sends beside
	// it. Both are absent otherwise and on an older server. Read the session
	// through WorkSessionID, never from either session field directly.
	WorkSessionPaused bool   `json:"work_session_paused"`
	FlatWorkSessionID string `json:"work_session_id"`
}

func GetCommandByID added in v1.5.0

func GetCommandByID(ac *client.AlpaconClient, cmdID string) (EventDetails, error)

func GetCommandByIDWithContext added in v1.21.0

func GetCommandByIDWithContext(ctx context.Context, ac *client.AlpaconClient, cmdID string) (EventDetails, error)

GetCommandByIDWithContext reads a command's details within the caller's context.

func PollCommandExecution

func PollCommandExecution(ac *client.AlpaconClient, cmdID api.PathID) (EventDetails, error)

PollCommandExecution polls with the default timeout and tick. An MFA refusal (auth_mfa_required) is returned at once as the typed error, so the caller can wait for MFA and poll again; the poll only reads, so that is safe.

func (EventDetails) IsRejected added in v1.19.0

func (d EventDetails) IsRejected() bool

IsRejected says the command reached a terminal refusal, including a denied command and a completed command whose file signature failed.

func (EventDetails) Rejection added in v1.19.0

func (d EventDetails) Rejection() *CommandRejectedError

Rejection returns the typed error for a terminal command refusal.

func (EventDetails) StatusError added in v1.21.0

func (d EventDetails) StatusError() *CommandStatusError

StatusError returns d's status-only failure; the caller checks IsStatusOnlyFailure first.

func (EventDetails) WorkSessionID added in v1.20.0

func (d EventDetails) WorkSessionID() string

WorkSessionID is the one reader of the work session a detail names: the nested work_session, else the flat work_session_id of a pause trigger.

func (EventDetails) WorkSessionStatus added in v1.20.2

func (d EventDetails) WorkSessionStatus() string

WorkSessionStatus reads the current session status, empty when the server sends none.

type EventSessionResponse added in v1.4.0

type EventSessionResponse struct {
	ID           string `json:"id"`
	WebsocketURL string `json:"websocket_url"`
	ChannelID    string `json:"channel_id"`
}

EventSessionResponse is returned when creating an event session.

func CreateEventSession added in v1.4.0

func CreateEventSession(ctx context.Context, ac *client.AlpaconClient) (*EventSessionResponse, error)

CreateEventSession creates a new event session and returns the WebSocket URL and channel ID for subscribing to events. ctx bounds the request.

type EventSubscriptionRequest added in v1.4.0

type EventSubscriptionRequest struct {
	Channel   string    `json:"channel"`
	EventType EventType `json:"event_type"`
	// Omitted rather than sent empty: the server validates target_id as a UUID.
	TargetID string `json:"target_id,omitempty"`
}

EventSubscriptionRequest is sent to subscribe to an event type.

type EventType added in v1.9.2

type EventType string

EventType is a server event channel type, marshalled as a plain string. The server defines the full set; untyped literals convert, so types the CLI lacks a constant for stay usable.

type FileExecution added in v1.13.1

type FileExecution struct {
	Path        string   `json:"path"`
	Interpreter string   `json:"interpreter"`
	Args        []string `json:"args"`
	Content     string   `json:"content"`
	// ReuseDays proposes how long an opted-in grant lasts, in days; 0 leaves
	// the key out, the shape a server older than the field accepts.
	ReuseDays int `json:"reuse_days,omitempty"`
}

FileExecution is what a file-lane submission runs: the file at Path on the target host, through Interpreter, with Args. Content is the bytes the reviewer and the assessor judge and the server hashes; the agent hashes the file on the target's disk and runs it only when the two digests match, so Content is sent byte-for-byte—never trimmed, re-encoded, or normalized. Content itself never travels to the agent.

type FileExecutionSuggestion added in v1.17.0

type FileExecutionSuggestion struct {
	Path            string   `json:"path"`
	Interpreter     string   `json:"interpreter"`
	InterpreterName string   `json:"interpreter_name"`
	Args            []string `json:"args"`
}

FileExecutionSuggestion is a held command line the server recognized as a script on the target, restated as a verified file: the script's path, its interpreter and its arguments. Interpreter is set only when the command line named it by absolute path; a bare name such as bash leaves it null and arrives in InterpreterName, since only the target knows where it resolves.

type Outcome added in v1.9.2

type Outcome int

Outcome is how a Wait ended. OutcomeError is the zero value: it is only returned alongside a non-nil error, so a caller that forgets to check err still sees it.

const (
	OutcomeError Outcome = iota
	OutcomeMatched
	OutcomeFailed
	OutcomeTimeout
	OutcomeCanceled
)

type PendingApprovalError added in v1.7.4

type PendingApprovalError struct {
	Username          string
	ConsoleURL        string
	WorkSessionID     string
	WorkSessionStatus string
	CommandID         string
	// FileSuggestion is the server's proposal to run the held command as a
	// verified file instead; nil when the server made none.
	FileSuggestion *FileExecutionSuggestion
	// ScriptBodySuggestion says the held line carries a script body the file
	// lane could take instead; nil when the server sent none.
	ScriptBodySuggestion *ScriptBodySuggestion
	// ApprovalLane is the server's approval_lane: who decides the open request.
	// Empty on an older server.
	ApprovalLane string
	// WorkSessionPaused says this hold paused its work session.
	WorkSessionPaused bool
	// contains filtered or unexported fields
}

PendingApprovalError is returned when the server parked a command at the "awaiting_approval" status: a human must approve it out of band in the Alpacon console before it runs. CommandID identifies the parked job so a --wait caller can poll it; re-submitting would create a duplicate command and approval request.

func (*PendingApprovalError) AssigneeConfirms added in v1.20.0

func (e *PendingApprovalError) AssigneeConfirms() bool

AssigneeConfirms says the held command is the session assignee's own to confirm; any other lane, or none, is an approver's decision.

func (*PendingApprovalError) CurrentWorkSessionStatus added in v1.20.2

func (e *PendingApprovalError) CurrentWorkSessionStatus() string

CurrentWorkSessionStatus reports the latest known state, separate from the pause trigger.

func (*PendingApprovalError) Error added in v1.7.4

func (*PendingApprovalError) Error() string

func (*PendingApprovalError) ErrorFields added in v1.20.0

func (e *PendingApprovalError) ErrorFields() map[string]any

func (*PendingApprovalError) HasCommandDetails added in v1.20.2

func (e *PendingApprovalError) HasCommandDetails() bool

HasCommandDetails reports whether this result includes a successful command detail read.

func (*PendingApprovalError) LocalSignalAccount added in v1.20.0

func (e *PendingApprovalError) LocalSignalAccount() string

func (*PendingApprovalError) LocalSignalAssignee added in v1.20.0

func (e *PendingApprovalError) LocalSignalAssignee() bool

LocalSignalAssignee lets the pending-approval signal word itself for the assignee.

func (*PendingApprovalError) TriggeredPause added in v1.20.2

func (e *PendingApprovalError) TriggeredPause() bool

TriggeredPause reports that this hold paused its work session.

type RemoteCommandError added in v1.4.8

type RemoteCommandError struct {
	Username         string
	ConsoleURL       string
	WorkSessionID    string
	Output           string
	ReportedExitCode *int // the server's exit_code, nil when it sent none
	ErrorPhase       string
	// CommandID identifies the job this failure came from, so an approval wait
	// has something to poll. ApprovalRequestID is filled in by that wait, not
	// by the server response this error is built from.
	CommandID         string
	ApprovalRequestID string
	// Held is the open approval the command detail named, or the one the wait
	// read last; nil when there is none or the server predates the field.
	Held *utils.HeldRequest
}

RemoteCommandError is returned when the remote command completed but exited with a non-zero status.

func (*RemoteCommandError) Error added in v1.4.8

func (e *RemoteCommandError) Error() string

func (*RemoteCommandError) ErrorFields added in v1.20.0

func (e *RemoteCommandError) ErrorFields() map[string]any

func (*RemoteCommandError) ErrorHeld added in v1.20.0

func (e *RemoteCommandError) ErrorHeld() *utils.HeldRequest

func (*RemoteCommandError) ExitCode added in v1.4.8

func (e *RemoteCommandError) ExitCode() int

ExitCode is the exit this process leaves with: the server's exit_code bounded by ProcessExitCode, or 1 when it sent none.

func (*RemoteCommandError) LocalSignalAccount added in v1.20.0

func (e *RemoteCommandError) LocalSignalAccount() string

type ScriptBodySuggestion added in v1.20.0

type ScriptBodySuggestion struct {
	Signal string `json:"signal"`
}

ScriptBodySuggestion is the server's signal that a held command line carries a script body (a multi-line inline program, a heredoc, or an encoded body decoded into an interpreter) that could run as a verified file instead. Signal names what the server detected; the server proposes no path or interpreter.

type SubmissionObserver added in v1.21.0

type SubmissionObserver interface {
	CommandSubmitted(commandID string)
}

type SudoListener added in v1.4.0

type SudoListener struct {
	// contains filtered or unexported fields
}

SudoListener listens for sudo MFA events on the event WebSocket and handles the browser-based MFA flow.

ac is shared with the terminal WebSocket goroutines, which is safe because http.Client is concurrency-safe and mfaMu serializes token refresh and grant verification, so only one MFA flow runs at a time.

Event channel tokens are single-use, so every dial provisions its own session and re-subscribes once connected.

func NewSudoListener added in v1.4.0

func NewSudoListener(ac *client.AlpaconClient, serverName, sessionID string) *SudoListener

NewSudoListener creates a SudoListener but does not connect yet. ac may be nil only for a test that never calls Start: MFA request frames are then dropped, but provisioning a session on the listen goroutine would dereference it.

func (*SudoListener) Err added in v1.11.2

func (sl *SudoListener) Err() error

Err returns the last reason the listener could not connect, so a caller that only sees WaitConnected time out can report that instead of a bare timeout.

func (SudoListener) Start added in v1.4.0

func (w SudoListener) Start()

Start reads events in a background goroutine, reconnecting automatically until Stop is called.

func (SudoListener) Stop added in v1.4.0

func (w SudoListener) Stop()

Stop shuts down the listener and closes the connection to unblock a pending ReadMessage. Safe to call from any goroutine.

func (SudoListener) WaitConnected added in v1.4.0

func (w SudoListener) WaitConnected(timeout time.Duration) bool

WaitConnected blocks until a dial has connected and its onConnected hook has returned, until timeout, or until shutdown; returns whether it connected. A hook with nothing to subscribe to still counts, so this promises no subscription.

type WaitOptions added in v1.9.2

type WaitOptions struct {
	// CatchUp may be nil for a type with no REST projection.
	CatchUp CatchUpFunc
	OK      []string
	Fail    []string
	Timeout time.Duration
}

WaitOptions carries everything type-specific about a wait. Keeping it injected is why this package needs no knowledge of any event type.

type Waiter added in v1.9.2

type Waiter struct {
	*Watcher
	// contains filtered or unexported fields
}

Waiter blocks until one event decides the wait, then returns it. Reconnects and session reprovisioning are inherited from Watcher.

func NewWaiter added in v1.9.2

func NewWaiter(ac *client.AlpaconClient, eventType EventType, targetID string, opts WaitOptions) *Waiter

NewWaiter constructs a Waiter without connecting. Call Wait.

func (*Waiter) CatchUpFailed added in v1.9.2

func (w *Waiter) CatchUpFailed() <-chan error

CatchUpFailed reports a catch-up that could not be read. Buffered at one: a caller that misses a notice loses nothing a later one does not also carry.

func (Waiter) Start added in v1.9.2

func (w Waiter) Start()

Start reads events in a background goroutine, reconnecting automatically until Stop is called.

func (Waiter) Stop added in v1.9.2

func (w Waiter) Stop()

Stop shuts down the listener and closes the connection to unblock a pending ReadMessage. Safe to call from any goroutine.

func (*Waiter) Wait added in v1.9.2

func (w *Waiter) Wait() ([]byte, Outcome, error)

Wait blocks until an event matches, the timeout elapses, or Stop is called. The returned frame is the server's bytes verbatim, except on a catch-up hit where it is synthesized. A non-nil error means the wait could not run; Outcome is meaningless then.

Wait returns only once the listener and any catch-up read have stopped (see Close).

func (Waiter) WaitConnected added in v1.9.2

func (w Waiter) WaitConnected(timeout time.Duration) bool

WaitConnected blocks until a dial has connected and its onConnected hook has returned, until timeout, or until shutdown; returns whether it connected. A hook with nothing to subscribe to still counts, so this promises no subscription.

type Watcher added in v1.9.2

type Watcher struct {
	// contains filtered or unexported fields
}

Watcher streams raw event frames for one event type. Event channel tokens are single-use, so every dial attempt provisions its own session and re-subscribes once connected. When WaitConnected returns false, Err holds the reason if it was fatal.

func NewWatcher added in v1.9.2

func NewWatcher(ac *client.AlpaconClient, eventType EventType, targetID string) *Watcher

func (*Watcher) Close added in v1.20.0

func (w *Watcher) Close()

Close stops the Watcher and waits for its listener to end, its own requests and dial included. A best-effort close of a session whose dial failed may still be in flight, bounded by eventSessionCloseTimeout. Call it only after Start, and never from a callback the listener runs.

func (*Watcher) Err added in v1.9.2

func (w *Watcher) Err() error

Err returns the error that stopped the Watcher before it ever subscribed.

func (*Watcher) Frames added in v1.9.2

func (w *Watcher) Frames() <-chan []byte

func (*Watcher) ReconnectFailed added in v1.9.2

func (w *Watcher) ReconnectFailed() <-chan error

ReconnectFailed reports the first failure of each outage, so a stream whose reconnects keep failing is distinguishable from a quiet one.

func (*Watcher) Reconnected added in v1.9.2

func (w *Watcher) Reconnected() <-chan struct{}

Reconnected fires on each re-subscribe. Events published while disconnected are lost for good: the event channel has no history to replay.

func (Watcher) Start added in v1.9.2

func (w Watcher) Start()

Start reads events in a background goroutine, reconnecting automatically until Stop is called.

func (Watcher) Stop added in v1.9.2

func (w Watcher) Stop()

Stop shuts down the listener and closes the connection to unblock a pending ReadMessage. Safe to call from any goroutine.

func (Watcher) WaitConnected added in v1.9.2

func (w Watcher) WaitConnected(timeout time.Duration) bool

WaitConnected blocks until a dial has connected and its onConnected hook has returned, until timeout, or until shutdown; returns whether it connected. A hook with nothing to subscribe to still counts, so this promises no subscription.

Jump to

Keyboard shortcuts

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