fix: Complete AgentHealth improvements and build fixes
- Update Update scanner default from 15min to 12 hours (backend) - Add 1 week and 2 week frequency options (frontend) - Rename AgentScanners to AgentHealth component - Add OS-aware package manager badges (APT, DNF, Windows/Winget, Docker) - Fix all build errors (types, imports, storage metrics) - Add useMemo optimization for enabled/auto-run counts
This commit is contained in:
@@ -19,6 +19,7 @@ import (
|
|||||||
"github.com/Fimeg/RedFlag/aggregator-agent/internal/acknowledgment"
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/acknowledgment"
|
||||||
"github.com/Fimeg/RedFlag/aggregator-agent/internal/client"
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/client"
|
||||||
"github.com/Fimeg/RedFlag/aggregator-agent/internal/config"
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/config"
|
||||||
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/models"
|
||||||
"github.com/Fimeg/RedFlag/aggregator-agent/internal/orchestrator"
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/orchestrator"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -223,13 +224,13 @@ func handleScanSystem(apiClient *client.Client, cfg *config.Config, ackTracker *
|
|||||||
metricItems := make([]client.MetricsReportItem, 0, len(metrics))
|
metricItems := make([]client.MetricsReportItem, 0, len(metrics))
|
||||||
for _, metric := range metrics {
|
for _, metric := range metrics {
|
||||||
item := client.MetricsReportItem{
|
item := client.MetricsReportItem{
|
||||||
PackageType: "system",
|
PackageType: "system",
|
||||||
PackageName: metric.MetricName,
|
PackageName: metric.MetricName,
|
||||||
CurrentVersion: metric.CurrentValue,
|
CurrentVersion: metric.CurrentValue,
|
||||||
AvailableVersion: metric.AvailableValue,
|
AvailableVersion: metric.AvailableValue,
|
||||||
Severity: metric.Severity,
|
Severity: metric.Severity,
|
||||||
RepositorySource: metric.MetricType,
|
RepositorySource: metric.MetricType,
|
||||||
Metadata: metric.Metadata,
|
Metadata: metric.Metadata,
|
||||||
}
|
}
|
||||||
metricItems = append(metricItems, item)
|
metricItems = append(metricItems, item)
|
||||||
}
|
}
|
||||||
@@ -311,13 +312,13 @@ func handleScanDocker(apiClient *client.Client, cfg *config.Config, ackTracker *
|
|||||||
imageItems := make([]client.DockerReportItem, 0, len(images))
|
imageItems := make([]client.DockerReportItem, 0, len(images))
|
||||||
for _, image := range images {
|
for _, image := range images {
|
||||||
item := client.DockerReportItem{
|
item := client.DockerReportItem{
|
||||||
PackageType: "docker_image",
|
PackageType: "docker_image",
|
||||||
PackageName: image.ImageName,
|
PackageName: image.ImageName,
|
||||||
CurrentVersion: image.ImageID,
|
CurrentVersion: image.ImageID,
|
||||||
AvailableVersion: image.LatestImageID,
|
AvailableVersion: image.LatestImageID,
|
||||||
Severity: image.Severity,
|
Severity: image.Severity,
|
||||||
RepositorySource: image.RepositorySource,
|
RepositorySource: image.RepositorySource,
|
||||||
Metadata: image.Metadata,
|
Metadata: image.Metadata,
|
||||||
}
|
}
|
||||||
imageItems = append(imageItems, item)
|
imageItems = append(imageItems, item)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,14 +20,14 @@ import (
|
|||||||
|
|
||||||
// Client handles API communication with the server
|
// Client handles API communication with the server
|
||||||
type Client struct {
|
type Client struct {
|
||||||
baseURL string
|
baseURL string
|
||||||
token string
|
token string
|
||||||
http *http.Client
|
http *http.Client
|
||||||
RapidPollingEnabled bool
|
RapidPollingEnabled bool
|
||||||
RapidPollingUntil time.Time
|
RapidPollingUntil time.Time
|
||||||
machineID string // Cached machine ID for security binding
|
machineID string // Cached machine ID for security binding
|
||||||
eventBuffer *event.Buffer
|
eventBuffer *event.Buffer
|
||||||
agentID uuid.UUID
|
agentID uuid.UUID
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient creates a new API client
|
// NewClient creates a new API client
|
||||||
@@ -54,13 +54,13 @@ func NewClient(baseURL, token string) *Client {
|
|||||||
func NewClientWithEventBuffer(baseURL, token string, statePath string, agentID uuid.UUID) *Client {
|
func NewClientWithEventBuffer(baseURL, token string, statePath string, agentID uuid.UUID) *Client {
|
||||||
client := NewClient(baseURL, token)
|
client := NewClient(baseURL, token)
|
||||||
client.agentID = agentID
|
client.agentID = agentID
|
||||||
|
|
||||||
// Initialize event buffer if state path is provided
|
// Initialize event buffer if state path is provided
|
||||||
if statePath != "" {
|
if statePath != "" {
|
||||||
eventBufferPath := filepath.Join(statePath, "events_buffer.json")
|
eventBufferPath := filepath.Join(statePath, "events_buffer.json")
|
||||||
client.eventBuffer = event.NewBuffer(eventBufferPath)
|
client.eventBuffer = event.NewBuffer(eventBufferPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,22 +121,22 @@ func (c *Client) SetToken(token string) {
|
|||||||
|
|
||||||
// RegisterRequest is the payload for agent registration
|
// RegisterRequest is the payload for agent registration
|
||||||
type RegisterRequest struct {
|
type RegisterRequest struct {
|
||||||
Hostname string `json:"hostname"`
|
Hostname string `json:"hostname"`
|
||||||
OSType string `json:"os_type"`
|
OSType string `json:"os_type"`
|
||||||
OSVersion string `json:"os_version"`
|
OSVersion string `json:"os_version"`
|
||||||
OSArchitecture string `json:"os_architecture"`
|
OSArchitecture string `json:"os_architecture"`
|
||||||
AgentVersion string `json:"agent_version"`
|
AgentVersion string `json:"agent_version"`
|
||||||
RegistrationToken string `json:"registration_token,omitempty"` // Fallback method
|
RegistrationToken string `json:"registration_token,omitempty"` // Fallback method
|
||||||
MachineID string `json:"machine_id"`
|
MachineID string `json:"machine_id"`
|
||||||
PublicKeyFingerprint string `json:"public_key_fingerprint"`
|
PublicKeyFingerprint string `json:"public_key_fingerprint"`
|
||||||
Metadata map[string]string `json:"metadata"`
|
Metadata map[string]string `json:"metadata"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterResponse is returned after successful registration
|
// RegisterResponse is returned after successful registration
|
||||||
type RegisterResponse struct {
|
type RegisterResponse struct {
|
||||||
AgentID uuid.UUID `json:"agent_id"`
|
AgentID uuid.UUID `json:"agent_id"`
|
||||||
Token string `json:"token"` // Short-lived access token (24h)
|
Token string `json:"token"` // Short-lived access token (24h)
|
||||||
RefreshToken string `json:"refresh_token"` // Long-lived refresh token (90d)
|
RefreshToken string `json:"refresh_token"` // Long-lived refresh token (90d)
|
||||||
Config map[string]interface{} `json:"config"`
|
Config map[string]interface{} `json:"config"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +156,7 @@ func (c *Client) Register(req RegisterRequest) (*RegisterResponse, error) {
|
|||||||
c.bufferEvent("registration_failure", "marshal_error", "error", "client",
|
c.bufferEvent("registration_failure", "marshal_error", "error", "client",
|
||||||
fmt.Sprintf("Failed to marshal registration request: %v", err),
|
fmt.Sprintf("Failed to marshal registration request: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"hostname": req.Hostname,
|
"hostname": req.Hostname,
|
||||||
})
|
})
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -168,7 +168,7 @@ func (c *Client) Register(req RegisterRequest) (*RegisterResponse, error) {
|
|||||||
c.bufferEvent("registration_failure", "request_creation_error", "error", "client",
|
c.bufferEvent("registration_failure", "request_creation_error", "error", "client",
|
||||||
fmt.Sprintf("Failed to create registration request: %v", err),
|
fmt.Sprintf("Failed to create registration request: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"hostname": req.Hostname,
|
"hostname": req.Hostname,
|
||||||
})
|
})
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -187,8 +187,8 @@ func (c *Client) Register(req RegisterRequest) (*RegisterResponse, error) {
|
|||||||
c.bufferEvent("registration_failure", "network_error", "error", "client",
|
c.bufferEvent("registration_failure", "network_error", "error", "client",
|
||||||
fmt.Sprintf("Registration request failed: %v", err),
|
fmt.Sprintf("Registration request failed: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"hostname": req.Hostname,
|
"hostname": req.Hostname,
|
||||||
"server_url": c.baseURL,
|
"server_url": c.baseURL,
|
||||||
})
|
})
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -198,15 +198,15 @@ func (c *Client) Register(req RegisterRequest) (*RegisterResponse, error) {
|
|||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||||
errorMsg := fmt.Sprintf("registration failed: %s - %s", resp.Status, string(bodyBytes))
|
errorMsg := fmt.Sprintf("registration failed: %s - %s", resp.Status, string(bodyBytes))
|
||||||
|
|
||||||
// Buffer registration failure event
|
// Buffer registration failure event
|
||||||
c.bufferEvent("registration_failure", "api_error", "error", "client",
|
c.bufferEvent("registration_failure", "api_error", "error", "client",
|
||||||
errorMsg,
|
errorMsg,
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"status_code": resp.StatusCode,
|
"status_code": resp.StatusCode,
|
||||||
"response_body": string(bodyBytes),
|
"response_body": string(bodyBytes),
|
||||||
"hostname": req.Hostname,
|
"hostname": req.Hostname,
|
||||||
"server_url": c.baseURL,
|
"server_url": c.baseURL,
|
||||||
})
|
})
|
||||||
return nil, fmt.Errorf(errorMsg)
|
return nil, fmt.Errorf(errorMsg)
|
||||||
}
|
}
|
||||||
@@ -217,7 +217,7 @@ func (c *Client) Register(req RegisterRequest) (*RegisterResponse, error) {
|
|||||||
c.bufferEvent("registration_failure", "decode_error", "error", "client",
|
c.bufferEvent("registration_failure", "decode_error", "error", "client",
|
||||||
fmt.Sprintf("Failed to decode registration response: %v", err),
|
fmt.Sprintf("Failed to decode registration response: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"hostname": req.Hostname,
|
"hostname": req.Hostname,
|
||||||
})
|
})
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -239,7 +239,7 @@ type TokenRenewalRequest struct {
|
|||||||
|
|
||||||
// TokenRenewalResponse is returned after successful token renewal
|
// TokenRenewalResponse is returned after successful token renewal
|
||||||
type TokenRenewalResponse struct {
|
type TokenRenewalResponse struct {
|
||||||
Token string `json:"token"` // New short-lived access token (24h)
|
Token string `json:"token"` // New short-lived access token (24h)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RenewToken uses refresh token to get a new access token (proper implementation)
|
// RenewToken uses refresh token to get a new access token (proper implementation)
|
||||||
@@ -258,7 +258,7 @@ func (c *Client) RenewToken(agentID uuid.UUID, refreshToken string, agentVersion
|
|||||||
c.bufferEvent("token_renewal_failure", "marshal_error", "error", "client",
|
c.bufferEvent("token_renewal_failure", "marshal_error", "error", "client",
|
||||||
fmt.Sprintf("Failed to marshal token renewal request: %v", err),
|
fmt.Sprintf("Failed to marshal token renewal request: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"agent_id": agentID.String(),
|
"agent_id": agentID.String(),
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
@@ -270,7 +270,7 @@ func (c *Client) RenewToken(agentID uuid.UUID, refreshToken string, agentVersion
|
|||||||
c.bufferEvent("token_renewal_failure", "request_creation_error", "error", "client",
|
c.bufferEvent("token_renewal_failure", "request_creation_error", "error", "client",
|
||||||
fmt.Sprintf("Failed to create token renewal request: %v", err),
|
fmt.Sprintf("Failed to create token renewal request: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"agent_id": agentID.String(),
|
"agent_id": agentID.String(),
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
@@ -283,8 +283,8 @@ func (c *Client) RenewToken(agentID uuid.UUID, refreshToken string, agentVersion
|
|||||||
c.bufferEvent("token_renewal_failure", "network_error", "error", "client",
|
c.bufferEvent("token_renewal_failure", "network_error", "error", "client",
|
||||||
fmt.Sprintf("Token renewal request failed: %v", err),
|
fmt.Sprintf("Token renewal request failed: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"agent_id": agentID.String(),
|
"agent_id": agentID.String(),
|
||||||
"server_url": c.baseURL,
|
"server_url": c.baseURL,
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
@@ -294,15 +294,15 @@ func (c *Client) RenewToken(agentID uuid.UUID, refreshToken string, agentVersion
|
|||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||||
errorMsg := fmt.Sprintf("token renewal failed: %s - %s", resp.Status, string(bodyBytes))
|
errorMsg := fmt.Sprintf("token renewal failed: %s - %s", resp.Status, string(bodyBytes))
|
||||||
|
|
||||||
// Buffer token renewal failure event
|
// Buffer token renewal failure event
|
||||||
c.bufferEvent("token_renewal_failure", "api_error", "error", "client",
|
c.bufferEvent("token_renewal_failure", "api_error", "error", "client",
|
||||||
errorMsg,
|
errorMsg,
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"status_code": resp.StatusCode,
|
"status_code": resp.StatusCode,
|
||||||
"response_body": string(bodyBytes),
|
"response_body": string(bodyBytes),
|
||||||
"agent_id": agentID.String(),
|
"agent_id": agentID.String(),
|
||||||
"server_url": c.baseURL,
|
"server_url": c.baseURL,
|
||||||
})
|
})
|
||||||
return fmt.Errorf(errorMsg)
|
return fmt.Errorf(errorMsg)
|
||||||
}
|
}
|
||||||
@@ -313,7 +313,7 @@ func (c *Client) RenewToken(agentID uuid.UUID, refreshToken string, agentVersion
|
|||||||
c.bufferEvent("token_renewal_failure", "decode_error", "error", "client",
|
c.bufferEvent("token_renewal_failure", "decode_error", "error", "client",
|
||||||
fmt.Sprintf("Failed to decode token renewal response: %v", err),
|
fmt.Sprintf("Failed to decode token renewal response: %v", err),
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
"agent_id": agentID.String(),
|
"agent_id": agentID.String(),
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
@@ -327,10 +327,10 @@ func (c *Client) RenewToken(agentID uuid.UUID, refreshToken string, agentVersion
|
|||||||
|
|
||||||
// Command represents a command from the server
|
// Command represents a command from the server
|
||||||
type Command struct {
|
type Command struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Params map[string]interface{} `json:"params"`
|
Params map[string]interface{} `json:"params"`
|
||||||
Signature string `json:"signature,omitempty"` // Ed25519 signature of the command
|
Signature string `json:"signature,omitempty"` // Ed25519 signature of the command
|
||||||
}
|
}
|
||||||
|
|
||||||
// CommandItem is an alias for Command for consistency with server models
|
// CommandItem is an alias for Command for consistency with server models
|
||||||
@@ -338,9 +338,9 @@ type CommandItem = Command
|
|||||||
|
|
||||||
// CommandsResponse contains pending commands
|
// CommandsResponse contains pending commands
|
||||||
type CommandsResponse struct {
|
type CommandsResponse struct {
|
||||||
Commands []Command `json:"commands"`
|
Commands []Command `json:"commands"`
|
||||||
RapidPolling *RapidPollingConfig `json:"rapid_polling,omitempty"`
|
RapidPolling *RapidPollingConfig `json:"rapid_polling,omitempty"`
|
||||||
AcknowledgedIDs []string `json:"acknowledged_ids,omitempty"` // IDs server has received
|
AcknowledgedIDs []string `json:"acknowledged_ids,omitempty"` // IDs server has received
|
||||||
}
|
}
|
||||||
|
|
||||||
// RapidPollingConfig contains rapid polling configuration from server
|
// RapidPollingConfig contains rapid polling configuration from server
|
||||||
@@ -351,16 +351,16 @@ type RapidPollingConfig struct {
|
|||||||
|
|
||||||
// SystemMetrics represents lightweight system metrics sent with check-ins
|
// SystemMetrics represents lightweight system metrics sent with check-ins
|
||||||
type SystemMetrics struct {
|
type SystemMetrics struct {
|
||||||
CPUPercent float64 `json:"cpu_percent,omitempty"`
|
CPUPercent float64 `json:"cpu_percent,omitempty"`
|
||||||
MemoryPercent float64 `json:"memory_percent,omitempty"`
|
MemoryPercent float64 `json:"memory_percent,omitempty"`
|
||||||
MemoryUsedGB float64 `json:"memory_used_gb,omitempty"`
|
MemoryUsedGB float64 `json:"memory_used_gb,omitempty"`
|
||||||
MemoryTotalGB float64 `json:"memory_total_gb,omitempty"`
|
MemoryTotalGB float64 `json:"memory_total_gb,omitempty"`
|
||||||
DiskUsedGB float64 `json:"disk_used_gb,omitempty"`
|
DiskUsedGB float64 `json:"disk_used_gb,omitempty"`
|
||||||
DiskTotalGB float64 `json:"disk_total_gb,omitempty"`
|
DiskTotalGB float64 `json:"disk_total_gb,omitempty"`
|
||||||
DiskPercent float64 `json:"disk_percent,omitempty"`
|
DiskPercent float64 `json:"disk_percent,omitempty"`
|
||||||
Uptime string `json:"uptime,omitempty"`
|
Uptime string `json:"uptime,omitempty"`
|
||||||
Version string `json:"version,omitempty"` // Agent version
|
Version string `json:"version,omitempty"` // Agent version
|
||||||
Metadata map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
|
Metadata map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
|
||||||
|
|
||||||
// Command acknowledgment tracking
|
// Command acknowledgment tracking
|
||||||
PendingAcknowledgments []string `json:"pending_acknowledgments,omitempty"` // Command IDs awaiting ACK
|
PendingAcknowledgments []string `json:"pending_acknowledgments,omitempty"` // Command IDs awaiting ACK
|
||||||
@@ -427,9 +427,9 @@ func (c *Client) GetCommands(agentID uuid.UUID, metrics *SystemMetrics) (*Comman
|
|||||||
|
|
||||||
// UpdateReport represents discovered updates
|
// UpdateReport represents discovered updates
|
||||||
type UpdateReport struct {
|
type UpdateReport struct {
|
||||||
CommandID string `json:"command_id"`
|
CommandID string `json:"command_id"`
|
||||||
Timestamp time.Time `json:"timestamp"`
|
Timestamp time.Time `json:"timestamp"`
|
||||||
Updates []UpdateReportItem `json:"updates"`
|
Updates []UpdateReportItem `json:"updates"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateReportItem represents a single update
|
// UpdateReportItem represents a single update
|
||||||
@@ -480,20 +480,20 @@ func (c *Client) ReportUpdates(agentID uuid.UUID, report UpdateReport) error {
|
|||||||
|
|
||||||
// MetricsReport represents metrics data (storage, system, CPU, memory)
|
// MetricsReport represents metrics data (storage, system, CPU, memory)
|
||||||
type MetricsReport struct {
|
type MetricsReport struct {
|
||||||
CommandID string `json:"command_id"`
|
CommandID string `json:"command_id"`
|
||||||
Timestamp time.Time `json:"timestamp"`
|
Timestamp time.Time `json:"timestamp"`
|
||||||
Metrics []MetricsReportItem `json:"metrics"`
|
Metrics []MetricsReportItem `json:"metrics"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MetricsReportItem represents a single metric
|
// MetricsReportItem represents a single metric
|
||||||
type MetricsReportItem struct {
|
type MetricsReportItem struct {
|
||||||
PackageType string `json:"package_type"`
|
PackageType string `json:"package_type"`
|
||||||
PackageName string `json:"package_name"`
|
PackageName string `json:"package_name"`
|
||||||
CurrentVersion string `json:"current_version"`
|
CurrentVersion string `json:"current_version"`
|
||||||
AvailableVersion string `json:"available_version"`
|
AvailableVersion string `json:"available_version"`
|
||||||
Severity string `json:"severity"`
|
Severity string `json:"severity"`
|
||||||
RepositorySource string `json:"repository_source"`
|
RepositorySource string `json:"repository_source"`
|
||||||
Metadata map[string]interface{} `json:"metadata"`
|
Metadata map[string]interface{} `json:"metadata"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReportMetrics sends metrics data to the server
|
// ReportMetrics sends metrics data to the server
|
||||||
@@ -529,20 +529,20 @@ func (c *Client) ReportMetrics(agentID uuid.UUID, report MetricsReport) error {
|
|||||||
|
|
||||||
// DockerReport represents Docker image information
|
// DockerReport represents Docker image information
|
||||||
type DockerReport struct {
|
type DockerReport struct {
|
||||||
CommandID string `json:"command_id"`
|
CommandID string `json:"command_id"`
|
||||||
Timestamp time.Time `json:"timestamp"`
|
Timestamp time.Time `json:"timestamp"`
|
||||||
Images []DockerReportItem `json:"images"`
|
Images []DockerReportItem `json:"images"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DockerReportItem represents a single Docker image
|
// DockerReportItem represents a single Docker image
|
||||||
type DockerReportItem struct {
|
type DockerReportItem struct {
|
||||||
PackageType string `json:"package_type"`
|
PackageType string `json:"package_type"`
|
||||||
PackageName string `json:"package_name"`
|
PackageName string `json:"package_name"`
|
||||||
CurrentVersion string `json:"current_version"`
|
CurrentVersion string `json:"current_version"`
|
||||||
AvailableVersion string `json:"available_version"`
|
AvailableVersion string `json:"available_version"`
|
||||||
Severity string `json:"severity"`
|
Severity string `json:"severity"`
|
||||||
RepositorySource string `json:"repository_source"`
|
RepositorySource string `json:"repository_source"`
|
||||||
Metadata map[string]interface{} `json:"metadata"`
|
Metadata map[string]interface{} `json:"metadata"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReportDockerImages sends Docker image information to the server
|
// ReportDockerImages sends Docker image information to the server
|
||||||
@@ -577,7 +577,7 @@ func (c *Client) ReportDockerImages(agentID uuid.UUID, report DockerReport) erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ReportStorageMetrics sends storage metrics to the server via dedicated endpoint
|
// ReportStorageMetrics sends storage metrics to the server via dedicated endpoint
|
||||||
func (c *Client) ReportStorageMetrics(agentID uuid.UUID, report StorageMetricReport) error {
|
func (c *Client) ReportStorageMetrics(agentID uuid.UUID, report models.StorageMetricReport) error {
|
||||||
url := fmt.Sprintf("%s/api/v1/agents/%s/storage-metrics", c.baseURL, agentID)
|
url := fmt.Sprintf("%s/api/v1/agents/%s/storage-metrics", c.baseURL, agentID)
|
||||||
|
|
||||||
body, err := json.Marshal(report)
|
body, err := json.Marshal(report)
|
||||||
@@ -652,26 +652,26 @@ func (c *Client) ReportLog(agentID uuid.UUID, report LogReport) error {
|
|||||||
|
|
||||||
// DependencyReport represents a dependency report after dry run
|
// DependencyReport represents a dependency report after dry run
|
||||||
type DependencyReport struct {
|
type DependencyReport struct {
|
||||||
PackageName string `json:"package_name"`
|
PackageName string `json:"package_name"`
|
||||||
PackageType string `json:"package_type"`
|
PackageType string `json:"package_type"`
|
||||||
Dependencies []string `json:"dependencies"`
|
Dependencies []string `json:"dependencies"`
|
||||||
UpdateID string `json:"update_id"`
|
UpdateID string `json:"update_id"`
|
||||||
DryRunResult *InstallResult `json:"dry_run_result,omitempty"`
|
DryRunResult *InstallResult `json:"dry_run_result,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// InstallResult represents the result of a package installation attempt
|
// InstallResult represents the result of a package installation attempt
|
||||||
type InstallResult struct {
|
type InstallResult struct {
|
||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
ErrorMessage string `json:"error_message,omitempty"`
|
ErrorMessage string `json:"error_message,omitempty"`
|
||||||
Stdout string `json:"stdout,omitempty"`
|
Stdout string `json:"stdout,omitempty"`
|
||||||
Stderr string `json:"stderr,omitempty"`
|
Stderr string `json:"stderr,omitempty"`
|
||||||
ExitCode int `json:"exit_code"`
|
ExitCode int `json:"exit_code"`
|
||||||
DurationSeconds int `json:"duration_seconds"`
|
DurationSeconds int `json:"duration_seconds"`
|
||||||
Action string `json:"action,omitempty"`
|
Action string `json:"action,omitempty"`
|
||||||
PackagesInstalled []string `json:"packages_installed,omitempty"`
|
PackagesInstalled []string `json:"packages_installed,omitempty"`
|
||||||
ContainersUpdated []string `json:"containers_updated,omitempty"`
|
ContainersUpdated []string `json:"containers_updated,omitempty"`
|
||||||
Dependencies []string `json:"dependencies,omitempty"`
|
Dependencies []string `json:"dependencies,omitempty"`
|
||||||
IsDryRun bool `json:"is_dry_run"`
|
IsDryRun bool `json:"is_dry_run"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReportDependencies sends dependency report to the server
|
// ReportDependencies sends dependency report to the server
|
||||||
@@ -707,7 +707,7 @@ func (c *Client) ReportDependencies(agentID uuid.UUID, report DependencyReport)
|
|||||||
|
|
||||||
// SystemInfoReport represents system information updates
|
// SystemInfoReport represents system information updates
|
||||||
type SystemInfoReport struct {
|
type SystemInfoReport struct {
|
||||||
Timestamp time.Time `json:"timestamp"`
|
Timestamp time.Time `json:"timestamp"`
|
||||||
CPUModel string `json:"cpu_model,omitempty"`
|
CPUModel string `json:"cpu_model,omitempty"`
|
||||||
CPUCores int `json:"cpu_cores,omitempty"`
|
CPUCores int `json:"cpu_cores,omitempty"`
|
||||||
CPUThreads int `json:"cpu_threads,omitempty"`
|
CPUThreads int `json:"cpu_threads,omitempty"`
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ type SubsystemConfig struct {
|
|||||||
// Execution settings
|
// Execution settings
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
Timeout time.Duration `json:"timeout"` // Timeout for this subsystem
|
Timeout time.Duration `json:"timeout"` // Timeout for this subsystem
|
||||||
|
|
||||||
// Interval for this subsystem (in minutes)
|
// Interval for this subsystem (in minutes)
|
||||||
// This controls how often the server schedules scans for this subsystem
|
// This controls how often the server schedules scans for this subsystem
|
||||||
IntervalMinutes int `json:"interval_minutes,omitempty"`
|
IntervalMinutes int `json:"interval_minutes,omitempty"`
|
||||||
@@ -51,16 +51,16 @@ func GetDefaultSubsystemsConfig() SubsystemsConfig {
|
|||||||
// Default circuit breaker config
|
// Default circuit breaker config
|
||||||
defaultCB := CircuitBreakerConfig{
|
defaultCB := CircuitBreakerConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
FailureThreshold: 3, // 3 consecutive failures
|
FailureThreshold: 3, // 3 consecutive failures
|
||||||
FailureWindow: 10 * time.Minute, // within 10 minutes
|
FailureWindow: 10 * time.Minute, // within 10 minutes
|
||||||
OpenDuration: 30 * time.Minute, // circuit open for 30 min
|
OpenDuration: 30 * time.Minute, // circuit open for 30 min
|
||||||
HalfOpenAttempts: 2, // 2 successful attempts to close circuit
|
HalfOpenAttempts: 2, // 2 successful attempts to close circuit
|
||||||
}
|
}
|
||||||
|
|
||||||
// Aggressive circuit breaker for Windows Update (known to be slow/problematic)
|
// Aggressive circuit breaker for Windows Update (known to be slow/problematic)
|
||||||
windowsCB := CircuitBreakerConfig{
|
windowsCB := CircuitBreakerConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
FailureThreshold: 2, // Only 2 failures
|
FailureThreshold: 2, // Only 2 failures
|
||||||
FailureWindow: 15 * time.Minute,
|
FailureWindow: 15 * time.Minute,
|
||||||
OpenDuration: 60 * time.Minute, // Open for 1 hour
|
OpenDuration: 60 * time.Minute, // Open for 1 hour
|
||||||
HalfOpenAttempts: 3,
|
HalfOpenAttempts: 3,
|
||||||
@@ -68,15 +68,15 @@ func GetDefaultSubsystemsConfig() SubsystemsConfig {
|
|||||||
|
|
||||||
return SubsystemsConfig{
|
return SubsystemsConfig{
|
||||||
System: SubsystemConfig{
|
System: SubsystemConfig{
|
||||||
Enabled: true, // System scanner always available
|
Enabled: true, // System scanner always available
|
||||||
Timeout: 10 * time.Second, // System info should be fast
|
Timeout: 10 * time.Second, // System info should be fast
|
||||||
IntervalMinutes: 5, // Default: 5 minutes
|
IntervalMinutes: 5, // Default: 5 minutes
|
||||||
CircuitBreaker: defaultCB,
|
CircuitBreaker: defaultCB,
|
||||||
},
|
},
|
||||||
Updates: SubsystemConfig{
|
Updates: SubsystemConfig{
|
||||||
Enabled: true, // Virtual subsystem for package update scheduling
|
Enabled: true, // Virtual subsystem for package update scheduling
|
||||||
Timeout: 0, // Not used - delegates to individual package scanners
|
Timeout: 0, // Not used - delegates to individual package scanners
|
||||||
IntervalMinutes: 15, // Default: 15 minutes
|
IntervalMinutes: 720, // Default: 12 hours (more reasonable for update checks)
|
||||||
CircuitBreaker: CircuitBreakerConfig{Enabled: false}, // No circuit breaker for virtual subsystem
|
CircuitBreaker: CircuitBreakerConfig{Enabled: false}, // No circuit breaker for virtual subsystem
|
||||||
},
|
},
|
||||||
APT: SubsystemConfig{
|
APT: SubsystemConfig{
|
||||||
@@ -88,31 +88,31 @@ func GetDefaultSubsystemsConfig() SubsystemsConfig {
|
|||||||
DNF: SubsystemConfig{
|
DNF: SubsystemConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
Timeout: 15 * time.Minute, // TODO: Make scanner timeouts user-adjustable via settings. DNF operations can take a long time on large systems
|
Timeout: 15 * time.Minute, // TODO: Make scanner timeouts user-adjustable via settings. DNF operations can take a long time on large systems
|
||||||
IntervalMinutes: 15, // Default: 15 minutes
|
IntervalMinutes: 15, // Default: 15 minutes
|
||||||
CircuitBreaker: defaultCB,
|
CircuitBreaker: defaultCB,
|
||||||
},
|
},
|
||||||
Docker: SubsystemConfig{
|
Docker: SubsystemConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
Timeout: 60 * time.Second, // Registry queries can be slow
|
Timeout: 60 * time.Second, // Registry queries can be slow
|
||||||
IntervalMinutes: 15, // Default: 15 minutes
|
IntervalMinutes: 15, // Default: 15 minutes
|
||||||
CircuitBreaker: defaultCB,
|
CircuitBreaker: defaultCB,
|
||||||
},
|
},
|
||||||
Windows: SubsystemConfig{
|
Windows: SubsystemConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
Timeout: 10 * time.Minute, // Windows Update can be VERY slow
|
Timeout: 10 * time.Minute, // Windows Update can be VERY slow
|
||||||
IntervalMinutes: 15, // Default: 15 minutes
|
IntervalMinutes: 15, // Default: 15 minutes
|
||||||
CircuitBreaker: windowsCB,
|
CircuitBreaker: windowsCB,
|
||||||
},
|
},
|
||||||
Winget: SubsystemConfig{
|
Winget: SubsystemConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
Timeout: 2 * time.Minute, // Winget has multiple retry strategies
|
Timeout: 2 * time.Minute, // Winget has multiple retry strategies
|
||||||
IntervalMinutes: 15, // Default: 15 minutes
|
IntervalMinutes: 15, // Default: 15 minutes
|
||||||
CircuitBreaker: defaultCB,
|
CircuitBreaker: defaultCB,
|
||||||
},
|
},
|
||||||
Storage: SubsystemConfig{
|
Storage: SubsystemConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
Timeout: 10 * time.Second, // Disk info should be fast
|
Timeout: 10 * time.Second, // Disk info should be fast
|
||||||
IntervalMinutes: 5, // Default: 5 minutes
|
IntervalMinutes: 5, // Default: 5 minutes
|
||||||
CircuitBreaker: defaultCB,
|
CircuitBreaker: defaultCB,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Fimeg/RedFlag/aggregator-agent/internal/client"
|
|
||||||
"github.com/Fimeg/RedFlag/aggregator-agent/internal/system"
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/system"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"log"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Fimeg/RedFlag/aggregator-server/internal/database/queries"
|
"github.com/Fimeg/RedFlag/aggregator-server/internal/database/queries"
|
||||||
"github.com/Fimeg/RedFlag/aggregator-server/internal/models"
|
"github.com/Fimeg/RedFlag/aggregator-server/internal/models"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/gorilla/mux"
|
|
||||||
"github.com/lib/pq"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// StorageMetricsHandler handles storage metrics endpoints
|
// StorageMetricsHandler handles storage metrics endpoints
|
||||||
@@ -25,28 +23,21 @@ func NewStorageMetricsHandler(queries *queries.StorageMetricsQueries) *StorageMe
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReportStorageMetrics handles POST /api/v1/agents/{id}/storage-metrics
|
// ReportStorageMetrics handles POST /api/v1/agents/:id/storage-metrics
|
||||||
func (h *StorageMetricsHandler) ReportStorageMetrics(w http.ResponseWriter, r *http.Request) {
|
func (h *StorageMetricsHandler) ReportStorageMetrics(c *gin.Context) {
|
||||||
vars := mux.Vars(r)
|
// Get agent ID from context (set by middleware)
|
||||||
agentIDStr := vars["id"]
|
agentID := c.MustGet("agent_id").(uuid.UUID)
|
||||||
|
|
||||||
// Parse agent ID
|
|
||||||
agentID, err := uuid.Parse(agentIDStr)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid agent ID", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse request body
|
// Parse request body
|
||||||
var req models.StorageMetricRequest
|
var req models.StorageMetricRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate agent ID matches
|
// Validate agent ID matches
|
||||||
if req.AgentID != agentID {
|
if req.AgentID != agentID {
|
||||||
http.Error(w, "Agent ID mismatch", http.StatusBadRequest)
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Agent ID mismatch"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,58 +59,34 @@ func (h *StorageMetricsHandler) ReportStorageMetrics(w http.ResponseWriter, r *h
|
|||||||
CreatedAt: time.Now(),
|
CreatedAt: time.Now(),
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.queries.InsertStorageMetric(r.Context(), dbMetric); err != nil {
|
if err := h.queries.InsertStorageMetric(c.Request.Context(), dbMetric); err != nil {
|
||||||
log.Printf("[ERROR] Failed to insert storage metric for agent %s: %v\n", agentID, err)
|
log.Printf("[ERROR] Failed to insert storage metric for agent %s: %v\n", agentID, err)
|
||||||
http.Error(w, "Failed to insert storage metric", http.StatusInternalServerError)
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert storage metric"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
c.JSON(http.StatusOK, gin.H{
|
||||||
json.NewEncoder(w).Encode(map[string]string{
|
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"message": "Storage metrics reported successfully",
|
"message": "Storage metrics reported successfully",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetStorageMetrics handles GET /api/v1/agents/{id}/storage-metrics
|
// GetStorageMetrics handles GET /api/v1/agents/:id/storage-metrics
|
||||||
func (h *StorageMetricsHandler) GetStorageMetrics(w http.ResponseWriter, r *http.Request) {
|
func (h *StorageMetricsHandler) GetStorageMetrics(c *gin.Context) {
|
||||||
vars := mux.Vars(r)
|
// Get agent ID from context (set by middleware)
|
||||||
agentIDStr := vars["id"]
|
agentID := c.MustGet("agent_id").(uuid.UUID)
|
||||||
|
|
||||||
// Parse agent ID
|
|
||||||
agentID, err := uuid.Parse(agentIDStr)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid agent ID", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Optional query parameters for pagination/limit
|
|
||||||
limit := parseIntQueryParam(r, "limit", 100)
|
|
||||||
offset := parseIntQueryParam(r, "offset", 0)
|
|
||||||
|
|
||||||
// Get storage metrics
|
// Get storage metrics
|
||||||
metrics, err := h.queries.GetStorageMetricsByAgentID(r.Context(), agentID, limit, offset)
|
metrics, err := h.queries.GetStorageMetricsByAgentID(c.Request.Context(), agentID, 100, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[ERROR] Failed to retrieve storage metrics for agent %s: %v\n", agentID, err)
|
log.Printf("[ERROR] Failed to retrieve storage metrics for agent %s: %v\n", agentID, err)
|
||||||
http.Error(w, "Failed to retrieve storage metrics", http.StatusInternalServerError)
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve storage metrics"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
c.JSON(http.StatusOK, gin.H{
|
||||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
||||||
"metrics": metrics,
|
"metrics": metrics,
|
||||||
"total": len(metrics),
|
"total": len(metrics),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseIntQueryParam safely parses integer query parameters with defaults
|
|
||||||
func parseIntQueryParam(r *http.Request, key string, defaultValue int) int {
|
|
||||||
if val := r.URL.Query().Get(key); val != "" {
|
|
||||||
var result int
|
|
||||||
if _, err := fmt.Sscanf(val, "%d", &result); err == nil && result > 0 {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Fimeg/RedFlag/aggregator-server/internal/models"
|
"github.com/Fimeg/RedFlag/aggregator-server/internal/models"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -136,7 +135,7 @@ func (q *StorageMetricsQueries) GetLatestStorageMetrics(ctx context.Context, age
|
|||||||
// GetStorageMetricsSummary returns summary statistics for an agent
|
// GetStorageMetricsSummary returns summary statistics for an agent
|
||||||
func (q *StorageMetricsQueries) GetStorageMetricsSummary(ctx context.Context, agentID uuid.UUID) (map[string]interface{}, error) {
|
func (q *StorageMetricsQueries) GetStorageMetricsSummary(ctx context.Context, agentID uuid.UUID) (map[string]interface{}, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT
|
SELECT
|
||||||
COUNT(*) as total_disks,
|
COUNT(*) as total_disks,
|
||||||
COUNT(CASE WHEN severity = 'critical' THEN 1 END) as critical_disks,
|
COUNT(CASE WHEN severity = 'critical' THEN 1 END) as critical_disks,
|
||||||
COUNT(CASE WHEN severity = 'important' THEN 1 END) as important_disks,
|
COUNT(CASE WHEN severity = 'important' THEN 1 END) as important_disks,
|
||||||
@@ -149,19 +148,38 @@ func (q *StorageMetricsQueries) GetStorageMetricsSummary(ctx context.Context, ag
|
|||||||
AND created_at >= NOW() - INTERVAL '24 hours'
|
AND created_at >= NOW() - INTERVAL '24 hours'
|
||||||
`
|
`
|
||||||
|
|
||||||
var summary map[string]interface{}
|
var (
|
||||||
|
totalDisks int
|
||||||
|
criticalDisks int
|
||||||
|
importantDisks int
|
||||||
|
avgUsedPercent sql.NullFloat64
|
||||||
|
maxUsedPercent sql.NullFloat64
|
||||||
|
firstCollectedAt sql.NullTime
|
||||||
|
lastCollectedAt sql.NullTime
|
||||||
|
)
|
||||||
|
|
||||||
err := q.db.QueryRowContext(ctx, query, agentID).Scan(
|
err := q.db.QueryRowContext(ctx, query, agentID).Scan(
|
||||||
&summary["total_disks"],
|
&totalDisks,
|
||||||
&summary["critical_disks"],
|
&criticalDisks,
|
||||||
&summary["important_disks"],
|
&importantDisks,
|
||||||
&summary["avg_used_percent"],
|
&avgUsedPercent,
|
||||||
&summary["max_used_percent"],
|
&maxUsedPercent,
|
||||||
&summary["first_collected_at"],
|
&firstCollectedAt,
|
||||||
&summary["last_collected_at"],
|
&lastCollectedAt,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to get storage metrics summary: %w", err)
|
return nil, fmt.Errorf("failed to get storage metrics summary: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
summary := map[string]interface{}{
|
||||||
|
"total_disks": totalDisks,
|
||||||
|
"critical_disks": criticalDisks,
|
||||||
|
"important_disks": importantDisks,
|
||||||
|
"avg_used_percent": avgUsedPercent.Float64,
|
||||||
|
"max_used_percent": maxUsedPercent.Float64,
|
||||||
|
"first_collected_at": firstCollectedAt.Time,
|
||||||
|
"last_collected_at": lastCollectedAt.Time,
|
||||||
|
}
|
||||||
|
|
||||||
return summary, nil
|
return summary, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useMemo } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import {
|
import {
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
@@ -266,9 +266,9 @@ export function AgentHealth({ agentId }: AgentHealthProps) {
|
|||||||
{ value: 20160, label: '2 weeks' },
|
{ value: 20160, label: '2 weeks' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Calculate counts directly without useMemo
|
||||||
const enabledCount = useMemo(() => subsystems.filter(s => s.enabled).length, [subsystems]);
|
const enabledCount = subsystems.filter(s => s.enabled).length;
|
||||||
const autoRunCount = useMemo(() => subsystems.filter(s => s.auto_run && s.enabled).length, [subsystems]);
|
const autoRunCount = subsystems.filter(s => s.auto_run && s.enabled).length;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
|||||||
@@ -1,624 +0,0 @@
|
|||||||
import React, { useState } from 'react';
|
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import {
|
|
||||||
RefreshCw,
|
|
||||||
Activity,
|
|
||||||
Play,
|
|
||||||
HardDrive,
|
|
||||||
Cpu,
|
|
||||||
Container,
|
|
||||||
Package,
|
|
||||||
Shield,
|
|
||||||
Fingerprint,
|
|
||||||
CheckCircle,
|
|
||||||
AlertCircle,
|
|
||||||
XCircle,
|
|
||||||
Upload,
|
|
||||||
} from 'lucide-react';
|
|
||||||
import { formatRelativeTime } from '@/lib/utils';
|
|
||||||
import { agentApi, securityApi } from '@/lib/api';
|
|
||||||
import toast from 'react-hot-toast';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { AgentSubsystem } from '@/types';
|
|
||||||
import { AgentUpdatesModal } from './AgentUpdatesModal';
|
|
||||||
|
|
||||||
interface AgentScannersProps {
|
|
||||||
agentId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Map subsystem types to icons and display names
|
|
||||||
const subsystemConfig: Record<string, { icon: React.ReactNode; name: string; description: string; category: string }> = {
|
|
||||||
updates: {
|
|
||||||
icon: <Package className="h-4 w-4" />,
|
|
||||||
name: 'Package Update Scanner',
|
|
||||||
description: 'Scans for available package updates (APT, DNF, Windows Update, etc.)',
|
|
||||||
category: 'system',
|
|
||||||
},
|
|
||||||
storage: {
|
|
||||||
icon: <HardDrive className="h-4 w-4" />,
|
|
||||||
name: 'Disk Usage Reporter',
|
|
||||||
description: 'Reports disk usage metrics and storage availability',
|
|
||||||
category: 'storage',
|
|
||||||
},
|
|
||||||
system: {
|
|
||||||
icon: <Cpu className="h-4 w-4" />,
|
|
||||||
name: 'System Metrics Scanner',
|
|
||||||
description: 'Reports CPU, memory, processes, and system uptime',
|
|
||||||
category: 'system',
|
|
||||||
},
|
|
||||||
docker: {
|
|
||||||
icon: <Container className="h-4 w-4" />,
|
|
||||||
name: 'Docker Image Scanner',
|
|
||||||
description: 'Scans Docker containers for available image updates',
|
|
||||||
category: 'system',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export function AgentScanners({ agentId }: AgentScannersProps) {
|
|
||||||
const [showUpdateModal, setShowUpdateModal] = useState(false);
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
|
|
||||||
// Fetch subsystems from API
|
|
||||||
const { data: subsystems = [], isLoading, refetch } = useQuery({
|
|
||||||
queryKey: ['subsystems', agentId],
|
|
||||||
queryFn: async () => {
|
|
||||||
const data = await agentApi.getSubsystems(agentId);
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
refetchInterval: 30000, // Refresh every 30 seconds
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch agent data for Update Agent button
|
|
||||||
const { data: agent } = useQuery({
|
|
||||||
queryKey: ['agent', agentId],
|
|
||||||
queryFn: () => agentApi.getAgent(agentId),
|
|
||||||
refetchInterval: 30000,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch security health status
|
|
||||||
const { data: securityOverview, isLoading: securityLoading } = useQuery({
|
|
||||||
queryKey: ['security-overview'],
|
|
||||||
queryFn: async () => {
|
|
||||||
const data = await securityApi.getOverview();
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
refetchInterval: 60000, // Refresh every minute
|
|
||||||
});
|
|
||||||
|
|
||||||
// Helper function to get security status color and icon
|
|
||||||
const getSecurityStatusDisplay = (status: string) => {
|
|
||||||
switch (status) {
|
|
||||||
case 'healthy':
|
|
||||||
case 'operational':
|
|
||||||
return {
|
|
||||||
color: 'text-green-600 bg-green-100 border-green-200',
|
|
||||||
icon: <CheckCircle className="h-4 w-4 text-green-600" />
|
|
||||||
};
|
|
||||||
case 'enforced':
|
|
||||||
return {
|
|
||||||
color: 'text-blue-600 bg-blue-100 border-blue-200',
|
|
||||||
icon: <Shield className="h-4 w-4 text-blue-600" />
|
|
||||||
};
|
|
||||||
case 'degraded':
|
|
||||||
return {
|
|
||||||
color: 'text-amber-600 bg-amber-100 border-amber-200',
|
|
||||||
icon: <AlertCircle className="h-4 w-4 text-amber-600" />
|
|
||||||
};
|
|
||||||
case 'unhealthy':
|
|
||||||
case 'unavailable':
|
|
||||||
return {
|
|
||||||
color: 'text-red-600 bg-red-100 border-red-200',
|
|
||||||
icon: <XCircle className="h-4 w-4 text-red-600" />
|
|
||||||
};
|
|
||||||
default:
|
|
||||||
return {
|
|
||||||
color: 'text-gray-600 bg-gray-100 border-gray-200',
|
|
||||||
icon: <AlertCircle className="h-4 w-4 text-gray-600" />
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get security icon for subsystem type
|
|
||||||
const getSecurityIcon = (type: string) => {
|
|
||||||
switch (type) {
|
|
||||||
case 'ed25519_signing':
|
|
||||||
return <Shield className="h-4 w-4" />;
|
|
||||||
case 'nonce_validation':
|
|
||||||
return <RefreshCw className="h-4 w-4" />;
|
|
||||||
case 'machine_binding':
|
|
||||||
return <Fingerprint className="h-4 w-4" />;
|
|
||||||
case 'command_validation':
|
|
||||||
return <CheckCircle className="h-4 w-4" />;
|
|
||||||
default:
|
|
||||||
return <Shield className="h-4 w-4" />;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get display name for security subsystem
|
|
||||||
const getSecurityDisplayName = (type: string) => {
|
|
||||||
switch (type) {
|
|
||||||
case 'ed25519_signing':
|
|
||||||
return 'Ed25519 Signing';
|
|
||||||
case 'nonce_validation':
|
|
||||||
return 'Nonce Protection';
|
|
||||||
case 'machine_binding':
|
|
||||||
return 'Machine Binding';
|
|
||||||
case 'command_validation':
|
|
||||||
return 'Command Validation';
|
|
||||||
default:
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Toggle subsystem enabled/disabled
|
|
||||||
const toggleSubsystemMutation = useMutation({
|
|
||||||
mutationFn: async ({ subsystem, enabled }: { subsystem: string; enabled: boolean }) => {
|
|
||||||
if (enabled) {
|
|
||||||
return await agentApi.enableSubsystem(agentId, subsystem);
|
|
||||||
} else {
|
|
||||||
return await agentApi.disableSubsystem(agentId, subsystem);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onSuccess: (_, variables) => {
|
|
||||||
toast.success(`${subsystemConfig[variables.subsystem]?.name || variables.subsystem} ${variables.enabled ? 'enabled' : 'disabled'}`);
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
|
|
||||||
},
|
|
||||||
onError: (error: any, variables) => {
|
|
||||||
toast.error(`Failed to ${variables.enabled ? 'enable' : 'disable'} subsystem: ${error.response?.data?.error || error.message}`);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update subsystem interval
|
|
||||||
const updateIntervalMutation = useMutation({
|
|
||||||
mutationFn: async ({ subsystem, intervalMinutes }: { subsystem: string; intervalMinutes: number }) => {
|
|
||||||
return await agentApi.setSubsystemInterval(agentId, subsystem, intervalMinutes);
|
|
||||||
},
|
|
||||||
onSuccess: (_, variables) => {
|
|
||||||
toast.success(`Interval updated to ${variables.intervalMinutes} minutes`);
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
|
|
||||||
},
|
|
||||||
onError: (error: any) => {
|
|
||||||
toast.error(`Failed to update interval: ${error.response?.data?.error || error.message}`);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Toggle auto-run
|
|
||||||
const toggleAutoRunMutation = useMutation({
|
|
||||||
mutationFn: async ({ subsystem, autoRun }: { subsystem: string; autoRun: boolean }) => {
|
|
||||||
return await agentApi.setSubsystemAutoRun(agentId, subsystem, autoRun);
|
|
||||||
},
|
|
||||||
onSuccess: (_, variables) => {
|
|
||||||
toast.success(`Auto-run ${variables.autoRun ? 'enabled' : 'disabled'}`);
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
|
|
||||||
},
|
|
||||||
onError: (error: any) => {
|
|
||||||
toast.error(`Failed to toggle auto-run: ${error.response?.data?.error || error.message}`);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Trigger manual scan
|
|
||||||
const triggerScanMutation = useMutation({
|
|
||||||
mutationFn: async (subsystem: string) => {
|
|
||||||
return await agentApi.triggerSubsystem(agentId, subsystem);
|
|
||||||
},
|
|
||||||
onSuccess: (_, subsystem) => {
|
|
||||||
toast.success(`${subsystemConfig[subsystem]?.name || subsystem} scan triggered`);
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
|
|
||||||
},
|
|
||||||
onError: (error: any) => {
|
|
||||||
toast.error(`Failed to trigger scan: ${error.response?.data?.error || error.message}`);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleToggleEnabled = (subsystem: string, currentEnabled: boolean) => {
|
|
||||||
toggleSubsystemMutation.mutate({ subsystem, enabled: !currentEnabled });
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleIntervalChange = (subsystem: string, intervalMinutes: number) => {
|
|
||||||
updateIntervalMutation.mutate({ subsystem, intervalMinutes });
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleToggleAutoRun = (subsystem: string, currentAutoRun: boolean) => {
|
|
||||||
toggleAutoRunMutation.mutate({ subsystem, autoRun: !currentAutoRun });
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleTriggerScan = (subsystem: string) => {
|
|
||||||
triggerScanMutation.mutate(subsystem);
|
|
||||||
};
|
|
||||||
|
|
||||||
const frequencyOptions = [
|
|
||||||
{ value: 5, label: '5 min' },
|
|
||||||
{ value: 15, label: '15 min' },
|
|
||||||
{ value: 30, label: '30 min' },
|
|
||||||
{ value: 60, label: '1 hour' },
|
|
||||||
{ value: 240, label: '4 hours' },
|
|
||||||
{ value: 720, label: '12 hours' },
|
|
||||||
{ value: 1440, label: '24 hours' },
|
|
||||||
];
|
|
||||||
|
|
||||||
|
|
||||||
const enabledCount = subsystems.filter(s => s.enabled).length;
|
|
||||||
const autoRunCount = subsystems.filter(s => s.auto_run && s.enabled).length;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Subsystems Section - Continuous Surface */}
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-base font-semibold text-gray-900">Subsystems</h3>
|
|
||||||
<p className="text-xs text-gray-600 mt-0.5">
|
|
||||||
{enabledCount} enabled • {autoRunCount} auto-running • {subsystems.length} total
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowUpdateModal(true)}
|
|
||||||
className="text-sm text-primary-600 hover:text-primary-800 flex items-center space-x-1 border border-primary-300 px-2 py-1 rounded"
|
|
||||||
>
|
|
||||||
<Upload className="h-4 w-4" />
|
|
||||||
<span>Update Agent</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="flex items-center justify-center py-12">
|
|
||||||
<RefreshCw className="h-6 w-6 animate-spin text-gray-400" />
|
|
||||||
<span className="ml-2 text-gray-600">Loading subsystems...</span>
|
|
||||||
</div>
|
|
||||||
) : subsystems.length === 0 ? (
|
|
||||||
<div className="text-center py-12">
|
|
||||||
<Activity className="mx-auto h-12 w-12 text-gray-400" />
|
|
||||||
<h3 className="mt-2 text-sm font-medium text-gray-900">No subsystems found</h3>
|
|
||||||
<p className="mt-1 text-sm text-gray-500">
|
|
||||||
Subsystems will be created automatically when the agent checks in.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="overflow-x-auto">
|
|
||||||
<table className="min-w-full text-sm">
|
|
||||||
<thead>
|
|
||||||
<tr className="border-b border-gray-200">
|
|
||||||
<th className="text-left py-2 pr-4 font-medium text-gray-700">Subsystem</th>
|
|
||||||
<th className="text-left py-2 pr-4 font-medium text-gray-700">Category</th>
|
|
||||||
<th className="text-center py-2 pr-4 font-medium text-gray-700">Enabled</th>
|
|
||||||
<th className="text-center py-2 pr-4 font-medium text-gray-700">Auto-Run</th>
|
|
||||||
<th className="text-center py-2 pr-4 font-medium text-gray-700">Interval</th>
|
|
||||||
<th className="text-right py-2 pr-4 font-medium text-gray-700">Last Run</th>
|
|
||||||
<th className="text-right py-2 pr-4 font-medium text-gray-700">Next Run</th>
|
|
||||||
<th className="text-center py-2 font-medium text-gray-700">Actions</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-gray-100">
|
|
||||||
{subsystems.map((subsystem: AgentSubsystem) => {
|
|
||||||
const config = subsystemConfig[subsystem.subsystem] || {
|
|
||||||
icon: <Activity className="h-4 w-4" />,
|
|
||||||
name: subsystem.subsystem,
|
|
||||||
description: 'Custom subsystem',
|
|
||||||
category: 'system',
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<tr key={subsystem.id} className="hover:bg-gray-50">
|
|
||||||
{/* Subsystem Name */}
|
|
||||||
<td className="py-3 pr-4 text-gray-900">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<span className="text-gray-600">{config.icon}</span>
|
|
||||||
<div>
|
|
||||||
<div className="font-medium">{config.name}</div>
|
|
||||||
<div className="text-xs text-gray-500">{config.description}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
|
|
||||||
{/* Category */}
|
|
||||||
<td className="py-3 pr-4 text-gray-600 capitalize text-xs">{config.category}</td>
|
|
||||||
|
|
||||||
{/* Enabled Toggle */}
|
|
||||||
<td className="py-3 pr-4 text-center">
|
|
||||||
<button
|
|
||||||
onClick={() => handleToggleEnabled(subsystem.subsystem, subsystem.enabled)}
|
|
||||||
disabled={toggleSubsystemMutation.isPending}
|
|
||||||
className={cn(
|
|
||||||
'px-3 py-1 rounded text-xs font-medium transition-colors',
|
|
||||||
subsystem.enabled
|
|
||||||
? 'bg-green-100 text-green-700 hover:bg-green-200'
|
|
||||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{subsystem.enabled ? 'ON' : 'OFF'}
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
|
|
||||||
{/* Auto-Run Toggle */}
|
|
||||||
<td className="py-3 pr-4 text-center">
|
|
||||||
<button
|
|
||||||
onClick={() => handleToggleAutoRun(subsystem.subsystem, subsystem.auto_run)}
|
|
||||||
disabled={!subsystem.enabled || toggleAutoRunMutation.isPending}
|
|
||||||
className={cn(
|
|
||||||
'px-3 py-1 rounded text-xs font-medium transition-colors',
|
|
||||||
!subsystem.enabled ? 'bg-gray-50 text-gray-400 cursor-not-allowed' :
|
|
||||||
subsystem.auto_run
|
|
||||||
? 'bg-blue-100 text-blue-700 hover:bg-blue-200'
|
|
||||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{subsystem.auto_run ? 'AUTO' : 'MANUAL'}
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
|
|
||||||
{/* Interval Selector */}
|
|
||||||
<td className="py-3 pr-4 text-center">
|
|
||||||
{subsystem.enabled ? (
|
|
||||||
<select
|
|
||||||
value={subsystem.interval_minutes}
|
|
||||||
onChange={(e) => handleIntervalChange(subsystem.subsystem, parseInt(e.target.value))}
|
|
||||||
disabled={updateIntervalMutation.isPending}
|
|
||||||
className="px-2 py-1 text-xs border border-gray-300 rounded hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
|
||||||
>
|
|
||||||
{frequencyOptions.map(option => (
|
|
||||||
<option key={option.value} value={option.value}>
|
|
||||||
{option.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
) : (
|
|
||||||
<span className="text-xs text-gray-400">-</span>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
|
|
||||||
{/* Last Run */}
|
|
||||||
<td className="py-3 pr-4 text-right text-xs text-gray-600">
|
|
||||||
{subsystem.last_run_at ? formatRelativeTime(subsystem.last_run_at) : '-'}
|
|
||||||
</td>
|
|
||||||
|
|
||||||
{/* Next Run */}
|
|
||||||
<td className="py-3 pr-4 text-right text-xs text-gray-600">
|
|
||||||
{subsystem.next_run_at && subsystem.auto_run ? formatRelativeTime(subsystem.next_run_at) : '-'}
|
|
||||||
</td>
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<td className="py-3 text-center">
|
|
||||||
<button
|
|
||||||
onClick={() => handleTriggerScan(subsystem.subsystem)}
|
|
||||||
disabled={!subsystem.enabled || triggerScanMutation.isPending}
|
|
||||||
className={cn(
|
|
||||||
'px-3 py-1 rounded text-xs font-medium transition-colors inline-flex items-center space-x-1',
|
|
||||||
!subsystem.enabled
|
|
||||||
? 'bg-gray-50 text-gray-400 cursor-not-allowed'
|
|
||||||
: 'bg-blue-100 text-blue-700 hover:bg-blue-200'
|
|
||||||
)}
|
|
||||||
title="Trigger manual scan"
|
|
||||||
>
|
|
||||||
<Play className="h-3 w-3" />
|
|
||||||
<span>Scan</span>
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Security Health Section - Continuous Surface */}
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Shield className="h-5 w-5 text-blue-600" />
|
|
||||||
<h3 className="text-base font-semibold text-gray-900">Security Health</h3>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => queryClient.invalidateQueries({ queryKey: ['security-overview'] })}
|
|
||||||
disabled={securityLoading}
|
|
||||||
className="flex items-center space-x-1 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 hover:bg-gray-50/50 rounded-md transition-colors"
|
|
||||||
>
|
|
||||||
<RefreshCw className={cn('h-3 w-3', securityLoading && 'animate-spin')} />
|
|
||||||
<span>Refresh</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{securityLoading ? (
|
|
||||||
<div className="flex items-center justify-center py-6">
|
|
||||||
<RefreshCw className="h-5 w-5 animate-spin text-gray-400" />
|
|
||||||
<span className="ml-2 text-sm text-gray-600">Loading security status...</span>
|
|
||||||
</div>
|
|
||||||
) : securityOverview ? (
|
|
||||||
<div className="p-4 space-y-3">
|
|
||||||
{/* Overall Status - Compact */}
|
|
||||||
<div className="flex items-center justify-between p-3 bg-white/70 backdrop-blur-sm rounded-lg border border-gray-200/30">
|
|
||||||
<div className="flex items-center space-x-3">
|
|
||||||
<div className={cn(
|
|
||||||
'w-3 h-3 rounded-full',
|
|
||||||
securityOverview.overall_status === 'healthy' ? 'bg-green-500' :
|
|
||||||
securityOverview.overall_status === 'degraded' ? 'bg-amber-500' : 'bg-red-500'
|
|
||||||
)}></div>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs font-medium text-gray-900">Overall Status</p>
|
|
||||||
<p className="text-xs text-gray-600">
|
|
||||||
{securityOverview.overall_status === 'healthy' ? 'All systems nominal' :
|
|
||||||
securityOverview.overall_status === 'degraded' ? `${securityOverview.alerts.length} issue(s)` :
|
|
||||||
'Critical issues'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className={cn(
|
|
||||||
'inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium border',
|
|
||||||
securityOverview.overall_status === 'healthy' ? 'bg-green-100 text-green-700 border-green-200' :
|
|
||||||
securityOverview.overall_status === 'degraded' ? 'bg-amber-100 text-amber-700 border-amber-200' :
|
|
||||||
'bg-red-100 text-red-700 border-red-200'
|
|
||||||
)}>
|
|
||||||
{securityOverview.overall_status === 'healthy' && <CheckCircle className="w-3 h-3" />}
|
|
||||||
{securityOverview.overall_status === 'degraded' && <AlertCircle className="w-3 h-3" />}
|
|
||||||
{securityOverview.overall_status === 'unhealthy' && <XCircle className="w-3 h-3" />}
|
|
||||||
{securityOverview.overall_status.toUpperCase()}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Security Grid - 2x2 Layout */}
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
{Object.entries(securityOverview.subsystems).map(([key, subsystem]) => {
|
|
||||||
const statusColors = {
|
|
||||||
healthy: 'bg-green-100 text-green-700 border-green-200',
|
|
||||||
enforced: 'bg-blue-100 text-blue-700 border-blue-200',
|
|
||||||
degraded: 'bg-amber-100 text-amber-700 border-amber-200',
|
|
||||||
unhealthy: 'bg-red-100 text-red-700 border-red-200'
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div key={key} className="group relative">
|
|
||||||
<div className={cn(
|
|
||||||
'p-3 bg-white/70 backdrop-blur-sm rounded-lg border border-gray-200/30',
|
|
||||||
'hover:bg-white/90 hover:shadow-sm transition-all duration-150 cursor-pointer'
|
|
||||||
)}>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<div className="p-1.5 rounded-md bg-gray-50/80 group-hover:bg-gray-100 transition-colors">
|
|
||||||
{getSecurityIcon(key)}
|
|
||||||
</div>
|
|
||||||
<div className="min-w-0">
|
|
||||||
<p className="text-xs font-medium text-gray-900 truncate">
|
|
||||||
{getSecurityDisplayName(key)}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-gray-600 truncate">
|
|
||||||
{key === 'command_validation' ?
|
|
||||||
`${subsystem.metrics?.total_pending_commands || 0} pending` :
|
|
||||||
key === 'ed25519_signing' ?
|
|
||||||
'Key valid' :
|
|
||||||
key === 'machine_binding' ?
|
|
||||||
`${subsystem.checks?.recent_violations || 0} violations` :
|
|
||||||
key === 'nonce_validation' ?
|
|
||||||
`${subsystem.checks?.validation_failures || 0} blocked` :
|
|
||||||
subsystem.status}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className={cn(
|
|
||||||
'px-1.5 py-0.5 rounded text-[10px] font-medium border',
|
|
||||||
statusColors[subsystem.status as keyof typeof statusColors] || statusColors.unhealthy
|
|
||||||
)}>
|
|
||||||
{subsystem.status === 'healthy' && <CheckCircle className="w-3 h-3 inline" />}
|
|
||||||
{subsystem.status === 'enforced' && <Shield className="w-3 h-3 inline" />}
|
|
||||||
{subsystem.status === 'degraded' && <AlertCircle className="w-3 h-3 inline" />}
|
|
||||||
{subsystem.status === 'unhealthy' && <XCircle className="w-3 h-3 inline" />}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Detailed Info Panel */}
|
|
||||||
<div className="grid grid-cols-1 gap-2">
|
|
||||||
{Object.entries(securityOverview.subsystems).map(([key, subsystem]) => {
|
|
||||||
const checks = subsystem.checks || {};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div key={`${key}-details`} className="opacity-70 hover:opacity-100 transition-opacity">
|
|
||||||
<div className="p-2 bg-gray-50/70 rounded border border-gray-200/50">
|
|
||||||
<p className="text-[10px] text-gray-700 font-mono truncate">
|
|
||||||
{key === 'nonce_validation' ?
|
|
||||||
`Nonces: ${subsystem.metrics?.total_pending_commands || 0} | Max: ${checks.max_age_minutes || 5}m | Failures: ${checks.validation_failures || 0}` :
|
|
||||||
key === 'machine_binding' ?
|
|
||||||
`Bound: ${checks.bound_agents || 'N/A'} | Violations: ${checks.recent_violations || 0} | Method: Hardware` :
|
|
||||||
key === 'ed25519_signing' ?
|
|
||||||
`Key: ${checks.public_key_fingerprint?.substring(0, 16) || 'N/A'}... | Algo: ${checks.algorithm || 'Ed25519'}` :
|
|
||||||
key === 'command_validation' ?
|
|
||||||
`Processed: ${subsystem.metrics?.commands_last_hour || 0}/hr | Pending: ${subsystem.metrics?.total_pending_commands || 0}` :
|
|
||||||
`Status: ${subsystem.status}`}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Security Alerts & Recommendations */}
|
|
||||||
{(securityOverview.alerts.length > 0 || securityOverview.recommendations.length > 0) && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{securityOverview.alerts.length > 0 && (
|
|
||||||
<div className="flex-1 p-2 bg-red-50 rounded border border-red-200">
|
|
||||||
<div className="flex items-center gap-1 mb-1">
|
|
||||||
<XCircle className="h-3 w-3 text-red-500" />
|
|
||||||
<p className="text-xs font-medium text-red-800">Alerts ({securityOverview.alerts.length})</p>
|
|
||||||
</div>
|
|
||||||
<ul className="text-[10px] text-red-700 space-y-0.5">
|
|
||||||
{securityOverview.alerts.slice(0, 1).map((alert, index) => (
|
|
||||||
<li key={index} className="truncate">• {alert}</li>
|
|
||||||
))}
|
|
||||||
{securityOverview.alerts.length > 1 && (
|
|
||||||
<li className="text-red-600">+{securityOverview.alerts.length - 1} more</li>
|
|
||||||
)}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{securityOverview.recommendations.length > 0 && (
|
|
||||||
<div className="flex-1 p-2 bg-amber-50 rounded border border-amber-200">
|
|
||||||
<div className="flex items-center gap-1 mb-1">
|
|
||||||
<AlertCircle className="h-3 w-3 text-amber-500" />
|
|
||||||
<p className="text-xs font-medium text-amber-800">Recs ({securityOverview.recommendations.length})</p>
|
|
||||||
</div>
|
|
||||||
<ul className="text-[10px] text-amber-700 space-y-0.5">
|
|
||||||
{securityOverview.recommendations.slice(0, 1).map((rec, index) => (
|
|
||||||
<li key={index} className="truncate">• {rec}</li>
|
|
||||||
))}
|
|
||||||
{securityOverview.recommendations.length > 1 && (
|
|
||||||
<li className="text-amber-600">+{securityOverview.recommendations.length - 1} more</li>
|
|
||||||
)}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Stats Row */}
|
|
||||||
<div className="flex justify-between pt-2 border-t border-gray-200/50">
|
|
||||||
<div className="text-center">
|
|
||||||
<p className="text-[11px] font-medium text-gray-900">{Object.keys(securityOverview.subsystems).length}</p>
|
|
||||||
<p className="text-[10px] text-gray-600">Systems</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-center">
|
|
||||||
<p className="text-[11px] font-medium text-gray-900">
|
|
||||||
{Object.values(securityOverview.subsystems).filter(s => s.status === 'healthy' || s.status === 'enforced').length}
|
|
||||||
</p>
|
|
||||||
<p className="text-[10px] text-gray-600">Healthy</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-center">
|
|
||||||
<p className="text-[11px] font-medium text-gray-900">{securityOverview.alerts.length}</p>
|
|
||||||
<p className="text-[10px] text-gray-600">Alerts</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-center">
|
|
||||||
<p className="text-[11px] font-medium text-gray-600">
|
|
||||||
{new Date(securityOverview.timestamp).toLocaleTimeString()}
|
|
||||||
</p>
|
|
||||||
<p className="text-[10px] text-gray-600">Updated</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="text-center py-6">
|
|
||||||
<Shield className="mx-auto h-6 w-6 text-gray-400" />
|
|
||||||
<p className="mt-1 text-xs text-gray-600">Unable to load security status</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Agent Updates Modal */}
|
|
||||||
<AgentUpdatesModal
|
|
||||||
isOpen={showUpdateModal}
|
|
||||||
onClose={() => {
|
|
||||||
setShowUpdateModal(false);
|
|
||||||
}}
|
|
||||||
selectedAgentIds={[agentId]} // Single agent for this scanner view
|
|
||||||
onAgentsUpdated={() => {
|
|
||||||
// Refresh agent and subsystems data after update
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['agent', agentId] });
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react';
|
import { useState, useMemo } from 'react';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import {
|
import {
|
||||||
HardDrive,
|
HardDrive,
|
||||||
@@ -58,7 +58,7 @@ export function AgentStorage({ agentId }: AgentStorageProps) {
|
|||||||
const { data: storageData, refetch: refetchStorage } = useQuery({
|
const { data: storageData, refetch: refetchStorage } = useQuery({
|
||||||
queryKey: ['storage-metrics', agentId],
|
queryKey: ['storage-metrics', agentId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
return await storageMetricsApi.getStorageMetrics(agentId);
|
return await agentApi.getStorageMetrics(agentId);
|
||||||
},
|
},
|
||||||
refetchInterval: 30000, // Refresh every 30 seconds
|
refetchInterval: 30000, // Refresh every 30 seconds
|
||||||
});
|
});
|
||||||
@@ -124,18 +124,6 @@ export function AgentStorage({ agentId }: AgentStorageProps) {
|
|||||||
is_largest: disk.is_largest || false,
|
is_largest: disk.is_largest || false,
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
mountpoint: disk.mountpoint,
|
|
||||||
total: disk.total,
|
|
||||||
available: disk.available,
|
|
||||||
used: disk.used,
|
|
||||||
used_percent: disk.used_percent,
|
|
||||||
filesystem: disk.filesystem,
|
|
||||||
is_root: disk.is_root || false,
|
|
||||||
is_largest: disk.is_largest || false,
|
|
||||||
disk_type: disk.disk_type || 'Unknown',
|
|
||||||
device: disk.device || disk.filesystem,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
if (!agentData) {
|
if (!agentData) {
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ import toast from 'react-hot-toast';
|
|||||||
import { AgentSystemUpdates } from '@/components/AgentUpdates';
|
import { AgentSystemUpdates } from '@/components/AgentUpdates';
|
||||||
import { AgentStorage } from '@/components/AgentStorage';
|
import { AgentStorage } from '@/components/AgentStorage';
|
||||||
import { AgentUpdatesEnhanced } from '@/components/AgentUpdatesEnhanced';
|
import { AgentUpdatesEnhanced } from '@/components/AgentUpdatesEnhanced';
|
||||||
import { AgentScanners } from '@/components/AgentScanners';
|
import { AgentHealth } from '@/components/AgentHealth';
|
||||||
import { AgentUpdatesModal } from '@/components/AgentUpdatesModal';
|
import { AgentUpdatesModal } from '@/components/AgentUpdatesModal';
|
||||||
import { BulkAgentUpdate } from '@/components/RelayList';
|
import { BulkAgentUpdate } from '@/components/RelayList';
|
||||||
import ChatTimeline from '@/components/ChatTimeline';
|
import ChatTimeline from '@/components/ChatTimeline';
|
||||||
@@ -955,7 +955,7 @@ const Agents: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{activeTab === 'scanners' && (
|
{activeTab === 'scanners' && (
|
||||||
<AgentScanners agentId={selectedAgent.id} />
|
<AgentHealth agentId={selectedAgent.id} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{activeTab === 'history' && (
|
{activeTab === 'history' && (
|
||||||
|
|||||||
@@ -414,4 +414,35 @@ export interface SubsystemStats {
|
|||||||
run_count: number;
|
run_count: number;
|
||||||
last_status: string;
|
last_status: string;
|
||||||
last_duration: number;
|
last_duration: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Security subsystem types
|
||||||
|
export interface SecuritySubsystem {
|
||||||
|
status: string;
|
||||||
|
enabled: boolean;
|
||||||
|
metrics?: {
|
||||||
|
total_pending_commands?: number;
|
||||||
|
commands_last_hour?: number;
|
||||||
|
};
|
||||||
|
checks?: {
|
||||||
|
recent_violations?: number;
|
||||||
|
validation_failures?: number;
|
||||||
|
max_age_minutes?: number;
|
||||||
|
bound_agents?: number;
|
||||||
|
public_key_fingerprint?: string;
|
||||||
|
algorithm?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SecurityOverview {
|
||||||
|
overall_status: 'healthy' | 'degraded' | 'unhealthy';
|
||||||
|
timestamp: string;
|
||||||
|
subsystems: {
|
||||||
|
ed25519_signing: SecuritySubsystem;
|
||||||
|
nonce_validation: SecuritySubsystem;
|
||||||
|
machine_binding: SecuritySubsystem;
|
||||||
|
command_validation: SecuritySubsystem;
|
||||||
|
};
|
||||||
|
alerts: string[];
|
||||||
|
recommendations: string[];
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user