Documentation
¶
Overview ¶
Package command defines the Command domain entity for server-controlled agents.
Index ¶
- Constants
- type Command
- func (c *Command) Acknowledge()
- func (c *Command) AssignToPlatformAgent(agentID shared.ID)
- func (c *Command) CanAcceptIngest(agentID shared.ID, token string) bool
- func (c *Command) CanBeAcknowledged() bool
- func (c *Command) CanRetry(maxRetries int) bool
- func (c *Command) Cancel()
- func (c *Command) ClearAuthToken()
- func (c *Command) Complete(result json.RawMessage)
- func (c *Command) Expire()
- func (c *Command) Fail(errorMessage string)
- func (c *Command) GenerateAuthToken(ttl time.Duration) (string, error)
- func (c *Command) IsAuthTokenValid() bool
- func (c *Command) IsDispatchedToPlatformAgent() bool
- func (c *Command) IsExpired() bool
- func (c *Command) IsPending() bool
- func (c *Command) IsQueued() bool
- func (c *Command) ReturnToQueue()
- func (c *Command) SetAgentID(agentID shared.ID)
- func (c *Command) SetExpiration(expiresAt time.Time)
- func (c *Command) SetPlatformJob(queuePriority int)
- func (c *Command) SetStepRunID(stepRunID shared.ID)
- func (c *Command) Start()
- func (c *Command) UpdateQueuePriority(newPriority int)
- func (c *Command) VerifyAuthToken(token string) bool
- type CommandPriority
- type CommandStats
- type CommandStatus
- type CommandType
- type Filter
- type QueuePosition
- type Repository
Constants ¶
const ( // AuthTokenLength is the length of generated auth tokens (32 bytes = 64 hex chars) AuthTokenLength = 32 // AuthTokenPrefix is the prefix for auth tokens AuthTokenPrefix = "oc-cmd-" // DefaultAuthTokenTTL is the default time-to-live for auth tokens (24 hours) DefaultAuthTokenTTL = 24 * time.Hour // DefaultCommandTTL is the expiry every command gets unless the caller asks // for a different one. It is a BACKSTOP, not a scheduling knob: it exists so // a command that nothing ever answers eventually reaches // ExpirationChecker -> pipeline.OnStepFailed("COMMAND_EXPIRED") instead of // leaving the owning run waiting forever. // // Every command used to be created with expires_at NULL, and both consumers // of the column require `expires_at IS NOT NULL` — so FindExpired matched // zero rows in every deployment and the checker had never expired anything. // // 48h is deliberately chosen to sit BEYOND every other timeout in the // command path, so those fire first and this one only catches what they miss: // // 10m JobRecoveryController.TenantStuckThresholdMinutes // 30m JobRecoveryController.StuckThresholdMinutes (platform jobs) // 60m ExpirationChecker.MaxQueueMinutes (platform job stuck in queue) // 1h scan.DefaultScanTimeoutSeconds -> ScanTimeoutController // 24h scan.MaxScanTimeoutSeconds (the longest a scan may legitimately run) // 24h DefaultAuthTokenTTL (past this a platform job cannot authenticate, // so it can no longer be executed even if an agent picked it up) // // A shorter TTL would start expiring healthy in-flight work, which is worse // than the inertness this replaces. Note also that FindExpired only matches // status IN ('pending','acknowledged') — a command that is actually // 'running' is never expired by this path however long it runs. DefaultCommandTTL = 48 * time.Hour )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Command ¶
type Command struct {
ID shared.ID
TenantID shared.ID
AgentID *shared.ID // Target agent (nil = any agent can pick up)
Type CommandType
Priority CommandPriority
Payload json.RawMessage
Status CommandStatus
ErrorMessage string
// Timing
CreatedAt time.Time
ExpiresAt *time.Time
AcknowledgedAt *time.Time
StartedAt *time.Time
CompletedAt *time.Time
// Result
Result json.RawMessage
// Scheduling
ScheduledAt *time.Time
ScheduleID *shared.ID
// Pipeline tracking
StepRunID *shared.ID // Reference to pipeline step run (for progression tracking)
// IsPlatformJob indicates this job runs on a platform agent (not tenant's own agent)
IsPlatformJob bool
// PlatformAgentID is the platform agent assigned to execute this job (auto-selected)
PlatformAgentID *shared.ID
// AuthTokenHash is the SHA256 hash of the auth token (for verification)
AuthTokenHash string
// AuthTokenPrefix is the first 8 characters of the token (for logging/debugging)
AuthTokenPrefix string
// AuthTokenExpiresAt is when the auth token expires (typically 24h after creation)
AuthTokenExpiresAt *time.Time
// QueuePriority is the calculated priority score (plan_base + age_bonus)
// Higher value = processed first
QueuePriority int
// QueuedAt is when the job was added to the platform queue
QueuedAt *time.Time
// DispatchAttempts tracks how many times dispatch was attempted
DispatchAttempts int
// LastDispatchAt is the last time dispatch was attempted
LastDispatchAt *time.Time
}
Command represents a command to be executed by an agent.
func NewCommand ¶
func NewCommand(tenantID shared.ID, cmdType CommandType, priority CommandPriority, payload json.RawMessage) (*Command, error)
NewCommand creates a new Command entity.
The expiry default is applied here rather than at the call sites because this constructor is the single seam every command creation goes through (scan/trigger, scan/coverage dispatch, pipeline/run, validation/dispatcher and the command service). Setting it per-site is what left expires_at NULL everywhere. Callers that need a different deadline override it afterwards with SetExpiration.
func (*Command) Acknowledge ¶
func (c *Command) Acknowledge()
Acknowledge marks the command as acknowledged.
func (*Command) AssignToPlatformAgent ¶
AssignToPlatformAgent assigns this job to a specific platform agent.
func (*Command) CanAcceptIngest ¶
CanAcceptIngest checks if this command can accept ingest data from a platform agent. The command must be running, have a valid token, and match the agent.
func (*Command) CanBeAcknowledged ¶
CanBeAcknowledged checks if the command can be acknowledged.
func (*Command) ClearAuthToken ¶
func (c *Command) ClearAuthToken()
ClearAuthToken clears the auth token (call after command completes).
func (*Command) Complete ¶
func (c *Command) Complete(result json.RawMessage)
Complete marks the command as completed.
func (*Command) GenerateAuthToken ¶
GenerateAuthToken generates a new auth token for this command. Returns the raw token (to be sent to agent) and sets the hash on the command. The raw token should only be transmitted once and never stored.
func (*Command) IsAuthTokenValid ¶
IsAuthTokenValid checks if the auth token is still valid (not expired).
func (*Command) IsDispatchedToPlatformAgent ¶
IsDispatchedToPlatformAgent checks if this job has been dispatched to a platform agent.
func (*Command) ReturnToQueue ¶
func (c *Command) ReturnToQueue()
ReturnToQueue returns the job to the queue (e.g., if agent went offline).
func (*Command) SetAgentID ¶
SetAgentID sets the target agent ID.
func (*Command) SetExpiration ¶
SetExpiration sets the expiration time.
func (*Command) SetPlatformJob ¶
SetPlatformJob marks this command as a platform job and enqueues it.
func (*Command) SetStepRunID ¶
SetStepRunID sets the pipeline step run ID for tracking.
func (*Command) UpdateQueuePriority ¶
UpdateQueuePriority updates the queue priority (called by scheduler).
func (*Command) VerifyAuthToken ¶
VerifyAuthToken verifies if the provided token matches this command's token. Uses constant-time comparison to prevent timing attacks.
type CommandPriority ¶
type CommandPriority string
CommandPriority represents the priority of a command.
const ( CommandPriorityLow CommandPriority = "low" CommandPriorityNormal CommandPriority = "normal" CommandPriorityHigh CommandPriority = "high" CommandPriorityCritical CommandPriority = "critical" )
type CommandStats ¶
type CommandStats struct {
Total int64
Pending int64
Running int64
Completed int64
Failed int64
Canceled int64
}
CommandStats represents aggregated command statistics.
type CommandStatus ¶
type CommandStatus string
CommandStatus represents the status of a command.
const ( CommandStatusPending CommandStatus = "pending" CommandStatusAcknowledged CommandStatus = "acknowledged" CommandStatusRunning CommandStatus = "running" CommandStatusCompleted CommandStatus = "completed" CommandStatusFailed CommandStatus = "failed" CommandStatusCanceled CommandStatus = "canceled" CommandStatusExpired CommandStatus = "expired" )
type CommandType ¶
type CommandType string
CommandType represents the type of command.
const ( CommandTypeScan CommandType = "scan" CommandTypeCollect CommandType = "collect" CommandTypeHealthCheck CommandType = "health_check" CommandTypeConfigUpdate CommandType = "config_update" CommandTypeCancel CommandType = "cancel" // CommandTypeValidate is a CTEM Stage-4 validation job: an agent re-checks a // finding (safe-check / nuclei / adversary emulation) and reports an outcome // that is mapped back into validation evidence on completion. CommandTypeValidate CommandType = "validate" )
type Filter ¶
type Filter struct {
TenantID *shared.ID
AgentID *shared.ID
Type *CommandType
Status *CommandStatus
Priority *CommandPriority
IsPlatformJob *bool // Filter by platform job status (v3.2)
PlatformAgentID *shared.ID // Filter by assigned platform agent (v3.2)
}
Filter represents filter options for listing commands.
type QueuePosition ¶
type QueuePosition struct {
Position int `json:"position"` // Position in queue (1-based)
TotalQueued int `json:"total_queued"` // Total jobs in queue
Priority int `json:"priority"` // Current priority score
EstimatedWait time.Duration `json:"estimated_wait"` // Estimated wait time
}
QueuePosition represents a position in the platform job queue.
func (*QueuePosition) EstimateWaitTime ¶
func (q *QueuePosition) EstimateWaitTime(avgJobDuration time.Duration, availableAgents int) time.Duration
EstimateWaitTime estimates the wait time based on position and historical data.
type Repository ¶
type Repository interface {
// Create creates a new command.
Create(ctx context.Context, cmd *Command) error
// GetByID retrieves a command by ID.
GetByID(ctx context.Context, id shared.ID) (*Command, error)
// GetByTenantAndID retrieves a command by tenant and ID.
GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Command, error)
// GetPendingForAgent retrieves pending commands for an agent.
//
// capabilities is the polling agent's advertised capability set. A command
// whose payload carries a non-empty required_capabilities array is only
// returned when every required capability is present in capabilities, so a
// capability-scoped command (e.g. a "validate:nuclei" validate job) is never
// handed to an agent that cannot execute it. A command with no
// required_capabilities is returned to any agent (unchanged behavior). Pass
// nil/empty capabilities to only receive unscoped commands.
GetPendingForAgent(ctx context.Context, tenantID shared.ID, agentID *shared.ID, capabilities []string, limit int) ([]*Command, error)
// ClaimForAgent atomically transitions a still-pending command to
// acknowledged for the given agent, only if it is still pending and
// either unassigned or already assigned to this agent. Returns false if
// another concurrent poller already claimed it — this is what prevents
// the same unassigned command being double-dispatched to two agents.
ClaimForAgent(ctx context.Context, tenantID, commandID shared.ID, agentID string) (bool, error)
// List lists commands with filters and pagination.
List(ctx context.Context, filter Filter, page pagination.Pagination) (pagination.Result[*Command], error)
// Update updates a command.
Update(ctx context.Context, cmd *Command) error
// Delete deletes a command.
Delete(ctx context.Context, id shared.ID) error
// FindExpired finds commands that have expired but not yet marked as expired.
// This is the ONLY expiry path. A second reaper (ExpireOldCommands, a raw
// `UPDATE commands SET status='expired'`) used to sit alongside it and won
// the race often enough that FindExpired no longer matched the row — so the
// command died and the owning pipeline run was never told. It was removed
// from JobRecoveryController for that reason and has been deleted outright;
// do not reintroduce an expiry that does not go through ExpirationChecker,
// which calls pipeline.OnStepFailed.
FindExpired(ctx context.Context) ([]*Command, error)
// GetByAuthTokenHash retrieves a command by auth token hash.
GetByAuthTokenHash(ctx context.Context, hash string) (*Command, error)
// CountActivePlatformJobsByTenant counts active platform jobs for a tenant.
// Active = pending, acknowledged, or running.
CountActivePlatformJobsByTenant(ctx context.Context, tenantID shared.ID) (int, error)
// CountQueuedPlatformJobsByTenant counts queued (pending, not dispatched) platform jobs for a tenant.
CountQueuedPlatformJobsByTenant(ctx context.Context, tenantID shared.ID) (int, error)
// CountQueuedPlatformJobs counts all queued platform jobs across all tenants.
CountQueuedPlatformJobs(ctx context.Context) (int, error)
// GetQueuedPlatformJobs retrieves queued platform jobs ordered by priority.
// Returns jobs that are pending and not yet assigned to an agent.
GetQueuedPlatformJobs(ctx context.Context, limit int) ([]*Command, error)
// GetNextPlatformJob atomically claims the next job from the queue for an agent.
// Uses FOR UPDATE SKIP LOCKED for concurrent safety.
// Returns nil if no suitable job is available.
GetNextPlatformJob(ctx context.Context, agentID shared.ID, capabilities []string, tools []string) (*Command, error)
// UpdateQueuePriorities recalculates queue priorities for all pending platform jobs.
// Returns the number of jobs updated.
UpdateQueuePriorities(ctx context.Context) (int64, error)
// RecoverStuckJobs returns stuck jobs to the queue.
// A job is stuck if it's assigned but the agent is offline or hasn't progressed.
// Returns the number of jobs recovered.
RecoverStuckJobs(ctx context.Context, stuckThresholdMinutes int, maxRetries int) (int64, error)
// FindQueueExpiredPlatformJobs returns platform jobs that have waited in the
// queue longer than maxQueueMinutes.
//
// It returns the jobs rather than expiring them: the caller must expire each
// one *and* notify the owning pipeline run, otherwise the run waits on a
// step that is already dead. A raw UPDATE here is what left scans hanging
// until an unrelated timeout controller reported a generic failure.
FindQueueExpiredPlatformJobs(ctx context.Context, maxQueueMinutes int) ([]*Command, error)
// GetQueuePosition gets the queue position for a specific command.
GetQueuePosition(ctx context.Context, commandID shared.ID) (*QueuePosition, error)
// ListPlatformJobsByTenant lists platform jobs for a tenant.
ListPlatformJobsByTenant(ctx context.Context, tenantID shared.ID, page pagination.Pagination) (pagination.Result[*Command], error)
// ListPlatformJobsAdmin lists platform jobs across all tenants (admin only).
// Optional filters: agentID, tenantID, status.
ListPlatformJobsAdmin(ctx context.Context, agentID, tenantID *shared.ID, status *CommandStatus, page pagination.Pagination) (pagination.Result[*Command], error)
// GetPlatformJobsByAgent lists platform jobs assigned to an agent.
GetPlatformJobsByAgent(ctx context.Context, agentID shared.ID, status *CommandStatus) ([]*Command, error)
// RecoverStuckTenantCommands returns stuck tenant commands to the pool.
// A command is stuck if it's assigned to an offline agent or hasn't been picked up.
// Returns the number of commands recovered.
RecoverStuckTenantCommands(ctx context.Context, stuckThresholdMinutes int, maxRetries int) (int64, error)
// FailExhaustedCommands marks commands that exceeded max retries as failed.
// Returns the number of commands failed.
FailExhaustedCommands(ctx context.Context, maxRetries int) (int64, error)
// GetStatsByTenant returns aggregated command statistics for a tenant in a single query.
// This is optimized to avoid N queries when fetching stats.
GetStatsByTenant(ctx context.Context, tenantID shared.ID) (CommandStats, error)
// CancelByPipelineRunID marks all non-terminal commands for a pipeline run as canceled.
// Used when a scan is cancelled by the user to abort in-flight commands.
// Returns the number of commands canceled.
CancelByPipelineRunID(ctx context.Context, tenantID shared.ID, runID shared.ID) (int64, error)
}
Repository defines the interface for command persistence.