handlers

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package handlers provides HTTP request handlers for the Scanorama API. This file implements the AdminHandler type and its HTTP handler methods for configuration endpoints.

Package handlers - admin configuration retrieval and extraction.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements the AdminHandler log retrieval endpoint.

Package handlers - admin API types and request/response structures.

Package handlers - admin configuration validation.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements worker management handler methods for the AdminHandler type.

Package handlers provides HTTP request handlers for the Scanorama API. This file contains common utilities shared across all handlers to reduce code duplication and provide consistent patterns.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements discovery job management endpoints including CRUD operations, discovery execution control, and results retrieval.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements health check and system status endpoints.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements host management endpoints including CRUD operations and host-related scan retrieval.

Package handlers provides HTTP request handlers for the Scanorama API. This file defines the narrow interfaces that each handler depends on, allowing unit tests to inject mocks without a live database.

Package handlers provides HTTP request handlers for the Scanorama API. This package implements REST endpoint handlers for scanning, discovery, host management, and administrative operations.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements scan profile management endpoints including CRUD operations and profile configurations for different scan types.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements scan management endpoints including CRUD operations, scan execution control, and results retrieval.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements schedule management endpoints including CRUD operations and schedule activation/deactivation.

Package handlers provides HTTP request handlers for the Scanorama API. This file implements WebSocket endpoints for real-time updates on scan and discovery job progress, status changes, and results.

Index

Constants

View Source
const (
	StatusHealthy       = "healthy"
	StatusUnhealthy     = "unhealthy"
	StatusNotConfigured = "not configured"
)

Status constants.

Variables

This section is empty.

Functions

func CreateEntity

func CreateEntity[T any, I any](
	w http.ResponseWriter,
	r *http.Request,
	entityType string,
	logger *slog.Logger,
	metricsRegistry metrics.MetricsRegistry,
	parseAndConvert func(*http.Request) (I, error),
	createInDB func(context.Context, I) (*T, error),
	toResponse func(*T) interface{},
	metricName string,
)

CreateEntity is a generic helper to eliminate duplication in create operations. The type parameter I is the typed input struct passed to createInDB (e.g. db.CreateScanInput).

func SetBuildInfo

func SetBuildInfo(v, c, bt string)

SetBuildInfo sets build information (called by main package).

func UpdateEntity

func UpdateEntity[T any, I any](
	w http.ResponseWriter,
	r *http.Request,
	entityType string,
	logger *slog.Logger,
	metricsRegistry metrics.MetricsRegistry,
	parseAndConvert func(*http.Request) (I, error),
	updateInDB func(context.Context, uuid.UUID, I) (*T, error),
	toResponse func(*T) interface{},
	metricName string,
)

UpdateEntity is a generic helper to eliminate duplication in update operations. The type parameter I is the typed input struct passed to updateInDB (e.g. db.UpdateScanInput).

Types

type APIConfigUpdate

type APIConfigUpdate struct {
	Enabled           *bool    `json:"enabled,omitempty"`
	Host              *string  `json:"host,omitempty"`
	Port              *int     `json:"port,omitempty" validate:"omitempty,min=1,max=65535"`
	ReadTimeout       *string  `json:"read_timeout,omitempty"`
	WriteTimeout      *string  `json:"write_timeout,omitempty"`
	IdleTimeout       *string  `json:"idle_timeout,omitempty"`
	MaxHeaderBytes    *int     `json:"max_header_bytes,omitempty" validate:"omitempty,min=1024,max=1048576"`
	EnableCORS        *bool    `json:"enable_cors,omitempty"`
	CORSOrigins       []string `json:"cors_origins,omitempty"`
	AuthEnabled       *bool    `json:"auth_enabled,omitempty"`
	RateLimitEnabled  *bool    `json:"rate_limit_enabled,omitempty"`
	RateLimitRequests *int     `json:"rate_limit_requests,omitempty" validate:"omitempty,min=1,max=10000"`
	RateLimitWindow   *string  `json:"rate_limit_window,omitempty"`
	RequestTimeout    *string  `json:"request_timeout,omitempty"`
	MaxRequestSize    *int     `json:"max_request_size,omitempty" validate:"omitempty,min=1,max=104857600"`
}

APIConfigUpdate represents updatable API configuration fields.

type AdminHandler

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

AdminHandler handles administrative API endpoints.

func NewAdminHandler

func NewAdminHandler(logger *slog.Logger, metricsManager *metrics.Registry) *AdminHandler

NewAdminHandler creates a new admin handler.

func (*AdminHandler) GetConfig

func (h *AdminHandler) GetConfig(w http.ResponseWriter, r *http.Request)

GetConfig handles GET /api/v1/admin/config - get current configuration.

func (*AdminHandler) GetLogs

func (h *AdminHandler) GetLogs(w http.ResponseWriter, r *http.Request)

GetLogs handles GET /api/v1/admin/logs - retrieve system logs.

func (*AdminHandler) GetWorkerStatus

func (h *AdminHandler) GetWorkerStatus(w http.ResponseWriter, r *http.Request)

GetWorkerStatus handles GET /api/v1/admin/workers - get worker pool status.

func (*AdminHandler) StopWorker

func (h *AdminHandler) StopWorker(w http.ResponseWriter, r *http.Request)

StopWorker handles POST /api/v1/admin/workers/{id}/stop - stop a specific worker.

func (*AdminHandler) UpdateConfig

func (h *AdminHandler) UpdateConfig(w http.ResponseWriter, r *http.Request)

UpdateConfig handles PUT /api/v1/admin/config - update configuration.

type BaseHandler

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

BaseHandler provides common functionality for all handlers.

func NewBaseHandler

func NewBaseHandler(logger *slog.Logger, metricsRegistry metrics.MetricsRegistry) *BaseHandler

NewBaseHandler creates a new base handler.

type CRUDMetrics

type CRUDMetrics struct {
	Listed    string
	Created   string
	Retrieved string
	Updated   string
	Deleted   string
	Started   string
	Stopped   string
}

CRUDMetrics holds metric names for CRUD operations.

type CRUDOperation

type CRUDOperation[T any] struct {
	EntityType string
	Logger     *slog.Logger
	Metrics    metrics.MetricsRegistry
}

CRUDOperation is a generic CRUD operation pattern.

func (*CRUDOperation[T]) ExecuteDelete

func (op *CRUDOperation[T]) ExecuteDelete(
	w http.ResponseWriter,
	r *http.Request,
	id uuid.UUID,
	deleteFromDB func(context.Context, uuid.UUID) error,
	metricName string,
)

ExecuteDelete performs a generic delete operation.

func (*CRUDOperation[T]) ExecuteGet

func (op *CRUDOperation[T]) ExecuteGet(
	w http.ResponseWriter,
	r *http.Request,
	id uuid.UUID,
	getFromDB func(context.Context, uuid.UUID) (*T, error),
	toResponse func(*T) interface{},
	metricName string,
)

ExecuteGet performs a generic get operation.

func (*CRUDOperation[T]) ExecuteUpdate

func (op *CRUDOperation[T]) ExecuteUpdate(
	w http.ResponseWriter,
	r *http.Request,
	id uuid.UUID,
	parseRequest func(*http.Request) (interface{}, error),
	validateRequest func(interface{}) error,
	updateInDB func(context.Context, uuid.UUID, interface{}) (*T, error),
	toResponse func(*T) interface{},
	metricName string,
)

ExecuteUpdate performs a generic update operation.

type ConfigResponse

type ConfigResponse struct {
	API      interface{} `json:"api"`
	Database interface{} `json:"database"`
	Scanning interface{} `json:"scanning"`
	Logging  interface{} `json:"logging"`
	Daemon   interface{} `json:"daemon"`
}

ConfigResponse represents configuration information.

type ConfigUpdateData

type ConfigUpdateData struct {
	API      *APIConfigUpdate      `json:"api,omitempty"`
	Database *DatabaseConfigUpdate `json:"database,omitempty"`
	Scanning *ScanningConfigUpdate `json:"scanning,omitempty"`
	Logging  *LoggingConfigUpdate  `json:"logging,omitempty"`
	Daemon   *DaemonConfigUpdate   `json:"daemon,omitempty"`
}

ConfigUpdateData represents the configuration data for updates.

type ConfigUpdateRequest

type ConfigUpdateRequest struct {
	Section string           `json:"section" validate:"required,oneof=api database scanning logging daemon"`
	Config  ConfigUpdateData `json:"config" validate:"required"`
}

ConfigUpdateRequest represents a request to update configuration.

type ContextKey

type ContextKey string

ContextKey represents a context key type.

type CreateExclusionRequest added in v0.8.0

type CreateExclusionRequest struct {
	ExcludedCIDR string  `json:"excluded_cidr" validate:"required,cidr"`
	Reason       *string `json:"reason,omitempty"`
}

CreateExclusionRequest represents the request body for creating a network exclusion.

type CreateNetworkRequest added in v0.8.0

type CreateNetworkRequest struct {
	Name            string  `json:"name"             validate:"required,min=1,max=100"`
	CIDR            string  `json:"cidr"             validate:"required,cidr"`
	Description     *string `json:"description,omitempty"`
	DiscoveryMethod string  `json:"discovery_method" validate:"required,oneof=ping tcp arp"`
	IsActive        *bool   `json:"is_active,omitempty"`
	ScanEnabled     *bool   `json:"scan_enabled,omitempty"`
}

CreateNetworkRequest represents the request body for creating a network.

type DaemonConfigUpdate

type DaemonConfigUpdate struct {
	PIDFile         *string `json:"pid_file,omitempty" validate:"omitempty,min=1,max=255"`
	WorkDir         *string `json:"work_dir,omitempty" validate:"omitempty,min=1,max=255"`
	User            *string `json:"user,omitempty" validate:"omitempty,min=1,max=32"`
	Group           *string `json:"group,omitempty" validate:"omitempty,min=1,max=32"`
	Daemonize       *bool   `json:"daemonize,omitempty"`
	ShutdownTimeout *string `json:"shutdown_timeout,omitempty"`
}

DaemonConfigUpdate represents updatable daemon configuration fields.

type DatabaseConfigUpdate

type DatabaseConfigUpdate struct {
	Host            *string `json:"host,omitempty"`
	Port            *int    `json:"port,omitempty" validate:"omitempty,min=1,max=65535"`
	Database        *string `json:"database,omitempty" validate:"omitempty,min=1,max=63"`
	Username        *string `json:"username,omitempty" validate:"omitempty,min=1,max=63"`
	SSLMode         *string `json:"ssl_mode,omitempty" validate:"omitempty,oneof=disable require verify-ca verify-full"`
	MaxOpenConns    *int    `json:"max_open_conns,omitempty" validate:"omitempty,min=1,max=100"`
	MaxIdleConns    *int    `json:"max_idle_conns,omitempty" validate:"omitempty,min=1,max=100"`
	ConnMaxLifetime *string `json:"conn_max_lifetime,omitempty"`
	ConnMaxIdleTime *string `json:"conn_max_idle_time,omitempty"`
}

DatabaseConfigUpdate represents updatable database configuration fields.

type DatabaseInfo

type DatabaseInfo struct {
	Connected    bool          `json:"connected"`
	Driver       string        `json:"driver"`
	Host         string        `json:"host"`
	Database     string        `json:"database"`
	LastPing     time.Time     `json:"last_ping"`
	ResponseTime time.Duration `json:"response_time_ms"`
	Error        string        `json:"error,omitempty"`
}

DatabaseInfo contains database connection information.

type DatabasePinger

type DatabasePinger interface {
	Ping(ctx context.Context) error
}

DatabasePinger defines the interface for database health checking.

type DiscoveryHandler

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

DiscoveryHandler handles discovery-related API endpoints.

func NewDiscoveryHandler

func NewDiscoveryHandler(
	database DiscoveryStore, logger *slog.Logger, metricsManager *metrics.Registry,
) *DiscoveryHandler

NewDiscoveryHandler creates a new discovery handler.

func (*DiscoveryHandler) CreateDiscoveryJob

func (h *DiscoveryHandler) CreateDiscoveryJob(w http.ResponseWriter, r *http.Request)

CreateDiscoveryJob handles POST /api/v1/discovery - create a new discovery job.

func (*DiscoveryHandler) DeleteDiscoveryJob

func (h *DiscoveryHandler) DeleteDiscoveryJob(w http.ResponseWriter, r *http.Request)

DeleteDiscoveryJob handles DELETE /api/v1/discovery/{id} - delete a discovery job.

func (*DiscoveryHandler) GetDiscoveryJob

func (h *DiscoveryHandler) GetDiscoveryJob(w http.ResponseWriter, r *http.Request)

GetDiscoveryJob handles GET /api/v1/discovery/{id} - get a discovery job.

func (*DiscoveryHandler) ListDiscoveryJobs

func (h *DiscoveryHandler) ListDiscoveryJobs(w http.ResponseWriter, r *http.Request)

ListDiscoveryJobs handles GET /api/v1/discovery - list discovery jobs with filtering and pagination.

func (*DiscoveryHandler) StartDiscovery

func (h *DiscoveryHandler) StartDiscovery(w http.ResponseWriter, r *http.Request)

StartDiscovery handles POST /api/v1/discovery/{id}/start - start a discovery job.

func (*DiscoveryHandler) StopDiscovery

func (h *DiscoveryHandler) StopDiscovery(w http.ResponseWriter, r *http.Request)

StopDiscovery handles POST /api/v1/discovery/{id}/stop - stop a running discovery job.

func (*DiscoveryHandler) UpdateDiscoveryJob

func (h *DiscoveryHandler) UpdateDiscoveryJob(w http.ResponseWriter, r *http.Request)

UpdateDiscoveryJob handles PUT /api/v1/discovery/{id} - update an existing discovery job.

func (*DiscoveryHandler) WithEngine added in v0.14.0

WithEngine sets the discovery engine used to actually execute nmap scans when a job is started via the API. Without an engine, StartDiscovery only flips the DB status row and no scan is performed.

type DiscoveryRequest

type DiscoveryRequest struct {
	Name        string            `json:"name" validate:"required,min=1,max=255"`
	Description string            `json:"description,omitempty"`
	Networks    []string          `json:"networks" validate:"required,min=1"`
	Method      string            `json:"method" validate:"required,oneof=ping arp icmp tcp_connect"`
	Ports       string            `json:"ports,omitempty"`
	Timeout     time.Duration     `json:"timeout,omitempty"`
	Retries     int               `json:"retries,omitempty"`
	Options     map[string]string `json:"options,omitempty"`
	ScheduleID  *int64            `json:"schedule_id,omitempty"`
	Tags        []string          `json:"tags,omitempty"`
	Enabled     bool              `json:"enabled"`
}

DiscoveryRequest represents a discovery job creation/update request.

type DiscoveryResponse

type DiscoveryResponse struct {
	ID          uuid.UUID         `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Networks    []string          `json:"networks"`
	Method      string            `json:"method"`
	Ports       string            `json:"ports,omitempty"`
	Timeout     time.Duration     `json:"timeout,omitempty"`
	Retries     int               `json:"retries,omitempty"`
	Options     map[string]string `json:"options,omitempty"`
	ScheduleID  *int64            `json:"schedule_id,omitempty"`
	Tags        []string          `json:"tags,omitempty"`
	Enabled     bool              `json:"enabled"`
	Status      string            `json:"status"`
	Progress    float64           `json:"progress"`
	HostsFound  int               `json:"hosts_found"`
	LastRun     *time.Time        `json:"last_run,omitempty"`
	NextRun     *time.Time        `json:"next_run,omitempty"`
	RunCount    int               `json:"run_count"`
	ErrorCount  int               `json:"error_count"`
	LastError   string            `json:"last_error,omitempty"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
	CreatedBy   string            `json:"created_by,omitempty"`
}

DiscoveryResponse represents a discovery job response.

type DiscoveryResult

type DiscoveryResult struct {
	ID           int64     `json:"id"`
	HostIP       string    `json:"host_ip"`
	Hostname     string    `json:"hostname,omitempty"`
	MACAddress   string    `json:"mac_address,omitempty"`
	ResponseTime float64   `json:"response_time_ms"`
	Method       string    `json:"method"`
	IsNew        bool      `json:"is_new"`
	FirstSeen    time.Time `json:"first_seen"`
	LastSeen     time.Time `json:"last_seen"`
}

DiscoveryResult represents an individual discovery result.

type DiscoveryResultsResponse

type DiscoveryResultsResponse struct {
	JobID       int64                  `json:"job_id"`
	TotalHosts  int                    `json:"total_hosts"`
	NewHosts    int                    `json:"new_hosts"`
	UpdatedAt   time.Time              `json:"updated_at"`
	Results     []DiscoveryResult      `json:"results"`
	Summary     map[string]interface{} `json:"summary"`
	GeneratedAt time.Time              `json:"generated_at"`
}

DiscoveryResultsResponse represents discovery results.

type DiscoveryStore added in v0.13.0

type DiscoveryStore interface {
	ListDiscoveryJobs(ctx context.Context, filters db.DiscoveryFilters, offset, limit int) (
		[]*db.DiscoveryJob, int64, error)
	CreateDiscoveryJob(ctx context.Context, input db.CreateDiscoveryJobInput) (*db.DiscoveryJob, error)
	GetDiscoveryJob(ctx context.Context, id uuid.UUID) (*db.DiscoveryJob, error)
	UpdateDiscoveryJob(ctx context.Context, id uuid.UUID, input db.UpdateDiscoveryJobInput) (*db.DiscoveryJob, error)
	DeleteDiscoveryJob(ctx context.Context, id uuid.UUID) error
	StartDiscoveryJob(ctx context.Context, id uuid.UUID) error
	StopDiscoveryJob(ctx context.Context, id uuid.UUID) error
}

DiscoveryStore is the subset of *db.DB used by DiscoveryHandler.

type DiscoveryUpdateMessage

type DiscoveryUpdateMessage struct {
	JobID      int64   `json:"job_id"`
	Status     string  `json:"status"`
	Progress   float64 `json:"progress"`
	Message    string  `json:"message,omitempty"`
	Error      string  `json:"error,omitempty"`
	HostsFound int     `json:"hosts_found,omitempty"`
	NewHosts   int     `json:"new_hosts,omitempty"`
}

DiscoveryUpdateMessage represents a discovery job status update.

type Duration

type Duration time.Duration

Duration is a custom type that can unmarshal duration strings from JSON

func NewDuration

func NewDuration(d time.Duration) Duration

NewDuration creates a Duration from time.Duration

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Duration

func (Duration) ToDuration

func (d Duration) ToDuration() time.Duration

ToDuration converts custom Duration to time.Duration

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for Duration

type ErrorResponse

type ErrorResponse struct {
	Error     string    `json:"error"`
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
	RequestID string    `json:"request_id,omitempty"`
}

ErrorResponse represents an API error response.

type HandlerManager

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

HandlerManager manages all API handlers and their dependencies.

func New

func New(database *db.DB, logger *slog.Logger, metricsManager *metrics.Registry) *HandlerManager

New creates a new handler manager with all handler groups initialized.

func (*HandlerManager) CreateDiscoveryJob

func (hm *HandlerManager) CreateDiscoveryJob(w http.ResponseWriter, r *http.Request)

CreateDiscoveryJob handles POST /api/v1/discovery - create a new discovery job.

func (*HandlerManager) CreateHost

func (hm *HandlerManager) CreateHost(w http.ResponseWriter, r *http.Request)

CreateHost handles POST /api/v1/hosts - create a new host.

func (*HandlerManager) CreateProfile

func (hm *HandlerManager) CreateProfile(w http.ResponseWriter, r *http.Request)

CreateProfile handles POST /api/v1/profiles - create a new profile.

func (*HandlerManager) CreateScan

func (hm *HandlerManager) CreateScan(w http.ResponseWriter, r *http.Request)

CreateScan handles POST /api/v1/scans - create a new scan.

func (*HandlerManager) CreateSchedule

func (hm *HandlerManager) CreateSchedule(w http.ResponseWriter, r *http.Request)

CreateSchedule handles POST /api/v1/schedules - create a new schedule.

func (*HandlerManager) DeleteDiscoveryJob

func (hm *HandlerManager) DeleteDiscoveryJob(w http.ResponseWriter, r *http.Request)

DeleteDiscoveryJob handles DELETE /api/v1/discovery/{id} - delete a discovery job.

func (*HandlerManager) DeleteHost

func (hm *HandlerManager) DeleteHost(w http.ResponseWriter, r *http.Request)

DeleteHost handles DELETE /api/v1/hosts/{id} - delete a host.

func (*HandlerManager) DeleteProfile

func (hm *HandlerManager) DeleteProfile(w http.ResponseWriter, r *http.Request)

DeleteProfile handles DELETE /api/v1/profiles/{id} - delete a profile.

func (*HandlerManager) DeleteScan

func (hm *HandlerManager) DeleteScan(w http.ResponseWriter, r *http.Request)

DeleteScan handles DELETE /api/v1/scans/{id} - delete a scan.

func (*HandlerManager) DeleteSchedule

func (hm *HandlerManager) DeleteSchedule(w http.ResponseWriter, r *http.Request)

DeleteSchedule handles DELETE /api/v1/schedules/{id} - delete a schedule.

func (*HandlerManager) DisableSchedule

func (hm *HandlerManager) DisableSchedule(w http.ResponseWriter, r *http.Request)

DisableSchedule handles POST /api/v1/schedules/{id}/disable - disable a schedule.

func (*HandlerManager) DiscoveryWebSocket

func (hm *HandlerManager) DiscoveryWebSocket(w http.ResponseWriter, r *http.Request)

DiscoveryWebSocket handles WebSocket connections for discovery updates.

func (*HandlerManager) EnableSchedule

func (hm *HandlerManager) EnableSchedule(w http.ResponseWriter, r *http.Request)

EnableSchedule handles POST /api/v1/schedules/{id}/enable - enable a schedule.

func (*HandlerManager) GeneralWebSocket added in v0.12.0

func (hm *HandlerManager) GeneralWebSocket(w http.ResponseWriter, r *http.Request)

GeneralWebSocket handles general WebSocket connections for all updates.

func (*HandlerManager) GetConfig

func (hm *HandlerManager) GetConfig(w http.ResponseWriter, r *http.Request)

GetConfig retrieves the current configuration.

func (*HandlerManager) GetDatabase

func (hm *HandlerManager) GetDatabase() *db.DB

GetDatabase returns the database instance.

func (*HandlerManager) GetDiscoveryJob

func (hm *HandlerManager) GetDiscoveryJob(w http.ResponseWriter, r *http.Request)

GetDiscoveryJob handles GET /api/v1/discovery/{id} - get a specific discovery job.

func (*HandlerManager) GetHost

func (hm *HandlerManager) GetHost(w http.ResponseWriter, r *http.Request)

GetHost handles GET /api/v1/hosts/{id} - get a specific host.

func (*HandlerManager) GetHostScans

func (hm *HandlerManager) GetHostScans(w http.ResponseWriter, r *http.Request)

GetHostScans handles GET /api/v1/hosts/{id}/scans - get scans for a host.

func (*HandlerManager) GetLogger

func (hm *HandlerManager) GetLogger() *slog.Logger

GetLogger returns the logger instance.

func (*HandlerManager) GetLogs

func (hm *HandlerManager) GetLogs(w http.ResponseWriter, r *http.Request)

GetLogs retrieves system logs.

func (*HandlerManager) GetMetrics

func (hm *HandlerManager) GetMetrics() *metrics.Registry

GetMetrics returns the metrics manager.

func (*HandlerManager) GetProfile

func (hm *HandlerManager) GetProfile(w http.ResponseWriter, r *http.Request)

GetProfile handles GET /api/v1/profiles/{id} - get a specific profile.

func (*HandlerManager) GetScan

func (hm *HandlerManager) GetScan(w http.ResponseWriter, r *http.Request)

GetScan handles GET /api/v1/scans/{id} - get a specific scan.

func (*HandlerManager) GetScanResults

func (hm *HandlerManager) GetScanResults(w http.ResponseWriter, r *http.Request)

GetScanResults handles GET /api/v1/scans/{id}/results - get scan results.

func (*HandlerManager) GetSchedule

func (hm *HandlerManager) GetSchedule(w http.ResponseWriter, r *http.Request)

GetSchedule handles GET /api/v1/schedules/{id} - get a specific schedule.

func (*HandlerManager) GetWorkerStatus

func (hm *HandlerManager) GetWorkerStatus(w http.ResponseWriter, r *http.Request)

GetWorkerStatus retrieves the status of workers.

func (*HandlerManager) Health

func (hm *HandlerManager) Health(w http.ResponseWriter, r *http.Request)

Health and status endpoints.

func (*HandlerManager) ListDiscoveryJobs

func (hm *HandlerManager) ListDiscoveryJobs(w http.ResponseWriter, r *http.Request)

ListDiscoveryJobs handles GET /api/v1/discovery - list all discovery jobs.

func (*HandlerManager) ListHosts

func (hm *HandlerManager) ListHosts(w http.ResponseWriter, r *http.Request)

ListHosts handles GET /api/v1/hosts - list all hosts.

func (*HandlerManager) ListProfiles

func (hm *HandlerManager) ListProfiles(w http.ResponseWriter, r *http.Request)

ListProfiles handles GET /api/v1/profiles - list all profiles.

func (*HandlerManager) ListScans

func (hm *HandlerManager) ListScans(w http.ResponseWriter, r *http.Request)

ListScans handles GET /api/v1/scans - list all scans.

func (*HandlerManager) ListSchedules

func (hm *HandlerManager) ListSchedules(w http.ResponseWriter, r *http.Request)

ListSchedules handles GET /api/v1/schedules - list all schedules.

func (*HandlerManager) Metrics

func (hm *HandlerManager) Metrics(w http.ResponseWriter, r *http.Request)

Metrics handles GET /metrics - get application metrics.

func (*HandlerManager) ScanWebSocket

func (hm *HandlerManager) ScanWebSocket(w http.ResponseWriter, r *http.Request)

ScanWebSocket handles WebSocket connections for scan updates.

func (*HandlerManager) SetScanQueue added in v0.13.0

func (hm *HandlerManager) SetScanQueue(q *scanning.ScanQueue)

SetScanQueue configures the scan execution queue and propagates it to the scan handler (for API-triggered scans) and the health handler (for status reporting). Pass nil to revert to the default fire-and-forget behavior.

func (*HandlerManager) StartDiscovery

func (hm *HandlerManager) StartDiscovery(w http.ResponseWriter, r *http.Request)

StartDiscovery handles POST /api/v1/discovery/{id}/start - start discovery.

func (*HandlerManager) StartScan

func (hm *HandlerManager) StartScan(w http.ResponseWriter, r *http.Request)

StartScan handles POST /api/v1/scans/{id}/start - start a scan.

func (*HandlerManager) Status

func (hm *HandlerManager) Status(w http.ResponseWriter, r *http.Request)

Status handles GET /status - get system status.

func (*HandlerManager) StopDiscovery

func (hm *HandlerManager) StopDiscovery(w http.ResponseWriter, r *http.Request)

StopDiscovery handles POST /api/v1/discovery/{id}/stop - stop discovery.

func (*HandlerManager) StopScan

func (hm *HandlerManager) StopScan(w http.ResponseWriter, r *http.Request)

StopScan handles POST /api/v1/scans/{id}/stop - stop a scan.

func (*HandlerManager) StopWorker

func (hm *HandlerManager) StopWorker(w http.ResponseWriter, r *http.Request)

StopWorker stops a specific worker.

func (*HandlerManager) UpdateConfig

func (hm *HandlerManager) UpdateConfig(w http.ResponseWriter, r *http.Request)

UpdateConfig updates the configuration.

func (*HandlerManager) UpdateDiscoveryJob

func (hm *HandlerManager) UpdateDiscoveryJob(w http.ResponseWriter, r *http.Request)

UpdateDiscoveryJob handles PUT /api/v1/discovery/{id} - update an existing discovery job.

func (*HandlerManager) UpdateHost

func (hm *HandlerManager) UpdateHost(w http.ResponseWriter, r *http.Request)

UpdateHost handles PUT /api/v1/hosts/{id} - update an existing host.

func (*HandlerManager) UpdateProfile

func (hm *HandlerManager) UpdateProfile(w http.ResponseWriter, r *http.Request)

UpdateProfile handles PUT /api/v1/profiles/{id} - update an existing profile.

func (*HandlerManager) UpdateScan

func (hm *HandlerManager) UpdateScan(w http.ResponseWriter, r *http.Request)

UpdateScan handles PUT /api/v1/scans/{id} - update an existing scan.

func (*HandlerManager) UpdateSchedule

func (hm *HandlerManager) UpdateSchedule(w http.ResponseWriter, r *http.Request)

UpdateSchedule handles PUT /api/v1/schedules/{id} - update an existing schedule.

func (*HandlerManager) Version

func (hm *HandlerManager) Version(w http.ResponseWriter, r *http.Request)

Version handles GET /version - get version information.

type HealthHandler

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

HealthHandler handles health check and status endpoints.

func NewHealthHandler

func NewHealthHandler(
	database DatabasePinger,
	logger *slog.Logger,
	metricsManager metrics.MetricsRegistry,
) *HealthHandler

NewHealthHandler creates a new health handler.

func (*HealthHandler) Health

func (h *HealthHandler) Health(w http.ResponseWriter, r *http.Request)

Health performs a basic health check.

func (*HealthHandler) Liveness

func (h *HealthHandler) Liveness(w http.ResponseWriter, r *http.Request)

Liveness performs a simple liveness check without dependencies.

func (*HealthHandler) Metrics

func (h *HealthHandler) Metrics(w http.ResponseWriter, r *http.Request)

Metrics provides metrics endpoint (Prometheus format).

func (*HealthHandler) SetScanQueue added in v0.13.0

func (h *HealthHandler) SetScanQueue(q *scanning.ScanQueue)

SetScanQueue sets the scan queue for health monitoring.

func (*HealthHandler) Status

func (h *HealthHandler) Status(w http.ResponseWriter, r *http.Request)

Status provides detailed system status information.

func (*HealthHandler) Version

func (h *HealthHandler) Version(w http.ResponseWriter, r *http.Request)

Version provides version information.

type HealthResponse

type HealthResponse struct {
	Status    string            `json:"status"`
	Timestamp time.Time         `json:"timestamp"`
	Uptime    string            `json:"uptime"`
	Checks    map[string]string `json:"checks"`
}

HealthResponse represents a health check response.

type HostHandler

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

HostHandler handles host-related API endpoints.

func NewHostHandler

func NewHostHandler(database HostStore, logger *slog.Logger, metricsManager *metrics.Registry) *HostHandler

NewHostHandler creates a new host handler.

func (*HostHandler) CreateHost

func (h *HostHandler) CreateHost(w http.ResponseWriter, r *http.Request)

CreateHost handles POST /api/v1/hosts - create a new host.

func (*HostHandler) DeleteHost

func (h *HostHandler) DeleteHost(w http.ResponseWriter, r *http.Request)

DeleteHost handles DELETE /api/v1/hosts/{id} - delete a host.

func (*HostHandler) GetHost

func (h *HostHandler) GetHost(w http.ResponseWriter, r *http.Request)

GetHost handles GET /api/v1/hosts/{id} - get a specific host.

func (*HostHandler) GetHostScans

func (h *HostHandler) GetHostScans(w http.ResponseWriter, r *http.Request)

GetHostScans handles GET /api/v1/hosts/{id}/scans - get scans for a specific host.

func (*HostHandler) ListHosts

func (h *HostHandler) ListHosts(w http.ResponseWriter, r *http.Request)

ListHosts handles GET /api/v1/hosts - list all hosts with pagination.

func (*HostHandler) UpdateHost

func (h *HostHandler) UpdateHost(w http.ResponseWriter, r *http.Request)

UpdateHost handles PUT /api/v1/hosts/{id} - update a host.

type HostRequest

type HostRequest struct {
	IP          string            `json:"ip_address" validate:"required,ip"`
	Hostname    string            `json:"hostname,omitempty"`
	Description string            `json:"description,omitempty"`
	OS          string            `json:"os,omitempty"`
	OSVersion   string            `json:"os_version,omitempty"`
	Tags        []string          `json:"tags,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	Active      bool              `json:"active"`
}

HostRequest represents a host creation/update request.

type HostResponse

type HostResponse struct {
	ID          string `json:"id"`
	IPAddress   string `json:"ip_address"`
	Hostname    string `json:"hostname,omitempty"`
	Description string `json:"description,omitempty"`
	// Deprecated: use OSFamily instead.
	OS string `json:"os,omitempty"`
	// Deprecated: use OSName / OSVersion instead.
	OSVersionLegacy string `json:"os_version,omitempty"`
	// OSFamily is the broad OS family detected by nmap (e.g. "Linux", "Windows").
	OSFamily string `json:"os_family,omitempty"`
	// OSName is the full OS name returned by nmap (e.g. "Linux 5.15").
	OSName string `json:"os_name,omitempty"`
	// OSVersion is the OS generation / version string returned by nmap.
	OSVersion string `json:"os_version_detail,omitempty"`
	// OSConfidence is the nmap detection confidence percentage (0–100).
	OSConfidence *int              `json:"os_confidence,omitempty"`
	Tags         []string          `json:"tags,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	Status       string            `json:"status"`
	MACAddress   string            `json:"mac_address,omitempty"`
	Ports        []db.PortInfo     `json:"ports,omitempty"`
	FirstSeen    time.Time         `json:"first_seen"`
	LastSeen     *time.Time        `json:"last_seen,omitempty"`
	LastScanID   *int64            `json:"last_scan_id,omitempty"`
	ScanCount    int               `json:"scan_count"`
	TotalPorts   int               `json:"total_ports"`
	CreatedAt    time.Time         `json:"created_at"`
	UpdatedAt    time.Time         `json:"updated_at"`
	DiscoveredBy string            `json:"discovered_by,omitempty"`
}

HostResponse represents a host response.

type HostScanResponse

type HostScanResponse struct {
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	ScanType  string     `json:"scan_type"`
	Ports     string     `json:"ports,omitempty"`
	Targets   []string   `json:"targets,omitempty"`
	Status    string     `json:"status"`
	Progress  float64    `json:"progress"`
	StartTime *time.Time `json:"start_time,omitempty"`
	EndTime   *time.Time `json:"end_time,omitempty"`
	Duration  *string    `json:"duration,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
}

HostScanResponse represents a scan associated with a host.

type HostStore added in v0.13.0

type HostStore interface {
	ListHosts(ctx context.Context, filters *db.HostFilters, offset, limit int) ([]*db.Host, int64, error)
	CreateHost(ctx context.Context, input db.CreateHostInput) (*db.Host, error)
	GetHost(ctx context.Context, id uuid.UUID) (*db.Host, error)
	UpdateHost(ctx context.Context, id uuid.UUID, input db.UpdateHostInput) (*db.Host, error)
	DeleteHost(ctx context.Context, id uuid.UUID) error
	GetHostScans(ctx context.Context, hostID uuid.UUID, offset, limit int) ([]*db.Scan, int64, error)
}

HostStore is the subset of *db.DB used by HostHandler.

type JobControlOperation

type JobControlOperation struct {
	EntityType string
	Logger     *slog.Logger
	Metrics    metrics.MetricsRegistry
}

JobControlOperation is a job control operation pattern for start/stop operations.

func (*JobControlOperation) ExecuteStart

func (op *JobControlOperation) ExecuteStart(
	w http.ResponseWriter,
	r *http.Request,
	id uuid.UUID,
	startInDB func(context.Context, uuid.UUID) error,
	getFromDB func(context.Context, uuid.UUID) (interface{}, error),
	toResponse func(interface{}) interface{},
	metricName string,
)

ExecuteStart performs a generic start operation.

func (*JobControlOperation) ExecuteStop

func (op *JobControlOperation) ExecuteStop(
	w http.ResponseWriter,
	r *http.Request,
	id uuid.UUID,
	stopInDB func(context.Context, uuid.UUID) error,
	metricName string,
)

ExecuteStop performs a generic stop operation.

type JobInfo

type JobInfo struct {
	ID        string        `json:"id"`
	Type      string        `json:"type"`
	Target    string        `json:"target,omitempty"`
	StartTime time.Time     `json:"start_time"`
	Duration  time.Duration `json:"duration"`
	Progress  float64       `json:"progress"`
}

JobInfo represents current job information.

type ListOperation

type ListOperation[T any, F any] struct {
	EntityType string
	MetricName string
	Logger     *slog.Logger
	Metrics    metrics.MetricsRegistry
	GetFilters func(*http.Request) F
	ListFromDB func(context.Context, F, int, int) ([]T, int64, error)
	ToResponse func(T) interface{}
}

ListOperation is a generic list operation pattern.

func (*ListOperation[T, F]) Execute

func (op *ListOperation[T, F]) Execute(w http.ResponseWriter, r *http.Request)

Execute performs a generic list operation.

type LivenessResponse

type LivenessResponse struct {
	Status    string    `json:"status"`
	Timestamp time.Time `json:"timestamp"`
	Uptime    string    `json:"uptime"`
}

LivenessResponse represents a simple liveness check response.

type LogEntry

type LogEntry struct {
	Timestamp time.Time              `json:"timestamp"`
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Component string                 `json:"component,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
	Error     string                 `json:"error,omitempty"`
}

LogEntry represents a single log entry.

type LoggingConfigUpdate

type LoggingConfigUpdate struct {
	Level          *string `json:"level,omitempty" validate:"omitempty,oneof=debug info warn error"`
	Format         *string `json:"format,omitempty" validate:"omitempty,oneof=text json"`
	Output         *string `json:"output,omitempty" validate:"omitempty,min=1,max=255"`
	Structured     *bool   `json:"structured,omitempty"`
	RequestLogging *bool   `json:"request_logging,omitempty"`
}

LoggingConfigUpdate represents updatable logging configuration fields.

type LogsResponse

type LogsResponse struct {
	Lines       []LogEntry `json:"lines"`
	TotalLines  int        `json:"total_lines"`
	StartLine   int        `json:"start_line"`
	EndLine     int        `json:"end_line"`
	HasMore     bool       `json:"has_more"`
	GeneratedAt time.Time  `json:"generated_at"`
}

LogsResponse represents log retrieval response.

type MemoryInfo

type MemoryInfo struct {
	Allocated   uint64 `json:"allocated_bytes"`
	TotalAlloc  uint64 `json:"total_alloc_bytes"`
	System      uint64 `json:"system_bytes"`
	GCCycles    uint32 `json:"gc_cycles"`
	LastGC      string `json:"last_gc"`
	HeapObjects uint64 `json:"heap_objects"`
}

MemoryInfo contains memory usage information.

type MetricsInfo

type MetricsInfo struct {
	Enabled       bool                   `json:"enabled"`
	TotalCounters int                    `json:"total_counters"`
	TotalGauges   int                    `json:"total_gauges"`
	TotalHistos   int                    `json:"total_histograms"`
	LastUpdated   time.Time              `json:"last_updated"`
	Summary       map[string]interface{} `json:"summary,omitempty"`
}

MetricsInfo contains metrics system information.

type NetworkHandler added in v0.8.0

type NetworkHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

NetworkHandler handles network-related API requests.

func NewNetworkHandler added in v0.8.0

func NewNetworkHandler(
	service NetworkServicer, logger *slog.Logger, metricsRegistry metrics.MetricsRegistry,
) *NetworkHandler

NewNetworkHandler creates a new network handler.

func (*NetworkHandler) CreateGlobalExclusion added in v0.8.0

func (h *NetworkHandler) CreateGlobalExclusion(w http.ResponseWriter, r *http.Request)

CreateGlobalExclusion handles POST /api/v1/exclusions.

func (*NetworkHandler) CreateNetwork added in v0.8.0

func (h *NetworkHandler) CreateNetwork(w http.ResponseWriter, r *http.Request)

CreateNetwork handles POST /api/v1/networks.

func (*NetworkHandler) CreateNetworkExclusion added in v0.8.0

func (h *NetworkHandler) CreateNetworkExclusion(w http.ResponseWriter, r *http.Request)

CreateNetworkExclusion handles POST /api/v1/networks/{id}/exclusions.

func (*NetworkHandler) DeleteExclusion added in v0.8.0

func (h *NetworkHandler) DeleteExclusion(w http.ResponseWriter, r *http.Request)

DeleteExclusion handles DELETE /api/v1/exclusions/{id}.

func (*NetworkHandler) DeleteNetwork added in v0.8.0

func (h *NetworkHandler) DeleteNetwork(w http.ResponseWriter, r *http.Request)

DeleteNetwork handles DELETE /api/v1/networks/{id}.

func (*NetworkHandler) DisableNetwork added in v0.8.0

func (h *NetworkHandler) DisableNetwork(w http.ResponseWriter, r *http.Request)

DisableNetwork handles POST /api/v1/networks/{id}/disable.

func (*NetworkHandler) EnableNetwork added in v0.8.0

func (h *NetworkHandler) EnableNetwork(w http.ResponseWriter, r *http.Request)

EnableNetwork handles POST /api/v1/networks/{id}/enable.

func (*NetworkHandler) GetNetwork added in v0.8.0

func (h *NetworkHandler) GetNetwork(w http.ResponseWriter, r *http.Request)

GetNetwork handles GET /api/v1/networks/{id}.

func (*NetworkHandler) GetNetworkStats added in v0.8.0

func (h *NetworkHandler) GetNetworkStats(w http.ResponseWriter, r *http.Request)

GetNetworkStats handles GET /api/v1/networks/stats.

func (*NetworkHandler) ListGlobalExclusions added in v0.8.0

func (h *NetworkHandler) ListGlobalExclusions(w http.ResponseWriter, r *http.Request)

ListGlobalExclusions handles GET /api/v1/exclusions.

func (*NetworkHandler) ListNetworkExclusions added in v0.8.0

func (h *NetworkHandler) ListNetworkExclusions(w http.ResponseWriter, r *http.Request)

ListNetworkExclusions handles GET /api/v1/networks/{id}/exclusions.

func (*NetworkHandler) ListNetworks added in v0.8.0

func (h *NetworkHandler) ListNetworks(w http.ResponseWriter, r *http.Request)

ListNetworks handles GET /api/v1/networks.

func (*NetworkHandler) RenameNetwork added in v0.8.0

func (h *NetworkHandler) RenameNetwork(w http.ResponseWriter, r *http.Request)

RenameNetwork handles PUT /api/v1/networks/{id}/rename.

func (*NetworkHandler) UpdateNetwork added in v0.8.0

func (h *NetworkHandler) UpdateNetwork(w http.ResponseWriter, r *http.Request)

UpdateNetwork handles PUT /api/v1/networks/{id}.

type NetworkServicer added in v0.13.0

type NetworkServicer interface {
	ListNetworks(ctx context.Context, activeOnly bool) ([]*db.Network, error)
	GetNetworkByID(ctx context.Context, id uuid.UUID) (*services.NetworkWithExclusions, error)
	CreateNetwork(
		ctx context.Context, name, cidr, description, method string, active, scanEnabled bool,
	) (*db.Network, error)
	UpdateNetwork(
		ctx context.Context, id uuid.UUID, name, cidr, description, method string, active bool,
	) (*db.Network, error)
	DeleteNetwork(ctx context.Context, id uuid.UUID) error
	AddExclusion(ctx context.Context, networkID *uuid.UUID, cidr, reason string) (*db.NetworkExclusion, error)
	RemoveExclusion(ctx context.Context, exclusionID uuid.UUID) error
	GetNetworkExclusions(ctx context.Context, networkID uuid.UUID) ([]*db.NetworkExclusion, error)
	GetGlobalExclusions(ctx context.Context) ([]*db.NetworkExclusion, error)
	GetNetworkStats(ctx context.Context) (map[string]interface{}, error)
}

NetworkServicer is the subset of *services.NetworkService used by NetworkHandler.

type NetworkStatsResponse added in v0.8.0

type NetworkStatsResponse struct {
	Networks   map[string]interface{} `json:"networks"`
	Hosts      map[string]interface{} `json:"hosts"`
	Exclusions map[string]interface{} `json:"exclusions"`
}

NetworkStatsResponse is the response body for network statistics.

type PaginatedResponse

type PaginatedResponse struct {
	Data       interface{} `json:"data"`
	Pagination struct {
		Page       int   `json:"page"`
		PageSize   int   `json:"page_size"`
		TotalItems int64 `json:"total_items"`
		TotalPages int   `json:"total_pages"`
	} `json:"pagination"`
}

PaginatedResponse represents a paginated API response.

type PaginationParams

type PaginationParams struct {
	Page     int `json:"page"`
	PageSize int `json:"page_size"`
	Offset   int `json:"offset"`
}

PaginationParams holds pagination parameters.

type ProfileHandler

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

ProfileHandler handles profile-related API endpoints.

func NewProfileHandler

func NewProfileHandler(database ProfileStore, logger *slog.Logger, metricsManager *metrics.Registry) *ProfileHandler

NewProfileHandler creates a new profile handler.

func (*ProfileHandler) CreateProfile

func (h *ProfileHandler) CreateProfile(w http.ResponseWriter, r *http.Request)

CreateProfile handles POST /api/v1/profiles - create a new profile.

func (*ProfileHandler) DeleteProfile

func (h *ProfileHandler) DeleteProfile(w http.ResponseWriter, r *http.Request)

DeleteProfile handles DELETE /api/v1/profiles/{id} - delete a profile.

func (*ProfileHandler) GetProfile

func (h *ProfileHandler) GetProfile(w http.ResponseWriter, r *http.Request)

GetProfile handles GET /api/v1/profiles/{id} - get a specific profile.

func (*ProfileHandler) ListProfiles

func (h *ProfileHandler) ListProfiles(w http.ResponseWriter, r *http.Request)

ListProfiles handles GET /api/v1/profiles - list all profiles with pagination.

func (*ProfileHandler) UpdateProfile

func (h *ProfileHandler) UpdateProfile(w http.ResponseWriter, r *http.Request)

UpdateProfile handles PUT /api/v1/profiles/{id} - update a profile.

type ProfileRequest

type ProfileRequest struct {
	Name        string `json:"name" validate:"required,min=1,max=255"`
	Description string `json:"description,omitempty"`
	// ScanType supports: connect, syn, ack, aggressive, comprehensive
	ScanType         string            `json:"scan_type" validate:"required"`
	Ports            string            `json:"ports,omitempty"`
	Options          map[string]string `json:"options,omitempty"`
	Timing           TimingProfile     `json:"timing,omitempty"`
	ServiceDetection bool              `json:"service_detection"`
	OSDetection      bool              `json:"os_detection"`
	ScriptScan       bool              `json:"script_scan"`
	UDPScan          bool              `json:"udp_scan"`
	MaxRetries       int               `json:"max_retries,omitempty"`
	HostTimeout      Duration          `json:"host_timeout,omitempty"`
	ScanDelay        Duration          `json:"scan_delay,omitempty"`
	MaxRatePPS       int               `json:"max_rate_pps,omitempty"`
	MaxHostGroupSize int               `json:"max_host_group_size,omitempty"`
	MinHostGroupSize int               `json:"min_host_group_size,omitempty"`
	Tags             []string          `json:"tags,omitempty"`
	Default          bool              `json:"default"`
}

ProfileRequest represents a profile creation/update request.

type ProfileResponse

type ProfileResponse struct {
	ID               string            `json:"id"`
	Name             string            `json:"name"`
	Description      string            `json:"description,omitempty"`
	ScanType         string            `json:"scan_type"`
	Ports            string            `json:"ports,omitempty"`
	Options          map[string]string `json:"options,omitempty"`
	Timing           TimingProfile     `json:"timing,omitempty"`
	ServiceDetection bool              `json:"service_detection"`
	OSDetection      bool              `json:"os_detection"`
	ScriptScan       bool              `json:"script_scan"`
	UDPScan          bool              `json:"udp_scan"`
	MaxRetries       int               `json:"max_retries,omitempty"`
	HostTimeout      time.Duration     `json:"host_timeout,omitempty"`
	ScanDelay        time.Duration     `json:"scan_delay,omitempty"`
	MaxRatePPS       int               `json:"max_rate_pps,omitempty"`
	MaxHostGroupSize int               `json:"max_host_group_size,omitempty"`
	MinHostGroupSize int               `json:"min_host_group_size,omitempty"`
	Tags             []string          `json:"tags,omitempty"`
	Default          bool              `json:"default"`
	UsageCount       int               `json:"usage_count"`
	LastUsed         *time.Time        `json:"last_used,omitempty"`
	CreatedAt        time.Time         `json:"created_at"`
	UpdatedAt        time.Time         `json:"updated_at"`
	CreatedBy        string            `json:"created_by,omitempty"`
}

ProfileResponse represents a profile response.

type ProfileStore added in v0.13.0

type ProfileStore interface {
	ListProfiles(ctx context.Context, filters db.ProfileFilters, offset, limit int) ([]*db.ScanProfile, int64, error)
	CreateProfile(ctx context.Context, input db.CreateProfileInput) (*db.ScanProfile, error)
	GetProfile(ctx context.Context, id string) (*db.ScanProfile, error)
	UpdateProfile(ctx context.Context, id string, input db.UpdateProfileInput) (*db.ScanProfile, error)
	DeleteProfile(ctx context.Context, id string) error
}

ProfileStore is the subset of *db.DB used by ProfileHandler.

type RenameNetworkRequest added in v0.8.0

type RenameNetworkRequest struct {
	NewName string `json:"new_name" validate:"required,min=1,max=100"`
}

RenameNetworkRequest represents the request body for renaming a network.

type ScanHandler

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

ScanHandler handles scan-related API endpoints.

func NewScanHandler

func NewScanHandler(database ScanStore, logger *slog.Logger, metricsManager *metrics.Registry) *ScanHandler

NewScanHandler creates a new scan handler.

func (*ScanHandler) CreateScan

func (h *ScanHandler) CreateScan(w http.ResponseWriter, r *http.Request)

CreateScan handles POST /api/v1/scans - create a new scan.

func (*ScanHandler) DeleteScan

func (h *ScanHandler) DeleteScan(w http.ResponseWriter, r *http.Request)

DeleteScan handles DELETE /api/v1/scans/{id} - delete a scan.

func (*ScanHandler) GetScan

func (h *ScanHandler) GetScan(w http.ResponseWriter, r *http.Request)

GetScan handles GET /api/v1/scans/{id} - get a specific scan.

func (*ScanHandler) GetScanResults

func (h *ScanHandler) GetScanResults(w http.ResponseWriter, r *http.Request)

GetScanResults handles GET /api/v1/scans/{id}/results - get scan results.

func (*ScanHandler) ListScans

func (h *ScanHandler) ListScans(w http.ResponseWriter, r *http.Request)

ListScans handles GET /api/v1/scans - list all scans with pagination. ListScans handles GET /api/v1/scans - list scans with filtering and pagination.

func (*ScanHandler) SetScanQueue added in v0.13.0

func (h *ScanHandler) SetScanQueue(q *scanning.ScanQueue)

SetScanQueue configures an optional scan execution queue. When set, StartScan submits work to the queue instead of spawning an unbounded goroutine.

func (*ScanHandler) StartScan

func (h *ScanHandler) StartScan(w http.ResponseWriter, r *http.Request)

StartScan handles POST /api/v1/scans/{id}/start - start scan execution.

func (*ScanHandler) StopScan

func (h *ScanHandler) StopScan(w http.ResponseWriter, r *http.Request)

StopScan handles POST /api/v1/scans/{id}/stop - stop scan execution.

func (*ScanHandler) UpdateScan

func (h *ScanHandler) UpdateScan(w http.ResponseWriter, r *http.Request)

UpdateScan handles PUT /api/v1/scans/{id} - update a scan.

func (*ScanHandler) WithScanMode added in v0.14.0

func (h *ScanHandler) WithScanMode(mode string) *ScanHandler

WithScanMode sets the fallback scan mode used when a scan record does not carry an explicit ScanType. The sentinel default "connect" is applied last so callers may pass an empty string safely.

type ScanQueueInfo added in v0.13.0

type ScanQueueInfo struct {
	Configured     bool  `json:"configured"`
	QueueDepth     int   `json:"queue_depth"`
	ActiveScans    int   `json:"active_scans"`
	MaxConcurrent  int   `json:"max_concurrent"`
	MaxQueueSize   int   `json:"max_queue_size"`
	TotalSubmitted int64 `json:"total_submitted"`
	TotalCompleted int64 `json:"total_completed"`
	TotalRejected  int64 `json:"total_rejected"`
	TotalFailed    int64 `json:"total_failed"`
}

ScanQueueInfo contains scan queue status information.

type ScanRequest

type ScanRequest struct {
	Name        string            `json:"name" validate:"required,min=1,max=255"`
	Description string            `json:"description,omitempty"`
	Targets     []string          `json:"targets" validate:"required,min=1"`
	ScanType    string            `json:"scan_type" validate:"required,oneof=connect syn ack udp aggressive comprehensive"` //nolint:lll
	OSDetection bool              `json:"os_detection,omitempty"`
	Ports       string            `json:"ports,omitempty"`
	ProfileID   *string           `json:"profile_id,omitempty"`
	Options     map[string]string `json:"options,omitempty"`
	ScheduleID  *int64            `json:"schedule_id,omitempty"`
	Tags        []string          `json:"tags,omitempty"`
}

ScanRequest represents a scan creation/update request.

type ScanResponse

type ScanResponse struct {
	ID           uuid.UUID         `json:"id"`
	Name         string            `json:"name"`
	Description  string            `json:"description,omitempty"`
	Targets      []string          `json:"targets"`
	ScanType     string            `json:"scan_type"`
	Ports        string            `json:"ports,omitempty"`
	ProfileID    *string           `json:"profile_id,omitempty"`
	Options      map[string]string `json:"options,omitempty"`
	ScheduleID   *int64            `json:"schedule_id,omitempty"`
	Tags         []string          `json:"tags,omitempty"`
	Status       string            `json:"status"`
	Progress     float64           `json:"progress"`
	StartTime    *time.Time        `json:"started_at,omitempty"`
	EndTime      *time.Time        `json:"completed_at,omitempty"`
	Duration     *string           `json:"duration,omitempty"`
	CreatedAt    time.Time         `json:"created_at"`
	UpdatedAt    time.Time         `json:"updated_at"`
	CreatedBy    string            `json:"created_by,omitempty"`
	ErrorMessage *string           `json:"error_message,omitempty"`
	PortsScanned *string           `json:"ports_scanned,omitempty"`
}

ScanResponse represents a scan response.

type ScanResult

type ScanResult struct {
	ID           uuid.UUID `json:"id"`
	HostIP       string    `json:"host_ip"`
	Hostname     string    `json:"hostname,omitempty"`
	Port         int       `json:"port"`
	Protocol     string    `json:"protocol"`
	State        string    `json:"state"`
	Service      string    `json:"service,omitempty"`
	Version      string    `json:"version,omitempty"`
	Banner       string    `json:"banner,omitempty"`
	ScanTime     time.Time `json:"scan_time"`
	OSName       string    `json:"os_name,omitempty"`
	OSFamily     string    `json:"os_family,omitempty"`
	OSVersion    string    `json:"os_version,omitempty"`
	OSConfidence *int      `json:"os_confidence,omitempty"`
}

ScanResult represents an individual scan result.

type ScanResultsResponse

type ScanResultsResponse struct {
	ScanID      uuid.UUID       `json:"scan_id"`
	TotalHosts  int             `json:"total_hosts"`
	TotalPorts  int             `json:"total_ports"`
	OpenPorts   int             `json:"open_ports"`
	ClosedPorts int             `json:"closed_ports"`
	Results     []ScanResult    `json:"results"`
	Summary     *db.ScanSummary `json:"summary"`
	GeneratedAt time.Time       `json:"generated_at"`
}

ScanResultsResponse represents scan results.

type ScanStore added in v0.13.0

type ScanStore interface {
	ListScans(ctx context.Context, filters db.ScanFilters, offset, limit int) ([]*db.Scan, int64, error)
	CreateScan(ctx context.Context, input db.CreateScanInput) (*db.Scan, error)
	GetScan(ctx context.Context, id uuid.UUID) (*db.Scan, error)
	UpdateScan(ctx context.Context, id uuid.UUID, input db.UpdateScanInput) (*db.Scan, error)
	DeleteScan(ctx context.Context, id uuid.UUID) error
	StartScan(ctx context.Context, id uuid.UUID) error
	CompleteScan(ctx context.Context, id uuid.UUID) error
	StopScan(ctx context.Context, id uuid.UUID, errMsg ...string) error
	GetScanResults(ctx context.Context, scanID uuid.UUID, offset, limit int) ([]*db.ScanResult, int64, error)
	GetScanSummary(ctx context.Context, scanID uuid.UUID) (*db.ScanSummary, error)
	GetProfile(ctx context.Context, id string) (*db.ScanProfile, error)
}

ScanStore is the subset of *db.DB used by ScanHandler.

type ScanUpdateMessage

type ScanUpdateMessage struct {
	ScanID       int64      `json:"scan_id"`
	Status       string     `json:"status"`
	Progress     float64    `json:"progress"`
	Message      string     `json:"message,omitempty"`
	Error        string     `json:"error,omitempty"`
	StartTime    *time.Time `json:"start_time,omitempty"`
	EndTime      *time.Time `json:"end_time,omitempty"`
	ResultsCount int        `json:"results_count,omitempty"`
}

ScanUpdateMessage represents a scan status update.

type ScanningConfigUpdate

type ScanningConfigUpdate struct {
	WorkerPoolSize         *int    `json:"worker_pool_size,omitempty" validate:"omitempty,min=1,max=1000"`
	DefaultInterval        *string `json:"default_interval,omitempty"`
	MaxScanTimeout         *string `json:"max_scan_timeout,omitempty"`
	DefaultPorts           *string `json:"default_ports,omitempty" validate:"omitempty,max=1000"`
	ScanMode               *string `json:"scan_mode,omitempty" validate:"omitempty,oneof=connect syn ack udp aggressive comprehensive"` //nolint:lll
	MaxConcurrentTargets   *int    `json:"max_concurrent_targets,omitempty" validate:"omitempty,min=1,max=10000"`
	EnableServiceDetection *bool   `json:"enable_service_detection,omitempty"`
	EnableOSDetection      *bool   `json:"enable_os_detection,omitempty"`
}

ScanningConfigUpdate represents updatable scanning configuration fields.

type ScheduleHandler

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

ScheduleHandler handles schedule-related API endpoints.

func NewScheduleHandler

func NewScheduleHandler(
	database ScheduleStore, logger *slog.Logger, metricsManager *metrics.Registry,
) *ScheduleHandler

NewScheduleHandler creates a new schedule handler.

func (*ScheduleHandler) CreateSchedule

func (h *ScheduleHandler) CreateSchedule(w http.ResponseWriter, r *http.Request)

CreateSchedule handles POST /api/v1/schedules - create a new schedule.

func (*ScheduleHandler) DeleteSchedule

func (h *ScheduleHandler) DeleteSchedule(w http.ResponseWriter, r *http.Request)

DeleteSchedule handles DELETE /api/v1/schedules/{id} - delete a schedule.

func (*ScheduleHandler) DisableSchedule

func (h *ScheduleHandler) DisableSchedule(w http.ResponseWriter, r *http.Request)

DisableSchedule handles POST /api/v1/schedules/{id}/disable - disable a schedule.

func (*ScheduleHandler) EnableSchedule

func (h *ScheduleHandler) EnableSchedule(w http.ResponseWriter, r *http.Request)

EnableSchedule handles POST /api/v1/schedules/{id}/enable - enable a schedule.

func (*ScheduleHandler) GetSchedule

func (h *ScheduleHandler) GetSchedule(w http.ResponseWriter, r *http.Request)

GetSchedule handles GET /api/v1/schedules/{id} - get a specific schedule.

func (*ScheduleHandler) ListSchedules

func (h *ScheduleHandler) ListSchedules(w http.ResponseWriter, r *http.Request)

ListSchedules handles GET /api/v1/schedules - list all schedules with pagination.

func (*ScheduleHandler) UpdateSchedule

func (h *ScheduleHandler) UpdateSchedule(w http.ResponseWriter, r *http.Request)

UpdateSchedule handles PUT /api/v1/schedules/{id} - update a schedule.

type ScheduleRequest

type ScheduleRequest struct {
	Name         string            `json:"name" validate:"required,min=1,max=255"`
	Description  string            `json:"description,omitempty"`
	CronExpr     string            `json:"cron_expr" validate:"required"`
	Type         string            `json:"type" validate:"required,oneof=scan discovery"`
	NetworkID    uuid.UUID         `json:"network_id" validate:"required"`
	Enabled      bool              `json:"enabled"`
	MaxRunTime   time.Duration     `json:"max_run_time,omitempty"`
	RetryOnError bool              `json:"retry_on_error"`
	MaxRetries   int               `json:"max_retries,omitempty"`
	RetryDelay   time.Duration     `json:"retry_delay,omitempty"`
	Options      map[string]string `json:"options,omitempty"`
	Tags         []string          `json:"tags,omitempty"`
	NotifyOnFail bool              `json:"notify_on_fail"`
	NotifyEmails []string          `json:"notify_emails,omitempty"`
}

ScheduleRequest represents a schedule creation/update request.

type ScheduleResponse

type ScheduleResponse struct {
	ID           uuid.UUID         `json:"id"`
	Name         string            `json:"name"`
	Description  string            `json:"description,omitempty"`
	CronExpr     string            `json:"cron_expr"`
	Type         string            `json:"type"`
	NetworkID    string            `json:"network_id,omitempty"`
	NetworkName  string            `json:"network_name,omitempty"`
	Enabled      bool              `json:"enabled"`
	MaxRunTime   time.Duration     `json:"max_run_time,omitempty"`
	RetryOnError bool              `json:"retry_on_error"`
	MaxRetries   int               `json:"max_retries,omitempty"`
	RetryDelay   time.Duration     `json:"retry_delay,omitempty"`
	Options      map[string]string `json:"options,omitempty"`
	Tags         []string          `json:"tags,omitempty"`
	NotifyOnFail bool              `json:"notify_on_fail"`
	NotifyEmails []string          `json:"notify_emails,omitempty"`
	Status       string            `json:"status"`
	LastRun      *time.Time        `json:"last_run,omitempty"`
	NextRun      *time.Time        `json:"next_run,omitempty"`
	RunCount     int               `json:"run_count"`
	SuccessCount int               `json:"success_count"`
	ErrorCount   int               `json:"error_count"`
	LastError    string            `json:"last_error,omitempty"`
	LastDuration *time.Duration    `json:"last_duration,omitempty"`
	AvgDuration  *time.Duration    `json:"avg_duration,omitempty"`
	CreatedAt    time.Time         `json:"created_at"`
	UpdatedAt    time.Time         `json:"updated_at"`
	CreatedBy    string            `json:"created_by,omitempty"`
}

ScheduleResponse represents a schedule response.

type ScheduleStore added in v0.13.0

type ScheduleStore interface {
	ListSchedules(ctx context.Context, filters db.ScheduleFilters, offset, limit int) ([]*db.Schedule, int64, error)
	CreateSchedule(ctx context.Context, input db.CreateScheduleInput) (*db.Schedule, error)
	GetSchedule(ctx context.Context, id uuid.UUID) (*db.Schedule, error)
	UpdateSchedule(ctx context.Context, id uuid.UUID, input db.UpdateScheduleInput) (*db.Schedule, error)
	DeleteSchedule(ctx context.Context, id uuid.UUID) error
	EnableSchedule(ctx context.Context, id uuid.UUID) error
	DisableSchedule(ctx context.Context, id uuid.UUID) error
}

ScheduleStore is the subset of *db.DB used by ScheduleHandler.

type ServiceInfo

type ServiceInfo struct {
	Name      string    `json:"name"`
	Version   string    `json:"version"`
	StartTime time.Time `json:"start_time"`
	Uptime    string    `json:"uptime"`
	PID       int       `json:"pid"`
}

ServiceInfo contains service-related information.

type StatusResponse

type StatusResponse struct {
	Service   ServiceInfo    `json:"service"`
	System    SystemInfo     `json:"system"`
	Database  DatabaseInfo   `json:"database"`
	Metrics   MetricsInfo    `json:"metrics"`
	ScanQueue ScanQueueInfo  `json:"scan_queue"`
	Health    HealthResponse `json:"health"`
	Timestamp time.Time      `json:"timestamp"`
}

StatusResponse represents a detailed status response.

type SystemInfo

type SystemInfo struct {
	OS           string            `json:"os"`
	Architecture string            `json:"architecture"`
	CPUs         int               `json:"cpus"`
	GoVersion    string            `json:"go_version"`
	Memory       MemoryInfo        `json:"memory"`
	Goroutines   int               `json:"goroutines"`
	Environment  map[string]string `json:"environment,omitempty"`
}

SystemInfo contains system-related information.

type TimingProfile

type TimingProfile struct {
	Template          string   `json:"template,omitempty"` // paranoid, sneaky, polite, normal, aggressive, insane
	MinRTTTimeout     Duration `json:"min_rtt_timeout,omitempty"`
	MaxRTTTimeout     Duration `json:"max_rtt_timeout,omitempty"`
	InitialRTTTimeout Duration `json:"initial_rtt_timeout,omitempty"`
	MaxRetries        int      `json:"max_retries,omitempty"`
	HostTimeout       Duration `json:"host_timeout,omitempty"`
	ScanDelay         Duration `json:"scan_delay,omitempty"`
	MaxScanDelay      Duration `json:"max_scan_delay,omitempty"`
}

TimingProfile represents timing configuration for scans.

type UpdateNetworkRequest added in v0.8.0

type UpdateNetworkRequest struct {
	Name            *string `json:"name,omitempty"             validate:"omitempty,min=1,max=100"`
	CIDR            *string `json:"cidr,omitempty"             validate:"omitempty,cidr"`
	Description     *string `json:"description,omitempty"`
	DiscoveryMethod *string `json:"discovery_method,omitempty" validate:"omitempty,oneof=ping tcp arp"`
	IsActive        *bool   `json:"is_active,omitempty"`
	ScanEnabled     *bool   `json:"scan_enabled,omitempty"`
}

UpdateNetworkRequest represents the request body for updating a network.

type VersionResponse

type VersionResponse struct {
	Version   string    `json:"version"`
	Commit    string    `json:"commit"`
	BuildTime string    `json:"build_time"`
	GoVersion string    `json:"go_version"`
	Timestamp time.Time `json:"timestamp"`
}

VersionResponse represents version information.

type WebSocketHandler

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

WebSocketHandler handles WebSocket connections for real-time updates.

func NewWebSocketHandler

func NewWebSocketHandler(logger *slog.Logger, metricsManager *metrics.Registry) *WebSocketHandler

NewWebSocketHandler creates a new WebSocket handler.

func (*WebSocketHandler) BroadcastDiscoveryUpdate

func (h *WebSocketHandler) BroadcastDiscoveryUpdate(update *DiscoveryUpdateMessage) error

BroadcastDiscoveryUpdate sends a discovery update to all connected discovery clients.

func (*WebSocketHandler) BroadcastScanUpdate

func (h *WebSocketHandler) BroadcastScanUpdate(update *ScanUpdateMessage) error

BroadcastScanUpdate sends a scan update to all connected scan clients.

func (*WebSocketHandler) BroadcastSystemMessage

func (h *WebSocketHandler) BroadcastSystemMessage(messageType, content string) error

BroadcastSystemMessage sends a system message to all connected clients.

func (*WebSocketHandler) Close

func (h *WebSocketHandler) Close() error

Close gracefully shuts down the WebSocket handler.

func (*WebSocketHandler) DiscoveryWebSocket

func (h *WebSocketHandler) DiscoveryWebSocket(w http.ResponseWriter, r *http.Request)

DiscoveryWebSocket handles WebSocket connections for discovery updates.

func (*WebSocketHandler) GeneralWebSocket added in v0.12.0

func (h *WebSocketHandler) GeneralWebSocket(w http.ResponseWriter, r *http.Request)

GeneralWebSocket handles general WebSocket connections for all updates.

func (*WebSocketHandler) GetConnectedClients

func (h *WebSocketHandler) GetConnectedClients() map[string]int

GetConnectedClients returns the number of connected clients by type.

func (*WebSocketHandler) ScanWebSocket

func (h *WebSocketHandler) ScanWebSocket(w http.ResponseWriter, r *http.Request)

ScanWebSocket handles WebSocket connections for scan updates.

func (*WebSocketHandler) Shutdown

func (h *WebSocketHandler) Shutdown()

Shutdown gracefully stops the WebSocket handler.

type WebSocketMessage

type WebSocketMessage struct {
	Type      string      `json:"type"`
	Timestamp time.Time   `json:"timestamp"`
	Data      interface{} `json:"data"`
	RequestID string      `json:"request_id,omitempty"`
}

WebSocketMessage represents a WebSocket message structure.

type WorkerInfo

type WorkerInfo struct {
	ID            string         `json:"id"`
	Status        string         `json:"status"`
	CurrentJob    *JobInfo       `json:"current_job,omitempty"`
	JobsProcessed int64          `json:"jobs_processed"`
	JobsFailed    int64          `json:"jobs_failed"`
	LastJobTime   *time.Time     `json:"last_job_time,omitempty"`
	StartTime     time.Time      `json:"start_time"`
	Uptime        time.Duration  `json:"uptime"`
	MemoryUsage   int64          `json:"memory_usage_bytes"`
	CPUUsage      float64        `json:"cpu_usage_percent"`
	ErrorRate     float64        `json:"error_rate"`
	Metrics       map[string]int `json:"metrics"`
}

WorkerInfo represents individual worker information.

type WorkerStatusResponse

type WorkerStatusResponse struct {
	TotalWorkers   int                    `json:"total_workers"`
	ActiveWorkers  int                    `json:"active_workers"`
	IdleWorkers    int                    `json:"idle_workers"`
	QueueSize      int                    `json:"queue_size"`
	ProcessedJobs  int64                  `json:"processed_jobs"`
	FailedJobs     int64                  `json:"failed_jobs"`
	AvgJobDuration time.Duration          `json:"avg_job_duration"`
	Workers        []WorkerInfo           `json:"workers"`
	Summary        map[string]interface{} `json:"summary"`
	Timestamp      time.Time              `json:"timestamp"`
}

WorkerStatusResponse represents worker pool status information.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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