tool

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: GPL-3.0 Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tool defines the Tool domain entity for the tool registry. Tools are system-wide definitions with versioning and configuration management. Tenants can have custom configurations that override default tool settings.

Index

Constants

This section is empty.

Variables

View Source
var ValidTargetTypes = []string{
	"url",
	"domain",
	"ip",
	"host",
	"repository",
	"file",
	"container",
	"kubernetes",
	"cloud_account",
	"compute",
	"storage",
	"serverless",
	"network",
	"service",
	"port",
	"database",
	"mobile",
	"api",
	"certificate",
}

ValidTargetTypes defines the allowed target types for security (input validation). New target types should be added here after careful consideration.

Functions

func IsValidTargetType

func IsValidTargetType(targetType string) bool

IsValidTargetType checks if a target type is in the allowed list.

Types

type CompatibilityResult

type CompatibilityResult struct {
	// Compatible asset types (can be scanned)
	CompatibleTypes []asset.AssetType

	// Incompatible asset types (will be skipped)
	IncompatibleTypes []asset.AssetType

	// Total counts
	TotalAssetTypes      int
	CompatibleCount      int
	IncompatibleCount    int
	CompatibilityPercent float64

	// Whether any unclassified assets exist
	HasUnclassified   bool
	UnclassifiedCount int
}

CompatibilityResult holds the result of an asset compatibility check.

func (*CompatibilityResult) IsFullyCompatible

func (r *CompatibilityResult) IsFullyCompatible() bool

IsFullyCompatible returns true if all asset types are compatible.

func (*CompatibilityResult) IsFullyIncompatible

func (r *CompatibilityResult) IsFullyIncompatible() bool

IsFullyIncompatible returns true if no asset types are compatible.

func (*CompatibilityResult) IsPartiallyCompatible

func (r *CompatibilityResult) IsPartiallyCompatible() bool

IsPartiallyCompatible returns true if some (but not all) asset types are compatible.

type CustomPattern

type CustomPattern struct {
	Name    string `json:"name"`
	Pattern string `json:"pattern"`
}

CustomPattern represents a custom pattern definition.

type CustomTemplate

type CustomTemplate struct {
	Name    string `json:"name"`
	Path    string `json:"path,omitempty"`    // File path if stored on disk
	Content string `json:"content,omitempty"` // Content if stored in DB
}

CustomTemplate represents a custom template file.

type CustomWordlist

type CustomWordlist struct {
	Name string `json:"name"`
	Path string `json:"path"`
}

CustomWordlist represents a custom wordlist reference.

type EmbeddedCategory

type EmbeddedCategory struct {
	ID          shared.ID
	Name        string // slug: 'sast', 'dast', etc.
	DisplayName string // 'SAST', 'DAST', etc.
	Icon        string
	Color       string
}

EmbeddedCategory contains minimal category info for embedding in tool responses.

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus represents the status of a tool execution.

const (
	ExecutionStatusRunning   ExecutionStatus = "running"
	ExecutionStatusCompleted ExecutionStatus = "completed"
	ExecutionStatusFailed    ExecutionStatus = "failed"
	ExecutionStatusTimeout   ExecutionStatus = "timeout"
)

func (ExecutionStatus) IsValid

func (s ExecutionStatus) IsValid() bool

IsValid checks if the execution status is valid.

type InstallMethod

type InstallMethod string

InstallMethod represents how the tool is installed.

const (
	InstallGo     InstallMethod = "go"     // go install
	InstallPip    InstallMethod = "pip"    // pip install
	InstallNpm    InstallMethod = "npm"    // npm install
	InstallDocker InstallMethod = "docker" // docker pull
	InstallBinary InstallMethod = "binary" // Direct binary download
)

func (InstallMethod) IsValid

func (m InstallMethod) IsValid() bool

IsValid checks if the install method is valid.

type Repository

type Repository interface {
	// Tool operations (system-wide)
	Create(ctx context.Context, tool *Tool) error
	GetByID(ctx context.Context, id shared.ID) (*Tool, error)
	GetByName(ctx context.Context, name string) (*Tool, error)
	List(ctx context.Context, filter ToolFilter, page pagination.Pagination) (pagination.Result[*Tool], error)
	ListByNames(ctx context.Context, names []string) ([]*Tool, error)
	ListByCategoryID(ctx context.Context, categoryID shared.ID) ([]*Tool, error)
	ListByCategoryName(ctx context.Context, categoryName string) ([]*Tool, error)
	ListByCapability(ctx context.Context, capability string) ([]*Tool, error)
	// FindByCapabilities finds an active tool that matches all required capabilities.
	// Searches platform tools first, then tenant-specific tools.
	// Returns nil if no matching active tool is found.
	FindByCapabilities(ctx context.Context, tenantID shared.ID, capabilities []string) (*Tool, error)
	Update(ctx context.Context, tool *Tool) error
	Delete(ctx context.Context, id shared.ID) error

	// Tenant custom tools operations
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Tool, error)
	GetByTenantAndName(ctx context.Context, tenantID shared.ID, name string) (*Tool, error)
	GetPlatformToolByName(ctx context.Context, name string) (*Tool, error)
	ListPlatformTools(ctx context.Context, filter ToolFilter, page pagination.Pagination) (pagination.Result[*Tool], error)
	ListTenantCustomTools(ctx context.Context, tenantID shared.ID, filter ToolFilter, page pagination.Pagination) (pagination.Result[*Tool], error)
	ListAvailableTools(ctx context.Context, tenantID shared.ID, filter ToolFilter, page pagination.Pagination) (pagination.Result[*Tool], error) // Platform + tenant's custom tools
	DeleteTenantTool(ctx context.Context, tenantID, id shared.ID) error

	// Bulk operations
	BulkCreate(ctx context.Context, tools []*Tool) error
	BulkUpdateVersions(ctx context.Context, versions map[shared.ID]VersionInfo) error

	// Statistics
	Count(ctx context.Context, filter ToolFilter) (int64, error)

	// GetAllCapabilities returns all unique capabilities from all tools.
	// Used for dynamic capability validation.
	GetAllCapabilities(ctx context.Context) ([]string, error)
}

Repository defines the interface for tool persistence.

type TargetAssetTypeMapping

type TargetAssetTypeMapping struct {
	ID          shared.ID
	TargetType  string          // e.g., "url", "domain", "ip", "repository"
	AssetType   asset.AssetType // e.g., "website", "domain", "ip_address"
	Priority    int             // Lower = higher priority (10 = primary)
	IsActive    bool
	Description string // Optional description for admin UI
	CreatedAt   time.Time
	UpdatedAt   time.Time
	CreatedBy   *shared.ID // Optional: who created this mapping
}

TargetAssetTypeMapping represents a mapping between a tool's target type and an asset type that it can scan.

For example:

  • target_type="url" -> asset_type="website"
  • target_type="domain" -> asset_type="domain"
  • target_type="ip" -> asset_type="ip_address"

func NewTargetAssetTypeMapping

func NewTargetAssetTypeMapping(targetType string, assetType asset.AssetType) *TargetAssetTypeMapping

NewTargetAssetTypeMapping creates a new mapping with defaults.

func (*TargetAssetTypeMapping) IsPrimary

func (m *TargetAssetTypeMapping) IsPrimary() bool

IsPrimary returns true if this mapping has primary priority (10). Primary mappings are used for reverse lookups (asset_type -> target_type).

func (*TargetAssetTypeMapping) SetPrimary

func (m *TargetAssetTypeMapping) SetPrimary(isPrimary bool)

SetPrimary sets the mapping as primary (priority = 10) or non-primary (priority = 100).

type TargetMappingFilter

type TargetMappingFilter struct {
	TargetType  *string  // Filter by specific target type
	AssetType   *string  // Filter by specific asset type
	IsActive    *bool    // Filter by active status
	TargetTypes []string // Filter by multiple target types (IN clause)
	AssetTypes  []string // Filter by multiple asset types (IN clause)
}

TargetMappingFilter defines filtering options for target mapping queries.

type TargetMappingRepository

type TargetMappingRepository interface {
	// CRUD operations
	Create(ctx context.Context, mapping *TargetAssetTypeMapping) error
	GetByID(ctx context.Context, id shared.ID) (*TargetAssetTypeMapping, error)
	Update(ctx context.Context, mapping *TargetAssetTypeMapping) error
	Delete(ctx context.Context, id shared.ID) error
	List(ctx context.Context, filter TargetMappingFilter, page pagination.Pagination) (pagination.Result[*TargetAssetTypeMapping], error)

	// Compatibility check methods
	// GetAssetTypesForTargets returns all asset types that can be scanned by the given target types.
	// Example: GetAssetTypesForTargets(["url", "domain"]) -> ["website", "web_application", "domain", "subdomain"]
	GetAssetTypesForTargets(ctx context.Context, targetTypes []string) ([]asset.AssetType, error)

	// GetTargetsForAssetType returns all target types that can scan the given asset type.
	// Example: GetTargetsForAssetType("website") -> ["url"]
	GetTargetsForAssetType(ctx context.Context, assetType asset.AssetType) ([]string, error)

	// CanToolScanAssetType checks if a tool (via its supported_targets) can scan a specific asset type.
	// Returns true if any of the tool's target types map to the asset type.
	CanToolScanAssetType(ctx context.Context, targetTypes []string, assetType asset.AssetType) (bool, error)

	// GetIncompatibleAssetTypes returns asset types from the list that CANNOT be scanned
	// by any of the given target types.
	GetIncompatibleAssetTypes(ctx context.Context, targetTypes []string, assetTypes []asset.AssetType) ([]asset.AssetType, error)

	// GetCompatibleAssetTypes returns asset types from the list that CAN be scanned
	// by at least one of the given target types.
	GetCompatibleAssetTypes(ctx context.Context, targetTypes []string, assetTypes []asset.AssetType) ([]asset.AssetType, error)
}

TargetMappingRepository defines the interface for target mapping persistence.

type TenantToolConfig

type TenantToolConfig struct {
	ID       shared.ID
	TenantID shared.ID
	ToolID   shared.ID

	// Configuration override (merged with tool's DefaultConfig)
	Config map[string]any

	// Custom templates (e.g., Nuclei templates)
	CustomTemplates []CustomTemplate

	// Custom patterns (e.g., GF patterns, regex patterns)
	CustomPatterns []CustomPattern

	// Custom wordlists
	CustomWordlists []CustomWordlist

	// Status
	IsEnabled bool

	// Audit
	UpdatedBy *shared.ID
	CreatedAt time.Time
	UpdatedAt time.Time
}

TenantToolConfig represents tenant-specific tool configuration. This allows tenants to override default tool settings without modifying the system-wide tool definition.

func NewTenantToolConfig

func NewTenantToolConfig(
	tenantID shared.ID,
	toolID shared.ID,
	config map[string]any,
	updatedBy *shared.ID,
) (*TenantToolConfig, error)

NewTenantToolConfig creates a new tenant tool configuration.

func (*TenantToolConfig) AddCustomPattern

func (c *TenantToolConfig) AddCustomPattern(pattern CustomPattern) error

AddCustomPattern adds a custom pattern.

func (*TenantToolConfig) AddCustomTemplate

func (c *TenantToolConfig) AddCustomTemplate(template CustomTemplate) error

AddCustomTemplate adds a custom template.

func (*TenantToolConfig) Disable

func (c *TenantToolConfig) Disable()

Disable disables the tool for this tenant.

func (*TenantToolConfig) Enable

func (c *TenantToolConfig) Enable()

Enable enables the tool for this tenant.

func (*TenantToolConfig) RemoveCustomPattern

func (c *TenantToolConfig) RemoveCustomPattern(name string)

RemoveCustomPattern removes a custom pattern by name.

func (*TenantToolConfig) RemoveCustomTemplate

func (c *TenantToolConfig) RemoveCustomTemplate(name string)

RemoveCustomTemplate removes a custom template by name.

func (*TenantToolConfig) Update

func (c *TenantToolConfig) Update(
	config map[string]any,
	isEnabled bool,
	updatedBy *shared.ID,
) error

Update updates the tenant tool configuration.

type TenantToolConfigFilter

type TenantToolConfigFilter struct {
	TenantID  shared.ID
	ToolID    *shared.ID
	IsEnabled *bool
}

TenantToolConfigFilter defines filtering options for tenant tool config queries.

type TenantToolConfigRepository

type TenantToolConfigRepository interface {
	// CRUD operations
	Create(ctx context.Context, config *TenantToolConfig) error
	GetByID(ctx context.Context, id shared.ID) (*TenantToolConfig, error)
	GetByTenantAndTool(ctx context.Context, tenantID, toolID shared.ID) (*TenantToolConfig, error)
	List(ctx context.Context, filter TenantToolConfigFilter, page pagination.Pagination) (pagination.Result[*TenantToolConfig], error)
	Update(ctx context.Context, config *TenantToolConfig) error
	Delete(ctx context.Context, id shared.ID) error

	// Upsert - Create or update config
	Upsert(ctx context.Context, config *TenantToolConfig) error

	// Get effective config (merged default + tenant override)
	GetEffectiveConfig(ctx context.Context, tenantID, toolID shared.ID) (map[string]any, error)

	// List all enabled tools for a tenant
	ListEnabledTools(ctx context.Context, tenantID shared.ID) ([]*TenantToolConfig, error)

	// List all tools with their tenant-specific enabled status
	// Returns tools joined with tenant configs, where is_enabled defaults to true if no config exists
	ListToolsWithConfig(ctx context.Context, tenantID shared.ID, filter ToolFilter, page pagination.Pagination) (pagination.Result[*ToolWithConfig], error)

	// Bulk enable/disable tools for tenant
	BulkEnable(ctx context.Context, tenantID shared.ID, toolIDs []shared.ID) error
	BulkDisable(ctx context.Context, tenantID shared.ID, toolIDs []shared.ID) error
}

TenantToolConfigRepository defines the interface for tenant tool config persistence.

type TenantToolStats

type TenantToolStats struct {
	TenantID       shared.ID
	TotalRuns      int64
	SuccessfulRuns int64
	FailedRuns     int64
	TotalFindings  int64
	ToolBreakdown  []ToolStats
}

TenantToolStats holds aggregated tool statistics for a tenant.

type Tool

type Tool struct {
	ID          shared.ID
	TenantID    *shared.ID // nil = platform tool, UUID = tenant custom tool
	Name        string     // Unique identifier: 'semgrep', 'nuclei', etc.
	DisplayName string
	Description string
	LogoURL     string
	CategoryID  *shared.ID // Foreign key to tool_categories table

	// Installation
	InstallMethod InstallMethod
	InstallCmd    string
	UpdateCmd     string

	// Version tracking
	VersionCmd     string // Command to check version
	VersionRegex   string // Regex to extract version from output
	CurrentVersion string // Currently installed version
	LatestVersion  string // Latest available version

	// Configuration
	ConfigFilePath string         // Path to config file, e.g., '/root/.config/nuclei/config.yaml'
	ConfigSchema   map[string]any // JSON Schema for validating tool config
	DefaultConfig  map[string]any // Default configuration

	// Capabilities this tool provides (maps to agent capabilities)
	Capabilities []string

	// Supported input/output
	SupportedTargets []string // 'url', 'domain', 'ip', 'file', 'repository', 'container'
	OutputFormats    []string // 'json', 'sarif', 'csv', 'txt'

	// Documentation
	DocsURL   string
	GithubURL string

	// Status
	IsActive  bool // Tool is available for use
	IsBuiltin bool // System tool vs custom installed

	// Metadata
	Tags     []string
	Metadata map[string]any

	// Audit
	CreatedBy *shared.ID // User who created the tool (for custom tools)
	CreatedAt time.Time
	UpdatedAt time.Time
}

Tool represents a security tool in the registry. Platform tools (TenantID = nil, IsBuiltin = true) are available to all tenants. Tenant custom tools (TenantID = UUID, IsBuiltin = false) are private to that tenant.

func NewTenantCustomTool

func NewTenantCustomTool(
	tenantID shared.ID,
	createdBy shared.ID,
	name string,
	displayName string,
	categoryID *shared.ID,
	installMethod InstallMethod,
) (*Tool, error)

NewTenantCustomTool creates a new tenant custom Tool entity. Custom tools are private to the tenant and can be fully managed by them.

func NewTool

func NewTool(
	name string,
	displayName string,
	categoryID *shared.ID,
	installMethod InstallMethod,
) (*Tool, error)

NewTool creates a new platform Tool entity (TenantID = nil, IsBuiltin = true). Use NewTenantCustomTool for creating tenant-specific tools.

func (*Tool) Activate

func (t *Tool) Activate()

Activate enables the tool.

func (*Tool) BelongsToTenant

func (t *Tool) BelongsToTenant(tenantID shared.ID) bool

BelongsToTenant checks if the tool belongs to a specific tenant.

func (*Tool) CanDelete

func (t *Tool) CanDelete() error

CanDelete checks if the tool can be deleted.

func (*Tool) CanManage

func (t *Tool) CanManage(tenantID shared.ID) error

CanManage checks if a tenant can manage (edit/delete/enable/disable) this tool.

func (*Tool) Deactivate

func (t *Tool) Deactivate()

Deactivate disables the tool.

func (*Tool) HasCapability

func (t *Tool) HasCapability(capability string) bool

HasCapability checks if the tool has a specific capability.

func (*Tool) HasUpdateAvailable

func (t *Tool) HasUpdateAvailable() bool

HasUpdateAvailable checks if an update is available.

func (*Tool) IsCustomTool

func (t *Tool) IsCustomTool() bool

IsCustomTool returns true if this is a tenant custom tool.

func (*Tool) IsPlatformTool

func (t *Tool) IsPlatformTool() bool

IsPlatformTool returns true if this is a platform-provided tool.

func (*Tool) SetVersion

func (t *Tool) SetVersion(current, latest string)

SetVersion updates the version information.

func (*Tool) SupportsTarget

func (t *Tool) SupportsTarget(targetType string) bool

SupportsTarget checks if the tool supports a specific target type.

func (*Tool) Update

func (t *Tool) Update(
	displayName string,
	description string,
	installCmd string,
	updateCmd string,
	defaultConfig map[string]any,
) error

Update updates the tool properties.

type ToolExecution

type ToolExecution struct {
	ID       shared.ID
	TenantID shared.ID
	ToolID   shared.ID
	AgentID  *shared.ID

	// Execution context
	PipelineRunID *shared.ID
	StepRunID     *shared.ID

	// Status
	Status ExecutionStatus

	// Input/Output
	InputConfig   map[string]any
	TargetsCount  int
	FindingsCount int
	OutputSummary map[string]any
	ErrorMessage  string

	// Timing
	StartedAt   time.Time
	CompletedAt *time.Time
	DurationMs  int

	CreatedAt time.Time
}

ToolExecution represents a single tool execution record. Used for analytics and debugging.

func NewToolExecution

func NewToolExecution(
	tenantID shared.ID,
	toolID shared.ID,
	agentID *shared.ID,
	inputConfig map[string]any,
	targetsCount int,
) *ToolExecution

NewToolExecution creates a new tool execution record.

func (*ToolExecution) Complete

func (e *ToolExecution) Complete(findingsCount int, outputSummary map[string]any)

Complete marks the execution as completed.

func (*ToolExecution) Fail

func (e *ToolExecution) Fail(errorMessage string)

Fail marks the execution as failed.

func (*ToolExecution) Timeout

func (e *ToolExecution) Timeout()

Timeout marks the execution as timed out.

type ToolExecutionFilter

type ToolExecutionFilter struct {
	TenantID      shared.ID
	ToolID        *shared.ID
	AgentID       *shared.ID
	PipelineRunID *shared.ID
	Status        *ExecutionStatus
}

ToolExecutionFilter defines filtering options for tool execution queries.

type ToolExecutionRepository

type ToolExecutionRepository interface {
	Create(ctx context.Context, execution *ToolExecution) error

	// GetByID retrieves a tool execution by ID without tenant scoping.
	//
	// F-4: This method is UNSAFE for user-facing handlers — it would allow
	// an IDOR because the tool_executions row contains cross-tenant
	// sensitive data (error_message, output_summary, targets). Callers from
	// HTTP handlers MUST use GetByIDInTenant instead. Safe uses are limited
	// to agent/platform-authenticated internal lifecycle flows where tenant
	// identity is validated elsewhere, and audits / retention controllers
	// that iterate the whole table.
	GetByID(ctx context.Context, id shared.ID) (*ToolExecution, error)

	// GetByIDInTenant retrieves a tool execution restricted to one tenant.
	// Prefer this for any handler exposed to user input.
	GetByIDInTenant(ctx context.Context, tenantID, id shared.ID) (*ToolExecution, error)

	List(ctx context.Context, filter ToolExecutionFilter, page pagination.Pagination) (pagination.Result[*ToolExecution], error)
	Update(ctx context.Context, execution *ToolExecution) error

	// Statistics
	GetToolStats(ctx context.Context, tenantID, toolID shared.ID, days int) (*ToolStats, error)
	GetTenantStats(ctx context.Context, tenantID shared.ID, days int) (*TenantToolStats, error)
}

ToolExecutionRepository defines the interface for tool execution persistence.

type ToolFilter

type ToolFilter struct {
	CategoryID   *shared.ID // Filter by category_id (FK to tool_categories)
	CategoryName *string    // Filter by category name (via join with tool_categories)
	Capabilities []string
	IsActive     *bool
	IsBuiltin    *bool
	Search       string
	Tags         []string

	// Tenant filtering
	TenantID        *shared.ID // Filter by specific tenant's custom tools
	IncludePlatform bool       // Include platform tools (tenant_id IS NULL)
	OnlyPlatform    bool       // Only platform tools (tenant_id IS NULL)
	OnlyCustom      bool       // Only custom tools (tenant_id IS NOT NULL)
}

ToolFilter defines filtering options for tool queries.

type ToolStats

type ToolStats struct {
	ToolID         shared.ID
	TotalRuns      int64
	SuccessfulRuns int64
	FailedRuns     int64
	TotalFindings  int64
	AvgDurationMs  int64
}

ToolStats holds statistics for a specific tool.

type ToolWithConfig

type ToolWithConfig struct {
	Tool            *Tool
	Category        *EmbeddedCategory // Embedded category info for UI grouping
	TenantConfig    *TenantToolConfig
	EffectiveConfig map[string]any
	IsEnabled       bool
	IsAvailable     bool // True if at least one agent (tenant or platform) supports this tool
}

ToolWithConfig represents a tool with its tenant-specific configuration. Used when loading tools with their effective configuration for a tenant.

type VersionInfo

type VersionInfo struct {
	CurrentVersion string
	LatestVersion  string
}

VersionInfo holds version information for bulk update.

Jump to

Keyboard shortcuts

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