plugin

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package plugin is the contract a Bomly component implements: the Detector, Matcher, Auditor, and Analyzer interfaces with their descriptors, request and response types, the Base* defaults that insulate an implementation from interface growth, and Module, which packages one component with its constructor so the same value runs embedded in the host or served as a managed plugin.

A component reaches host services only through HostContext -- a logger, an HTTP client provider, runtime information, DecodeConfig for its own configuration block, and OnCleanup for releasing what it acquired -- and is otherwise a pure function of its request. It does not know which execution mode it is in: the embedded host and the managed transport (the runtime package) both satisfy HostContext, and both give it the same lifetime. Its constructor's context lasts as long as the component, and the cleanups it registers run in reverse order when that lifetime ends; ComponentScope is the implementation a host uses.

A descriptor may declare the pipeline inputs its component needs in Requires (see Requirement), so a host can explain an impossible plan before running it; Ready and Applicable still decide at run time. A managed plugin's manifest may disclose the access it expects (see Access), which a host shows the user as an unverified claim before the plugin is enabled.

A matcher or analyzer receives a copy of the host's graph and registry (MatchRequest.Clone, AnalyzeRequest.Clone), and the host keeps what it returns only when the call succeeds: changing the request in place and then failing leaves the host's state as it was, in both execution modes.

A plugin binary packages its component as a Module and serves it from main through the runtime package:

func main() {
	runtime.ServeModule(myModule)
}

Descriptors are validated at every entry point (ValidateDetectorDescriptor and its siblings, ValidateModule), and a descriptor's ConfigSchema is derived from the component's own config struct with ConfigSchemaFor. The request and response types here, together with the model package they carry, are the JSON payloads of the bomly.plugin.v1 protocol; their tags are the wire schema and only grow additively.

Index

Constants

View Source
const (
	MaxAccessEntries     = 32
	MaxAccessEntryLength = 253
)

MaxAccessEntries bounds each Access list, and MaxAccessEntryLength each entry: resource bounds on publisher-supplied manifest input. The entry bound is the DNS name limit, the longest entry any list needs.

View Source
const (
	MaxRequirements      = 16
	MaxRequirementLength = 64
)

MaxRequirements bounds how many requirements one descriptor may declare, and MaxRequirementLength how long one token may be. Both are resource bounds on untrusted descriptor input, not vocabulary.

View Source
const AccessAny = "*"

AccessAny is the entry that stands for every destination, variable or command in its list.

View Source
const CapabilityPackageUpdates = "package-updates-v1"

CapabilityPackageUpdates is advertised in a matcher's or analyzer's descriptor Capabilities to signal that it can return MatchResult.PackageUpdates / AnalyzeResult.PackageUpdates deltas when the request sets AcceptPackageUpdates. Hosts and plugins that do not know this capability keep exchanging full registries — the protocol v1 baseline.

View Source
const InstalledPluginsSchemaVersion = "bomly.installed-plugins.v1"

InstalledPluginsSchemaVersion is the installed plugin database schema version.

View Source
const PackageManifestSchemaVersion = "bomly.plugin.package.v1"

PackageManifestSchemaVersion is the package manifest schema version.

View Source
const PluginAPIVersion = "bomly.plugin.v1"

PluginAPIVersion is the current managed plugin API contract version.

View Source
const RuntimeDescriptorSnapshotSchemaVersion = "bomly.plugin.runtime-descriptor.v1"

RuntimeDescriptorSnapshotSchemaVersion is Bomly's internal installed descriptor snapshot schema.

View Source
const RuntimeHashiCorpGRPC = "hashicorp-grpc"

RuntimeHashiCorpGRPC identifies the supported external plugin runtime.

Variables

This section is empty.

Functions

func ConfigSchemaFor

func ConfigSchemaFor(prototype any) (json.RawMessage, error)

ConfigSchemaFor derives a JSON Schema (draft 2020-12 subset) for a component's configuration block from a prototype struct. Declare your configuration once as a typed Go struct, decode it at runtime with HostContext.DecodeConfig, and advertise its shape in the descriptor:

type Config struct {
	Endpoint string `json:"endpoint" doc:"API endpoint override" default:"https://api.example.com"`
	Timeout  int    `json:"timeoutSeconds" doc:"Request timeout in seconds" default:"30"`
	Strict   bool   `json:"strict" doc:"Fail on partial results"`
}

descriptor.ConfigSchema = MustConfigSchemaFor(Config{})

Recognized struct tags: `json` (property name and omission), `doc` (property description), and `default` (default value, converted to the field's type). Nested structs, pointers, slices, and string-keyed maps are supported. Unexported fields and fields tagged `json:"-"` are skipped.

func MustConfigSchemaFor

func MustConfigSchemaFor(prototype any) json.RawMessage

MustConfigSchemaFor is ConfigSchemaFor that panics on error. Use it for static descriptor initialization where the prototype is a compile-time constant shape.

func NormalizeCommitSHA added in v0.14.0

func NormalizeCommitSHA(value string) string

NormalizeCommitSHA returns value as a lowercase hexadecimal commit identifier of 7 to 64 digits -- an abbreviated or full SHA-1, or a SHA-256 -- or "" when value is not one. A producer applies it before recording ExecutionTarget.CommitSHA so a ref name or a path can never be mistaken for a commit.

func ValidateAccess added in v0.16.0

func ValidateAccess(access *Access) error

ValidateAccess validates an optional disclosure: nil -- the legacy "unknown" -- is valid, and a present one must pass Access.Validate.

func ValidateAnalyzerDescriptor

func ValidateAnalyzerDescriptor(descriptor *AnalyzerDescriptor) error

ValidateAnalyzerDescriptor validates typed analyzer registration data.

func ValidateAuditorDescriptor

func ValidateAuditorDescriptor(descriptor *AuditorDescriptor) error

ValidateAuditorDescriptor validates typed auditor registration data.

func ValidateDetectorDescriptor

func ValidateDetectorDescriptor(descriptor *DetectorDescriptor) error

ValidateDetectorDescriptor validates typed detector registration data.

func ValidateMatcherDescriptor

func ValidateMatcherDescriptor(descriptor *MatcherDescriptor) error

ValidateMatcherDescriptor validates typed matcher registration data.

func ValidateModule

func ValidateModule(m Module) error

ValidateModule checks that exactly one role is set, that the role matches the declared Kind, that the role constructor is present, and that the role descriptor validates.

Types

type Access added in v0.16.0

type Access struct {
	// FilesystemRead lists the areas the plugin reads; see FilesystemScope.
	FilesystemRead []FilesystemScope `json:"filesystemRead,omitempty"`
	// FilesystemWrite lists the areas the plugin writes or deletes in.
	// Writing an area implies reading it.
	FilesystemWrite []FilesystemScope `json:"filesystemWrite,omitempty"`
	// Network lists the destinations the plugin contacts: a host name
	// ("api.osv.dev"), a host and all its subdomains ("*.github.com"), or
	// "*" for destinations it cannot name in advance, such as a
	// user-configured registry. Destinations are descriptive patterns, not
	// a firewall rule.
	Network []string `json:"network,omitempty"`
	// Environment lists the environment variables the plugin reads, by name
	// ("GITHUB_TOKEN"), by prefix ("BOMLY_HTTP_*"), or "*" for all of them.
	// Names only: a host never displays or logs a value.
	Environment []string `json:"environment,omitempty"`
	// Subprocesses lists the commands the plugin starts, by base name
	// ("go", "npm"), or "*" for commands it cannot name in advance.
	Subprocesses []string `json:"subprocesses,omitempty"`
}

Access is a managed plugin's own disclosure of the host access it expects: which filesystem areas it reads and writes, which network destinations it contacts, which environment variables it reads, and which commands it starts. It is the "access" block of a package manifest (bomly-plugin.json, PackageManifestSchemaVersion), written by the plugin's publisher, and a host shows it to the user before the user enables the plugin.

It is disclosure, not enforcement. A managed plugin is a native process with the invoking user's authority; nothing in Bomly restricts it to what it declared, and a declaration is not evidence that the plugin behaves as declared. A host must present it as the publisher's unverified claim.

A manifest without an access block discloses nothing, which a host must treat as unknown and unrestricted -- never as "needs no access". A present block with every list empty is a claim that the plugin needs none.

Every list is bounded, deduplicated and sorted; network destinations are canonicalized. The vocabularies are open, as Requirement's is: a well-formed entry this SDK does not recognize is kept, so an older host shows a newer plugin's claim rather than hiding it, and a malformed entry fails Validate rather than being dropped, because silently dropping an entry would under-report access. The set of lists is closed: a key this SDK does not know fails decoding, for the same reason.

func (Access) MarshalJSON added in v0.16.0

func (a Access) MarshalJSON() ([]byte, error)

MarshalJSON normalizes the disclosure as it is written. A present block with no entries encodes as {}, a claim of no access, distinct from an absent block.

func (Access) Normalized added in v0.16.0

func (a Access) Normalized() Access

Normalized returns the disclosure with every list deduplicated and sorted and every network destination canonicalized through model.CanonicalHostname. An entry that cannot be canonicalized is kept as written, so Validate reports it instead of the normalization hiding it.

func (*Access) UnmarshalJSON added in v0.16.0

func (a *Access) UnmarshalJSON(data []byte) error

UnmarshalJSON normalizes the disclosure as it is read. The input is bounded before it is parsed, and every list is held to MaxAccessEntries before it is canonicalized or deduplicated, so neither the host gate's work nor a repeated entry escapes the bound.

func (Access) Validate added in v0.16.0

func (a Access) Validate() error

Validate checks every list against its bound and grammar: filesystem scopes are lower-case tokens; network destinations are "*", a host name, or "*." and a host name, each accepted by model.CanonicalHostname; environment entries are "*" or a POSIX name, optionally ending in "*"; subprocess entries are "*" or a command base name -- no path separator, whitespace or control character. Unknown but well-formed scopes pass.

type AnalyzeRequest

type AnalyzeRequest struct {
	ProjectPath     string                 `json:"projectPath,omitempty"`
	ExecutionTarget ExecutionTarget        `json:"executionTarget"`
	SubprojectInfo  Subproject             `json:"subprojectInfo"`
	Ecosystem       model.Ecosystem        `json:"ecosystem,omitempty"`
	PackageManager  model.PackageManager   `json:"packageManager,omitempty"`
	Language        model.Language         `json:"language,omitempty"`
	Query           PackageQuery           `json:"query"`
	Graph           *model.Graph           `json:"graph,omitempty"`
	Registry        *model.PackageRegistry `json:"registry,omitempty"`
	Target          *model.DependencyNode  `json:"target,omitempty"`
	AnalyzerFilter  AnalyzerFilter         `json:"analyzerFilter"`
	// AcceptPackageUpdates signals that the host understands
	// AnalyzeResult.PackageUpdates. Analyzers advertising
	// CapabilityPackageUpdates may return updates instead of a full registry
	// only when this is true.
	AcceptPackageUpdates bool      `json:"acceptPackageUpdates,omitempty"`
	Stderr               io.Writer `json:"-"`
}

AnalyzeRequest defines input for an analyzer. Analyzers annotate Vulnerability.Reachability on packages in the Registry.

func (AnalyzeRequest) Clone added in v0.15.0

func (r AnalyzeRequest) Clone() AnalyzeRequest

Clone returns a deep copy of the request that shares no mutable memory with it, on the terms MatchRequest.Clone states: the graph, registry and target are copied, every slice is copied, and Stderr is kept as the host's writer.

type AnalyzeResponse

type AnalyzeResponse = AnalyzeResult

AnalyzeResponse is the analyzer response payload exposed to plugins.

type AnalyzeResult

type AnalyzeResult struct {
	Registry       *model.PackageRegistry       `json:"registry,omitempty"`
	PackageUpdates []*model.Package             `json:"packageUpdates,omitempty"`
	AnalyzerRuns   []string                     `json:"analyzerRuns,omitempty"`
	AnalyzerStats  map[string]ReachabilityStats `json:"analyzerStats,omitempty"`
}

AnalyzeResult contains the registry after analyzer enrichment. An analyzer returns either Registry (the full annotated registry — the protocol v1 baseline) or, when the request set AcceptPackageUpdates, PackageUpdates: only the packages it touched. The host merges updates into its registry by PURL. When Registry is non-nil it wins and PackageUpdates is ignored.

type Analyzer

type Analyzer interface {
	Descriptor() AnalyzerDescriptor
	// Ready reports whether the analyzer can run for the given request. It
	// returns nil when ready and a non-nil error describing the reason
	// otherwise. Implementations may perform lightweight, cancellable I/O and
	// should honor ctx.
	Ready(context.Context, AnalyzeRequest) error
	Applicable(context.Context, AnalyzeRequest) (bool, error)
	Analyze(context.Context, AnalyzeRequest) (AnalyzeResult, error)
}

Analyzer enriches Vulnerability entries with reachability data derived from code analysis. Analyzers run after matchers, before auditors, and must never abort the pipeline on failure.

type AnalyzerDescriptor

type AnalyzerDescriptor struct {
	Name                string                 `json:"name"`
	DisplayName         string                 `json:"displayName,omitempty"`
	Aliases             []string               `json:"aliases,omitempty"`
	Tags                []string               `json:"tags,omitempty"`
	SupportedEcosystems []model.Ecosystem      `json:"supportedEcosystems,omitempty"`
	SupportedManagers   []model.PackageManager `json:"supportedManagers,omitempty"`
	// Version is the component's own release version; see
	// ComponentDescriptor.Version. Optional.
	Version string `json:"version,omitempty"`
	// Requires declares the pipeline inputs and host capabilities the
	// component needs; see Requirement. Optional: absent means legacy and
	// unspecified, never "needs nothing". Ready and Applicable still run.
	// Gate: Requirements.Validate, through the kind's Validate*Descriptor.
	Requires Requirements `json:"requires,omitempty"`
	// SupportedLanguages is the analyzer's primary dispatch axis.
	SupportedLanguages []model.Language `json:"supportedLanguages,omitempty"`
	// SupportedTiers communicates the precision the analyzer can deliver.
	SupportedTiers []model.ReachabilityTier `json:"supportedTiers,omitempty"`
	// Capabilities advertises optional protocol features this analyzer
	// supports, such as CapabilityPackageUpdates.
	Capabilities []string `json:"capabilities,omitempty"`
	// ConfigSchema optionally documents the analyzer's configuration block as
	// a JSON Schema. Build it with ConfigSchemaFor.
	ConfigSchema json.RawMessage `json:"configSchema,omitempty"`
}

AnalyzerDescriptor describes an analyzer registration.

func (AnalyzerDescriptor) Clone added in v0.16.0

Clone returns a deep copy of the descriptor: every slice, the declared requirements and the config schema are copied, so a host that keeps a descriptor cannot have it changed by the component that returned it.

func (AnalyzerDescriptor) Label

func (d AnalyzerDescriptor) Label() string

Label returns the user-facing analyzer label, falling back to Name.

type AnalyzerFilter

type AnalyzerFilter struct {
	Include []string `json:"Include,omitempty"`
	Exclude []string `json:"Exclude,omitempty"`
}

AnalyzerFilter narrows analyzer selection for a request.

The json tags keep their capitals. These fields carried no tag, so v1 peers send "Include" and "Exclude"; lowercasing one renames the wire field. TestWireV1FilterNamesKeepTheirCapitals fails if it happens.

func (AnalyzerFilter) Excludes

func (f AnalyzerFilter) Excludes(name string) bool

Excludes reports whether an analyzer name is explicitly denied.

func (AnalyzerFilter) Includes

func (f AnalyzerFilter) Includes(name string) bool

Includes reports whether an analyzer name is explicitly allowed.

type AnalyzerModule

type AnalyzerModule struct {
	Descriptor AnalyzerDescriptor
	New        func(context.Context, HostContext) (Analyzer, error)
}

AnalyzerModule declares one analyzer component.

type ApplicableResponse

type ApplicableResponse struct {
	Applicable bool `json:"applicable"`
}

ApplicableResponse reports whether a plugin should run for the given request.

type AuditRequest

type AuditRequest struct {
	ProjectPath     string                 `json:"projectPath,omitempty"`
	ExecutionTarget ExecutionTarget        `json:"executionTarget"`
	SubprojectInfo  Subproject             `json:"subprojectInfo"`
	Ecosystem       model.Ecosystem        `json:"ecosystem,omitempty"`
	PackageManager  model.PackageManager   `json:"packageManager,omitempty"`
	Query           PackageQuery           `json:"query"`
	Graph           *model.Graph           `json:"graph,omitempty"`
	BaselineGraph   *model.Graph           `json:"baselineGraph,omitempty"`
	Registry        *model.PackageRegistry `json:"registry,omitempty"`
	Target          *model.DependencyNode  `json:"target,omitempty"`
	// DependencyDetailChanges contains canonical head-side transitions for a
	// diff audit. Scan and explain requests leave it empty.
	DependencyDetailChanges []model.DependencyDetailTransition `json:"dependencyDetailChanges,omitempty"`
	AuditorFilter           AuditorFilter                      `json:"auditorFilter"`
	Stderr                  io.Writer                          `json:"-"`
}

AuditRequest defines input for an auditor. Auditors read the dependency Graph and the package Registry and emit reference-style findings.

type AuditResponse

type AuditResponse = AuditResult

AuditResponse is the auditor response payload exposed to plugins.

It aliases AuditResult so plugin code can name payload types by role while sharing the same transport shape Bomly core uses internally.

type AuditResult

type AuditResult struct {
	Findings        []model.Finding   `json:"findings,omitempty"`
	RiskScores      []model.RiskScore `json:"riskScores,omitempty"`
	AuditorRuns     []string          `json:"auditorRuns,omitempty"`
	AuditorFindings map[string]int    `json:"auditorFindings,omitempty"`
}

AuditResult contains findings and scores from one auditor.

type Auditor

type Auditor interface {
	Descriptor() AuditorDescriptor
	// Ready reports whether the auditor can run for the given request. It
	// returns nil when ready and a non-nil error describing the reason
	// otherwise. Implementations may perform lightweight, cancellable I/O and
	// should honor ctx.
	Ready(context.Context, AuditRequest) error
	Applicable(context.Context, AuditRequest) (bool, error)
	Audit(context.Context, AuditRequest) (AuditResult, error)
}

Auditor analyzes graphs or components and returns findings.

type AuditorDescriptor

type AuditorDescriptor struct {
	Name                string                 `json:"name"`
	DisplayName         string                 `json:"displayName,omitempty"`
	Aliases             []string               `json:"aliases,omitempty"`
	Tags                []string               `json:"tags,omitempty"`
	SupportedEcosystems []model.Ecosystem      `json:"supportedEcosystems,omitempty"`
	SupportedManagers   []model.PackageManager `json:"supportedManagers,omitempty"`
	// Version is the component's own release version; see
	// ComponentDescriptor.Version. Optional.
	Version string `json:"version,omitempty"`
	// Requires declares the pipeline inputs and host capabilities the
	// component needs; see Requirement. Optional: absent means legacy and
	// unspecified, never "needs nothing". Ready and Applicable still run.
	// Gate: Requirements.Validate, through the kind's Validate*Descriptor.
	Requires Requirements `json:"requires,omitempty"`
	// ConfigSchema optionally documents the auditor's configuration block as
	// a JSON Schema. Build it with ConfigSchemaFor.
	ConfigSchema json.RawMessage `json:"configSchema,omitempty"`
}

AuditorDescriptor describes an auditor registration.

func (AuditorDescriptor) Clone added in v0.16.0

Clone returns a deep copy of the descriptor: every slice, the declared requirements and the config schema are copied, so a host that keeps a descriptor cannot have it changed by the component that returned it.

func (AuditorDescriptor) Label

func (d AuditorDescriptor) Label() string

Label returns the user-facing auditor label, falling back to Name.

type AuditorFilter

type AuditorFilter struct {
	Include []string `json:"Include,omitempty"`
	Exclude []string `json:"Exclude,omitempty"`
}

AuditorFilter narrows auditor selection for a request.

The json tags keep their capitals. These fields carried no tag, so v1 peers send "Include" and "Exclude"; lowercasing one renames the wire field. TestWireV1FilterNamesKeepTheirCapitals fails if it happens.

func (AuditorFilter) Excludes

func (f AuditorFilter) Excludes(name string) bool

Excludes reports whether an auditor name is explicitly denied.

func (AuditorFilter) Includes

func (f AuditorFilter) Includes(name string) bool

Includes reports whether an auditor name is explicitly allowed.

type AuditorModule

type AuditorModule struct {
	Descriptor AuditorDescriptor
	New        func(context.Context, HostContext) (Auditor, error)
}

AuditorModule declares one auditor component.

type BaseAnalyzer

type BaseAnalyzer struct{}

BaseAnalyzer provides default implementations of Analyzer's optional lifecycle methods: always ready and always applicable.

func (BaseAnalyzer) Applicable

Applicable reports the analyzer as applicable.

func (BaseAnalyzer) Ready

Ready reports the analyzer as ready.

type BaseAuditor

type BaseAuditor struct{}

BaseAuditor provides default implementations of Auditor's optional lifecycle methods: always ready and always applicable.

func (BaseAuditor) Applicable

Applicable reports the auditor as applicable.

func (BaseAuditor) Ready

Ready reports the auditor as ready.

type BaseDetector

type BaseDetector struct{}

BaseDetector provides default implementations of Detector's optional lifecycle methods: always ready and always applicable.

func (BaseDetector) Applicable

Applicable reports the detector as applicable.

func (BaseDetector) Ready

Ready reports the detector as ready.

type BaseMatcher

type BaseMatcher struct{}

BaseMatcher provides default implementations of Matcher's optional lifecycle methods: always ready and always applicable.

func (BaseMatcher) Applicable

Applicable reports the matcher as applicable.

func (BaseMatcher) Ready

Ready reports the matcher as ready.

type ComponentDescriptor

type ComponentDescriptor struct {
	Name                string                 `json:"name"`
	DisplayName         string                 `json:"displayName,omitempty"`
	Aliases             []string               `json:"aliases,omitempty"`
	Tags                []string               `json:"tags,omitempty"`
	SupportedEcosystems []model.Ecosystem      `json:"supportedEcosystems,omitempty"`
	SupportedManagers   []model.PackageManager `json:"supportedManagers,omitempty"`
	// Version is the component's own release version, as its author states
	// it. A host records it beside the name so a result can say which
	// version of a component produced it. Optional; held to the name's
	// domain (bounded, valid UTF-8, no control characters) when present.
	Version string `json:"version,omitempty"`
	// Requires declares the pipeline inputs and host capabilities the
	// component needs; see Requirement. Optional: absent means legacy and
	// unspecified, never "needs nothing". Ready and Applicable still run.
	// Gate: Requirements.Validate, through the kind's Validate*Descriptor.
	Requires Requirements `json:"requires,omitempty"`
}

ComponentDescriptor describes the common identity and selection fields shared by detectors, matchers, auditors, and analyzers.

Name is required and bounded by MaxComponentNameLength; it must be valid UTF-8 with no control characters, because it reaches published documents where a newline would corrupt SPDX's line-oriented tag form. Whitespace inside a name is legal. The checks apply to the value as stored -- validation does not rewrite it -- so padding counts against the bound. The gate is validateComponentDescriptor, through each kind's Validate*Descriptor.

func (ComponentDescriptor) Label

func (d ComponentDescriptor) Label() string

Label returns the user-facing component label, falling back to Name.

type ComponentScope added in v0.15.0

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

ComponentScope is one component's lifetime: the context its constructor receives, and the cleanups it registers through HostContext.OnCleanup. A host creates one per component, passes Context to the module's New, and calls Close exactly when the component can no longer be used -- at the end of the command embedded, when the plugin is shut down managed -- so a component releases its resources the same way in both execution modes. The zero value is not usable; construct one with NewComponentScope.

func NewComponentScope added in v0.15.0

func NewComponentScope(parent context.Context, component string) *ComponentScope

NewComponentScope starts a lifetime for the named component, derived from parent: cancelling parent cancels the scope's context, but only Close runs the cleanups. The name prefixes every cleanup error.

func (*ComponentScope) Close added in v0.15.0

func (s *ComponentScope) Close() error

Close ends the lifetime: it cancels the scope's context, then runs every registered cleanup in reverse registration order, each at most once. A cleanup that fails or panics does not stop the rest; the failures are joined, each prefixed with the component name. A second Close runs nothing: it waits for the first to finish and returns its error, so no caller sees success while cleanups are still running.

func (*ComponentScope) Context added in v0.15.0

func (s *ComponentScope) Context() context.Context

Context returns the component's lifetime context: the one to pass to a module's New. It is cancelled when Close begins or when the parent is.

func (*ComponentScope) OnCleanup added in v0.15.0

func (s *ComponentScope) OnCleanup(fn func() error)

OnCleanup registers fn to run when the scope closes. After Close it runs fn at once, so a constructor still running when its lifetime ended -- cancelled mid-construction -- does not leak what it acquired late; that call's error has no Close left to report it and is dropped. A nil fn is ignored.

type ConsolidatedGraph

type ConsolidatedGraph struct {
	ExecutionTarget ExecutionTarget
	Graphs          *model.GraphContainer
	Manifests       []ConsolidatedManifest
	Subprojects     []ConsolidatedSubproject
}

ConsolidatedGraph describes a merged view above per-subproject graph results.

type ConsolidatedManifest

type ConsolidatedManifest struct {
	Entry          model.GraphEntry
	Subproject     Subproject
	DetectorName   string
	Origin         DetectorOrigin
	Technique      DetectorTechnique
	RootManifestID string
}

ConsolidatedManifest describes one selected manifest after detector-level deduplication and precedence rules have been applied.

type ConsolidatedSubproject

type ConsolidatedSubproject struct {
	Subproject      Subproject
	DetectorName    string
	RootManifestIDs []string
}

ConsolidatedSubproject describes one subproject included in a consolidated graph.

type DetectRequest

type DetectRequest = DetectionRequest

DetectRequest is the detector request payload exposed to plugins.

It aliases DetectionRequest so plugin code can name payload types by role while sharing the same transport shape Bomly core uses internally.

type DetectResponse

type DetectResponse = DetectionResult

DetectResponse is the detector response payload exposed to plugins.

It aliases DetectionResult so plugin code can name payload types by role while sharing the same transport shape Bomly core uses internally.

type DetectionRequest

type DetectionRequest struct {
	ProjectPath     string               `json:"projectPath,omitempty"`
	ExecutionTarget ExecutionTarget      `json:"executionTarget"`
	Subproject      Subproject           `json:"subproject"`
	Ecosystem       model.Ecosystem      `json:"ecosystem,omitempty"`
	PackageManager  model.PackageManager `json:"packageManager,omitempty"`
	// EnrichmentEnabled allows orchestration to request detector-time metadata
	// enrichment when a downstream command has opted into package enrichment.
	EnrichmentEnabled bool                  `json:"enrichmentEnabled,omitempty"`
	DetectorFilter    DetectorFilter        `json:"detectorFilter"`
	ScopeFilter       model.Scope           `json:"scopeFilter,omitempty"`
	Query             model.DependencyQuery `json:"query"`
	InstallFirst      bool                  `json:"installFirst,omitempty"`
	InstallArgs       []string              `json:"installArgs,omitempty"`
	CoreVersion       string                `json:"coreVersion,omitempty"`
	// AllowStdErrLogging tells a detector that the user enabled debug output
	// and accepts the detector's raw subprocess diagnostics in that output.
	AllowStdErrLogging bool `json:"allowStdErrLogging,omitempty"`
	// Stderr and Verbose are process-local fields used by built-in detectors.
	// Stderr is nil unless debug output is enabled. Verbose mirrors
	// AllowStdErrLogging for compatibility with existing detector code.
	Stderr  io.Writer `json:"-"`
	Verbose bool      `json:"-"`
	// Logger is a request-scoped logger injected by the pipeline, already
	// bound to the subproject and detector this request targets. It lets a
	// detector instance that is shared across concurrently-resolved
	// subprojects emit log lines that identify which subproject they belong
	// to. It is process-local and never serialized. Use DetectorLogger to
	// read it with a safe fallback.
	Logger *zap.Logger `json:"-"`
}

DetectionRequest defines input for dependency graph resolution.

func (DetectionRequest) DetectorLogger

func (r DetectionRequest) DetectorLogger(fallback *zap.Logger) *zap.Logger

DetectorLogger returns the most specific non-nil logger for this request: the request-scoped Logger injected by the pipeline (carrying subproject and detector context) when present, otherwise the supplied fallback (typically the detector's own instance logger), otherwise a no-op logger. It never returns nil, so callers can drop the usual "if logger == nil" guard.

type DetectionResult

type DetectionResult struct {
	SubprojectInfo      Subproject        `json:"subprojectInfo"`
	RootExecutionTarget ExecutionTarget   `json:"rootExecutionTarget"`
	DetectorName        string            `json:"detectorName,omitempty"`
	Origin              DetectorOrigin    `json:"origin,omitempty"`
	Technique           DetectorTechnique `json:"technique,omitempty"`
	// FallbackFrom names the planned primary detector that failed before a
	// fallback detector produced this result. Empty for routine applicability
	// hand-off between chained detectors.
	FallbackFrom string `json:"fallbackFrom,omitempty"`
	// FallbackReason is the human-readable cause of the primary detector's
	// failure, e.g. "not ready: java executable not found on PATH".
	FallbackReason string                `json:"fallbackReason,omitempty"`
	Graphs         *model.GraphContainer `json:"graphs,omitempty"`
	// Warnings are non-fatal problems the detector found while resolving: the
	// graphs above are usable, but something about the project will break or
	// degrade an install elsewhere. The engine fills in each warning's
	// Subproject and surfaces them alongside the ones it observes itself.
	Warnings []DetectorWarning `json:"warnings,omitempty"`
}

DetectionResult contains one or more manifest-scoped graphs.

func FilterDetectionResultByScope

func FilterDetectionResultByScope(result DetectionResult, scope model.Scope) (DetectionResult, error)

FilterDetectionResultByScope applies scope filtering to each graph entry in a detector result, discarding the report.

func FilterDetectionResultByScopeWithReport

func FilterDetectionResultByScopeWithReport(result DetectionResult, scope model.Scope) (DetectionResult, model.ScopeFilterReport, error)

FilterDetectionResultByScopeWithReport is FilterDetectionResultByScope, and also says which dependencies a runtime view kept across every entry because they asserted no scope. This is the variant a pipeline calls: it is the one hop that sees the whole result, so it is where a user-facing warning about how much the filter could not narrow can be raised once rather than per entry.

func (DetectionResult) ConsolidatedGraph

func (r DetectionResult) ConsolidatedGraph() (*model.Graph, error)

ConsolidatedGraph returns a single graph view for the resolve result.

type Detector

type Detector interface {
	Descriptor() DetectorDescriptor
	PackageManagerSupport() []PackageManagerSupport
	// Ready reports whether the detector can run for the given request. It
	// returns nil when ready and a non-nil error describing the reason
	// (e.g. a missing toolchain) otherwise. Implementations may perform
	// lightweight, cancellable I/O (such as probing for a runtime) and should
	// honor ctx.
	Ready(context.Context, DetectionRequest) error
	Applicable(context.Context, DetectionRequest) (bool, error)
	ResolveGraph(context.Context, DetectionRequest) (DetectionResult, error)
}

Detector resolves dependency information.

type DetectorDescriptor

type DetectorDescriptor struct {
	Name                string                 `json:"name"`
	DisplayName         string                 `json:"displayName,omitempty"`
	Aliases             []string               `json:"aliases,omitempty"`
	Tags                []string               `json:"tags,omitempty"`
	SupportedEcosystems []model.Ecosystem      `json:"supportedEcosystems,omitempty"`
	SupportedManagers   []model.PackageManager `json:"supportedManagers,omitempty"`
	// Version is the component's own release version; see
	// ComponentDescriptor.Version. Optional.
	Version string `json:"version,omitempty"`
	// Requires declares the pipeline inputs and host capabilities the
	// component needs; see Requirement. Optional: absent means legacy and
	// unspecified, never "needs nothing". Ready and Applicable still run.
	// Gate: Requirements.Validate, through the kind's Validate*Descriptor.
	Requires              Requirements            `json:"requires,omitempty"`
	Technique             DetectorTechnique       `json:"technique,omitempty"`
	PackageManagerSupport []PackageManagerSupport `json:"packageManagerSupport,omitempty"`
	FallbackDetectors     []string                `json:"fallbackDetectors,omitempty"`
	SupportsInstallFirst  bool                    `json:"supportsInstallFirst,omitempty"`
	// RemediationCapabilities advertises optional, read-only support for
	// package-manager-specific remediation strategies. Core calls the optional
	// provider only when this list is non-empty.
	RemediationCapabilities []RemediationCapability `json:"remediationCapabilities,omitempty"`
	// IgnoredDirectories lists directory basename globs (Go
	// path.Match syntax) that recursive subproject discovery must not descend
	// into because they hold third-party installs, vendored dependencies, or
	// build outputs for this detector's ecosystem (e.g. "node_modules",
	// "target"). Discovery aggregates these across every registered detector,
	// including external plugins. Optional; omitted by older plugins.
	IgnoredDirectories []string `json:"ignoredDirectories,omitempty"`
	// IgnoredDirectoryMarkers lists file names whose presence inside
	// a directory marks that directory as ignored during recursive discovery
	// regardless of its name (e.g. "pyvenv.cfg" identifies a Python
	// virtualenv). Optional; omitted by older plugins.
	IgnoredDirectoryMarkers []string `json:"ignoredDirectoryMarkers,omitempty"`
	// ConfigSchema optionally documents the detector's configuration block as
	// a JSON Schema. Build it with ConfigSchemaFor.
	ConfigSchema json.RawMessage `json:"configSchema,omitempty"`
}

DetectorDescriptor describes a detector registration.

func (DetectorDescriptor) Clone

Clone returns a deep copy of the detector descriptor.

func (DetectorDescriptor) Label

func (d DetectorDescriptor) Label() string

Label returns the user-facing detector label, falling back to Name.

type DetectorFilter

type DetectorFilter struct {
	Include []string `json:"Include,omitempty"`
	Exclude []string `json:"Exclude,omitempty"`
}

DetectorFilter narrows detector selection for a request.

The json tags keep their capitals. These fields carried no tag, so v1 peers send "Include" and "Exclude"; lowercasing one renames the wire field. TestWireV1FilterNamesKeepTheirCapitals fails if it happens.

func (DetectorFilter) Excludes

func (f DetectorFilter) Excludes(name string) bool

Excludes reports whether a detector name is explicitly denied.

func (DetectorFilter) Includes

func (f DetectorFilter) Includes(name string) bool

Includes reports whether a detector name is explicitly allowed.

type DetectorModule

type DetectorModule struct {
	Descriptor DetectorDescriptor
	Support    []PackageManagerSupport
	// TargetKinds lists the execution target kinds the detector supports.
	// Empty means the host derives the default [filesystem, git-repository],
	// mirroring the managed-plugin derivation.
	TargetKinds []ExecutionTargetKind
	New         func(context.Context, HostContext) (Detector, error)
}

DetectorModule declares one detector component: its static descriptor, package-manager support, and a constructor invoked once per execution.

type DetectorOrigin

type DetectorOrigin string

DetectorOrigin describes where a detector, matcher, or auditor is sourced from.

const (
	// CoreOrigin identifies components implemented directly in Bomly's own codebase.
	CoreOrigin DetectorOrigin = "core"
	// BundledOrigin identifies third-party components that are compiled into the Bomly binary (e.g. Syft, Grype).
	BundledOrigin DetectorOrigin = "bundled"
	// ExternalOrigin identifies components loaded as external plugins at runtime.
	ExternalOrigin DetectorOrigin = "external"
)

type DetectorRemediationProvider

type DetectorRemediationProvider interface {
	RemediationHints(context.Context, RemediationHintRequest) (RemediationHintResponse, error)
}

DetectorRemediationProvider optionally contributes read-only package-manager evidence after vulnerability enrichment.

type DetectorTechnique

type DetectorTechnique string

DetectorTechnique describes the resolution strategy used by a detector. Only meaningful for detectors; matchers and auditors leave this empty.

const (
	// ManifestTechnique reads a declarative dependency manifest file (e.g. package.json, Gemfile).
	ManifestTechnique DetectorTechnique = "manifest"
	// LockfileTechnique parses a deterministic lockfile (e.g. package-lock.json, yarn.lock).
	LockfileTechnique DetectorTechnique = "lockfile"
	// BuildToolTechnique invokes a build tool to resolve the live dependency graph.
	BuildToolTechnique DetectorTechnique = "build-tool"
	// SBOMTechnique ingests an existing SBOM document.
	SBOMTechnique DetectorTechnique = "sbom"
	// BinaryTechnique analyses a compiled binary or installed artifact.
	BinaryTechnique DetectorTechnique = "binary"
	// ContainerTechnique inspects a container image.
	ContainerTechnique DetectorTechnique = "container"
	// MultipleTechnique applies several of the above strategies depending on the target.
	MultipleTechnique DetectorTechnique = "multiple"
)

type DetectorWarning

type DetectorWarning struct {
	Type       DetectorWarningType `json:"type"`
	Code       DetectorWarningCode `json:"code,omitempty"`
	Source     string              `json:"source,omitempty"`
	Subproject string              `json:"subproject,omitempty"`
	Manifest   string              `json:"manifest,omitempty"`
	Message    string              `json:"message"`
}

DetectorWarning is one non-fatal problem found while detecting dependencies. Detectors return warnings alongside the graphs they resolve; the engine adds the ones it observes around them (a failed chain, a fallback). Every warning travels the same way to every surface, so a consumer never has to know which of the two produced it.

Source names the detector or tool the warning is about ("maven-detector", "pnpm"). Subproject and Manifest locate it when known; the engine fills in Subproject, so detectors only set Manifest.

func (DetectorWarning) DegradesCoverage

func (w DetectorWarning) DegradesCoverage() bool

DegradesCoverage reports whether this warning means the graph may be incomplete. It is shorthand for Type.DegradesCoverage.

type DetectorWarningCode

type DetectorWarningCode string

DetectorWarningCode identifies the specific check that produced a warning. It is empty for warnings the engine synthesizes from a detector failure, where Type already carries the full meaning.

const (
	// DetectorWarningCodeLockfileFormat means the committed lockfile's format
	// version disagrees with the package-manager version the project declares.
	DetectorWarningCodeLockfileFormat DetectorWarningCode = "lockfile-format-mismatch"
	// DetectorWarningCodeLockfileUnsupported means the project commits a
	// lockfile the declared package manager does not read.
	DetectorWarningCodeLockfileUnsupported DetectorWarningCode = "lockfile-unsupported"
	// DetectorWarningCodeEnginesConstraint means a declared engines constraint
	// contradicts another declaration in the same project.
	DetectorWarningCodeEnginesConstraint DetectorWarningCode = "engines-constraint-mismatch"
	// DetectorWarningCodeInstallGate means an install policy rejects versions by
	// age or publish date, so a freshly published fix version cannot install.
	DetectorWarningCodeInstallGate DetectorWarningCode = "install-policy-gate"
)

type DetectorWarningType

type DetectorWarningType string

DetectorWarningType classifies a detector warning by what it means for the run. It is the field policy decisions branch on: see DegradesCoverage.

const (
	// DetectorWarningResolutionFailure means a detector chain failed for a
	// subproject and the scan continued without that subproject's dependencies.
	DetectorWarningResolutionFailure DetectorWarningType = "resolution-failure"
	// DetectorWarningFallback means a fallback detector produced the graph after
	// the planned primary detector failed, so transitive dependencies may be
	// missing.
	DetectorWarningFallback DetectorWarningType = "fallback"
	// DetectorWarningPackageManager means the graph is sound, but the project's
	// package-manager configuration will break or degrade an install elsewhere —
	// typically in CI.
	DetectorWarningPackageManager DetectorWarningType = "package-manager"
)

func (DetectorWarningType) DegradesCoverage

func (t DetectorWarningType) DegradesCoverage() bool

DegradesCoverage reports whether the warning means the dependency graph may be incomplete, and therefore that findings may be missing. Consumers that require complete coverage before recording a decision — writing a finding baseline, for example — gate on this rather than on the presence of any warning: a package-manager mismatch says nothing about coverage.

type ExecutionMode

type ExecutionMode string

ExecutionMode identifies how a component instance is being executed.

const (
	// ExecutionEmbedded marks a component compiled into the host binary and
	// registered in-process.
	ExecutionEmbedded ExecutionMode = "embedded"
	// ExecutionManaged marks a component running in its own plugin process
	// managed by the host over the plugin transport.
	ExecutionManaged ExecutionMode = "managed"
)

type ExecutionTarget

type ExecutionTarget struct {
	Kind          ExecutionTargetKind `json:"kind,omitempty"`
	Location      string              `json:"location,omitempty"`
	RepositoryURL string              `json:"repositoryUrl,omitempty"`
	Ref           string              `json:"ref,omitempty"`
	// CommitSHA is the commit the scan actually ran against, resolved from
	// Ref by the host: Ref is what was asked for, CommitSHA is what was
	// found. Gate: NormalizeCommitSHA, applied by the producer. Optional;
	// empty when the target is not a revision of a repository.
	CommitSHA string `json:"commitSha,omitempty"`
}

ExecutionTarget names what one scan execution reads: a filesystem path, a repository at a ref, or a container image. Gate: CommitSHA passes NormalizeCommitSHA in the JSON codec on both directions, so a ref name or a padded hash a producer wrote in its place is cleared at the wire rather than carried as a commit; the other fields are trimmed.

func (ExecutionTarget) MarshalJSON added in v0.14.0

func (t ExecutionTarget) MarshalJSON() ([]byte, error)

MarshalJSON writes the gated form.

func (ExecutionTarget) Normalized added in v0.14.0

func (t ExecutionTarget) Normalized() ExecutionTarget

Normalized returns the target held to its gate.

func (*ExecutionTarget) UnmarshalJSON added in v0.14.0

func (t *ExecutionTarget) UnmarshalJSON(data []byte) error

UnmarshalJSON reads through the gate, so a managed component's payload cannot put a non-commit on CommitSHA.

type ExecutionTargetKind

type ExecutionTargetKind string

ExecutionTargetKind identifies the top-level source selected by the user for one scan execution.

const (
	// ExecutionTargetFilesystem points at a local filesystem path. The path may be a
	// directory or a single file depending on the selected scan target.
	ExecutionTargetFilesystem ExecutionTargetKind = "filesystem"
	// ExecutionTargetWorkingDirectory is kept as an alias for the existing local-path model.
	ExecutionTargetWorkingDirectory ExecutionTargetKind = ExecutionTargetFilesystem
	ExecutionTargetGitRepository    ExecutionTargetKind = "git-repository"
	ExecutionTargetContainerImage   ExecutionTargetKind = "container-image"
)

type FallbackDetector deprecated

type FallbackDetector interface {
	FallbackDetector() Detector
}

FallbackDetector optionally provides a fallback detector that should run when the primary detector cannot produce a result.

Deprecated: the host executes planned detector chains; fallback interfaces are no longer consulted. The interface is kept for one release so existing implementations keep compiling.

type FilesystemScope added in v0.16.0

type FilesystemScope string

FilesystemScope names an area of the filesystem a plugin touches, as a class rather than a path, because paths differ by machine and operating system while the question a user is answering -- does this read my project, write my home directory -- does not.

const (
	// FilesystemProject is the scan target: the project or checkout being
	// scanned.
	FilesystemProject FilesystemScope = "project"
	// FilesystemTemp is the operating system's temporary directory.
	FilesystemTemp FilesystemScope = "temp"
	// FilesystemCache is the user's cache directory (os.UserCacheDir), such
	// as a build or download cache a tool keeps there.
	FilesystemCache FilesystemScope = "cache"
	// FilesystemHome is the user's home directory beyond the cache.
	FilesystemHome FilesystemScope = "home"
	// FilesystemAny is anywhere the user can reach.
	FilesystemAny FilesystemScope = "any"
)

func (FilesystemScope) Known added in v0.16.0

func (s FilesystemScope) Known() bool

Known reports whether s is in this SDK's scope vocabulary.

type HostContext

type HostContext interface {
	Logger() *zap.Logger
	HTTPClient() *httpkit.ClientProvider
	Runtime() RuntimeInfo
	// DecodeConfig unmarshals the component's own configuration block into v.
	// Embedded execution sources it from the host config's kind-scoped
	// plugins.<kind>.<name> block; managed execution sources it from the
	// config file the host passes via BOMLY_PLUGIN_CONFIG_FILE. Identical
	// JSON semantics both ways.
	DecodeConfig(v any) error
	// OnCleanup registers fn to run once when the component's lifetime
	// ends, after the constructor's context is cancelled. Cleanups run in
	// reverse registration order, each at most once, and every one runs
	// even when an earlier one fails or panics; the failures are joined.
	// Register right after acquiring each resource -- a file, a temporary
	// directory, a goroutine, an idle HTTP transport -- so a constructor
	// that fails afterwards still releases what it acquired.
	//
	// Embedded, the lifetime is the host command's. Managed, it is the
	// plugin process's: cleanups run when the host shuts the plugin down,
	// within the transport's grace period, and not at all if the process is
	// killed outright. A cleanup registered after the lifetime has ended
	// runs at once. ComponentScope implements this for a host.
	OnCleanup(fn func() error)
}

HostContext is the only channel through which a component reaches host services. The same contract is satisfied by the embedded host (in-process registration) and the managed host (plugin subprocess), so a component written against it runs unchanged in both execution modes.

type InstallFirstDetector

type InstallFirstDetector interface {
	Install(context.Context, DetectionRequest) error
}

InstallFirstDetector optionally prepares dependencies before graph resolution.

type InstallResponse

type InstallResponse struct {
	Performed bool `json:"performed,omitempty"`
}

InstallResponse reports install-first execution details.

type MatchRequest

type MatchRequest struct {
	ProjectPath     string                 `json:"projectPath,omitempty"`
	ExecutionTarget ExecutionTarget        `json:"executionTarget"`
	SubprojectInfo  Subproject             `json:"subprojectInfo"`
	Ecosystem       model.Ecosystem        `json:"ecosystem,omitempty"`
	PackageManager  model.PackageManager   `json:"packageManager,omitempty"`
	Query           PackageQuery           `json:"query"`
	Graph           *model.Graph           `json:"graph,omitempty"`
	Registry        *model.PackageRegistry `json:"registry,omitempty"`
	Target          *model.DependencyNode  `json:"target,omitempty"`
	MatcherFilter   MatcherFilter          `json:"matcherFilter"`
	// AcceptPackageUpdates signals that the host understands
	// MatchResult.PackageUpdates. Matchers advertising
	// CapabilityPackageUpdates may return updates instead of a full registry
	// only when this is true.
	AcceptPackageUpdates bool      `json:"acceptPackageUpdates,omitempty"`
	Stderr               io.Writer `json:"-"`
}

MatchRequest defines input for a matcher. Matchers enrich the package Registry keyed by PURL; the dependency Graph provides identity and structure.

func (MatchRequest) Clone added in v0.15.0

func (r MatchRequest) Clone() MatchRequest

Clone returns a deep copy of the request that shares no mutable memory with it: the graph, registry and target are copied through their own Clone methods, and every slice is copied. Stderr is kept as is -- it is the host's writer, shared on purpose. A host calls Clone before each Ready, Applicable and Match call and commits the result only on success, so an embedded matcher that changes its request and then fails leaves the host's state as a managed one would, whose request crossed the wire as a copy.

type MatchResponse

type MatchResponse = MatchResult

MatchResponse is the matcher response payload exposed to plugins.

It aliases MatchResult so plugin code can name payload types by role while sharing the same transport shape Bomly core uses internally.

type MatchResult

type MatchResult struct {
	Registry       *model.PackageRegistry `json:"registry,omitempty"`
	PackageUpdates []*model.Package       `json:"packageUpdates,omitempty"`
	MatcherStats   MatcherStats           `json:"matcherStats,omitempty"`
}

MatchResult contains the package registry after matcher enrichment.

A matcher returns either Registry (the full enriched registry — the protocol v1 baseline) or, when the request set AcceptPackageUpdates, PackageUpdates: only the packages it touched. The host merges updates into its registry by PURL. When Registry is non-nil it wins and PackageUpdates is ignored.

type Matcher

type Matcher interface {
	Descriptor() MatcherDescriptor
	// Ready reports whether the matcher can run for the given request. It
	// returns nil when ready and a non-nil error describing the reason
	// otherwise. Implementations may perform lightweight, cancellable I/O and
	// should honor ctx.
	Ready(context.Context, MatchRequest) error
	Applicable(context.Context, MatchRequest) (bool, error)
	Match(context.Context, MatchRequest) (MatchResult, error)
}

Matcher enriches registry packages with license and vulnerability data.

type MatcherDescriptor

type MatcherDescriptor struct {
	Name                string                 `json:"name"`
	DisplayName         string                 `json:"displayName,omitempty"`
	Aliases             []string               `json:"aliases,omitempty"`
	Tags                []string               `json:"tags,omitempty"`
	SupportedEcosystems []model.Ecosystem      `json:"supportedEcosystems,omitempty"`
	SupportedManagers   []model.PackageManager `json:"supportedManagers,omitempty"`
	// Version is the component's own release version; see
	// ComponentDescriptor.Version. Optional.
	Version string `json:"version,omitempty"`
	// Requires declares the pipeline inputs and host capabilities the
	// component needs; see Requirement. Optional: absent means legacy and
	// unspecified, never "needs nothing". Ready and Applicable still run.
	// Gate: Requirements.Validate, through the kind's Validate*Descriptor.
	Requires Requirements `json:"requires,omitempty"`
	// Capabilities advertises optional protocol features this matcher
	// supports, such as CapabilityPackageUpdates.
	Capabilities []string `json:"capabilities,omitempty"`
	// ConfigSchema optionally documents the matcher's configuration block as
	// a JSON Schema. Build it with ConfigSchemaFor.
	ConfigSchema json.RawMessage `json:"configSchema,omitempty"`
}

MatcherDescriptor describes a matcher registration.

func (MatcherDescriptor) Clone added in v0.16.0

Clone returns a deep copy of the descriptor: every slice, the declared requirements and the config schema are copied, so a host that keeps a descriptor cannot have it changed by the component that returned it.

func (MatcherDescriptor) Label

func (d MatcherDescriptor) Label() string

Label returns the user-facing matcher label, falling back to Name.

type MatcherFilter

type MatcherFilter struct {
	Include []string `json:"Include,omitempty"`
	Exclude []string `json:"Exclude,omitempty"`
}

MatcherFilter narrows matcher selection for a request.

The json tags keep their capitals. These fields carried no tag, so v1 peers send "Include" and "Exclude"; lowercasing one renames the wire field. TestWireV1FilterNamesKeepTheirCapitals fails if it happens.

func (MatcherFilter) Excludes

func (f MatcherFilter) Excludes(name string) bool

Excludes reports whether a matcher name is explicitly denied.

func (MatcherFilter) Includes

func (f MatcherFilter) Includes(name string) bool

Includes reports whether a matcher name is explicitly allowed.

type MatcherModule

type MatcherModule struct {
	Descriptor MatcherDescriptor
	New        func(context.Context, HostContext) (Matcher, error)
}

MatcherModule declares one matcher component.

type MatcherStats

type MatcherStats struct {
	Name              string `json:"name"`
	DisplayName       string `json:"displayName,omitempty"`
	MatchedPackages   int    `json:"matchedPackages,omitempty"`
	UnmatchedPackages int    `json:"unmatchedPackages,omitempty"`
	Licenses          int    `json:"licenses,omitempty"`
	Vulnerabilities   int    `json:"vulnerabilities,omitempty"`
}

MatcherStats describes one completed matcher run and optional summary counts.

type Module

type Module struct {
	Kind     PluginKind
	Detector *DetectorModule
	Matcher  *MatcherModule
	Auditor  *AuditorModule
	Analyzer *AnalyzerModule
}

Module is the execution-neutral packaging of one component. Exactly one of the role fields must be set, and it must match Kind. The same Module value can be registered embedded by the host or served managed via plugin.ServeModule.

type PackageManagerSupport

type PackageManagerSupport struct {
	PackageManager   model.PackageManager `json:"packageManager"`
	EvidencePatterns []string             `json:"evidencePatterns,omitempty"`
	// MultiModule marks that the detector natively expands nested
	// workspace/reactor modules for this package manager from a root manifest
	// (Maven reactors, npm/pnpm/yarn workspaces, cargo workspace members,
	// ...). Recursive discovery prunes nested subprojects for the same
	// package manager below a directory where a native multi-module manager
	// was detected, so the same modules are not scanned twice. Optional;
	// omitted by older plugins.
	MultiModule bool `json:"multiModule,omitempty"`
}

PackageManagerSupport records package-manager discovery metadata for a detector. External detector plugins return this so Bomly can include them in subproject discovery and scan planning before the detector runs.

func Support

func Support(manager model.PackageManager, evidencePatterns ...string) PackageManagerSupport

Support returns package-manager discovery metadata for a detector.

func (PackageManagerSupport) WithMultiModule

func (s PackageManagerSupport) WithMultiModule() PackageManagerSupport

WithMultiModule returns a copy of the support entry marked as natively expanding nested workspace/reactor modules from a root manifest, opting the package manager into recursive-discovery ancestor pruning.

type PackageManagerSupporter

type PackageManagerSupporter interface {
	PackageManagerSupport() []PackageManagerSupport
}

PackageManagerSupporter reports detector package-manager discovery metadata.

type PackageQuery

type PackageQuery struct {
	Name string `json:"name,omitempty"`
	ID   string `json:"id,omitempty"`
}

PackageQuery identifies a specific package target.

type PluginKind

type PluginKind string

PluginKind identifies the runtime role implemented by a plugin.

const (
	// PluginKindDetector resolves dependency graphs.
	PluginKindDetector PluginKind = "detector"
	// PluginKindMatcher enriches resolved packages.
	PluginKindMatcher PluginKind = "matcher"
	// PluginKindAuditor evaluates findings and risk.
	PluginKindAuditor PluginKind = "auditor"
	// PluginKindAnalyzer runs code analysis (e.g. reachability) over the
	// matched graph and annotates registry vulnerability entries.
	PluginKindAnalyzer PluginKind = "analyzer"
)

type PluginTargetType

type PluginTargetType string

PluginTargetType identifies the discovery target families a plugin supports.

type ReachabilityStats

type ReachabilityStats struct {
	Reachable     int `json:"reachable,omitempty"`
	Unreachable   int `json:"unreachable,omitempty"`
	Unknown       int `json:"unknown,omitempty"`
	NotApplicable int `json:"not_applicable,omitempty"`
}

ReachabilityStats tallies the per-analyzer outcome distribution.

type ReadyResponse

type ReadyResponse struct {
	Ready bool `json:"ready"`
	// Reason explains why the plugin is not ready. It is ignored when Ready is
	// true and surfaced to users (and resolution errors) when Ready is false.
	Reason string `json:"reason,omitempty"`
}

ReadyResponse reports whether a plugin is ready to run.

type RemediationCapability

type RemediationCapability struct {
	SupportedManagers []model.PackageManager    `json:"supportedManagers,omitempty"`
	Actions           []model.RemediationAction `json:"actions,omitempty"`
}

RemediationCapability advertises the occurrence-scoped strategies for which a detector can provide package-manager-specific evidence. Capabilities do not grant authority to choose final remediation or modify a project.

type RemediationHint

type RemediationHint struct {
	DependencyRef string                    `json:"dependencyRef"`
	ManifestPath  string                    `json:"manifestPath,omitempty"`
	Strategies    []RemediationStrategyHint `json:"strategies,omitempty"`
}

RemediationHint contributes package-manager evidence for one detected dependency occurrence.

type RemediationHintRequest

type RemediationHintRequest struct {
	ProjectPath string                 `json:"projectPath,omitempty"`
	Detection   DetectionResult        `json:"detection"`
	Registry    *model.PackageRegistry `json:"registry,omitempty"`
}

RemediationHintRequest supplies completed detection and enrichment evidence to an optional detector remediation provider.

type RemediationHintResponse

type RemediationHintResponse struct {
	Hints       []RemediationHint `json:"hints,omitempty"`
	Diagnostics []string          `json:"diagnostics,omitempty"`
}

RemediationHintResponse contains optional read-only detector evidence.

type RemediationStrategyHint

type RemediationStrategyHint struct {
	Action model.RemediationAction `json:"action"`
	Advice string                  `json:"advice,omitempty"`
}

RemediationStrategyHint is read-only detector evidence that a strategy is available for one occurrence. Advice is detector-owned, action-specific package-manager guidance. For example, a transitive-override hint can explain the manager's override syntax, while a lockfile-refresh hint can provide the normal refresh command. Core validates and bounds this text, then retains authority over the final action.

type Requirement added in v0.16.0

type Requirement string

Requirement names one class of pipeline input, or one host capability, a component needs before it can do useful work: a source tree to read, a dependency graph to walk, vulnerability records to annotate. A descriptor declares them in Requires so a host can explain an impossible plan -- "this analyzer needs a source tree and the target is an SBOM" -- before running anything, and so generated documentation can say what a component needs.

A requirement names data, never a provider. A matcher may require vulnerability records; it may not require "plugin X", because which component produces the records is the host's selection and fallback policy, and a named dependency would turn the fixed pipeline into a service scheduler. The vocabulary has no way to spell a provider.

Declarations are advisory to the plan and never replace the runtime checks: a host that finds every requirement satisfied still calls Ready and Applicable, which remain authoritative. A descriptor that declares nothing is legacy -- its requirements are unspecified, not empty -- and a host treats it exactly as it treated every component before Requires existed.

Tokens are versioned ("<name>-v<N>") and the vocabulary is open: a token this SDK does not know still validates if it is well formed, survives the wire, and must be treated as unsatisfied by a host that does not know it, since a host cannot vouch for an input it has never heard of. A new meaning gets a new token or a new version, never a changed meaning for an existing one.

const (
	// RequirementSourceTree: the target is a source tree the component can
	// read -- a filesystem checkout or a Git repository -- rather than an
	// SBOM document or a container image. Reachability analyzers and
	// lockfile detectors need it.
	RequirementSourceTree Requirement = "source-tree-v1"
	// RequirementDependencyGraph: the request carries a dependency graph
	// with at least one dependency node, produced by an earlier stage.
	RequirementDependencyGraph Requirement = "dependency-graph-v1"
	// RequirementVulnerabilityRecords: the registry carries vulnerability
	// records, which a vulnerability matcher earlier in the pipeline
	// supplies. Analyzers that annotate reachability need it.
	RequirementVulnerabilityRecords Requirement = "vulnerability-records-v1"
)

func KnownRequirements added in v0.16.0

func KnownRequirements() []Requirement

KnownRequirements returns every requirement this SDK defines, sorted.

func (Requirement) Known added in v0.16.0

func (r Requirement) Known() bool

Known reports whether r is in this SDK's vocabulary. A host must treat a requirement that is not known as unsatisfied.

type Requirements added in v0.16.0

type Requirements []Requirement

Requirements is a descriptor's declared prerequisite list. Its JSON codec writes and reads it deduplicated and sorted, so two descriptors that declare the same set encode the same way and a host never sees order as meaning; it never drops an entry, so a token the host does not know reaches the host's conservative handling instead of disappearing.

func (Requirements) MarshalJSON added in v0.16.0

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

MarshalJSON writes the normalized list.

func (Requirements) Normalized added in v0.16.0

func (r Requirements) Normalized() Requirements

Normalized returns the requirements deduplicated and sorted; nil when empty, so an empty declaration and an absent one encode alike.

func (*Requirements) UnmarshalJSON added in v0.16.0

func (r *Requirements) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a list and normalizes it. The input is bounded before it is parsed, and the decoded list is held to MaxRequirements before it is deduplicated, so a repeated token cannot pass the bound by collapsing.

func (Requirements) Unsatisfied added in v0.16.0

func (r Requirements) Unsatisfied(available []Requirement) Requirements

Unsatisfied returns the requirements in r that available does not contain, normalized. available is what the host can vouch for at the point it plans the component -- the requirements it knows and finds met -- so a token the host does not know is never in it and always comes back unsatisfied. A nil result means every declared requirement is met; it says nothing about a legacy descriptor that declared none.

func (Requirements) Validate added in v0.16.0

func (r Requirements) Validate() error

Validate checks the declaration's shape: at most MaxRequirements tokens, each well formed and at most MaxRequirementLength bytes. It does not require a token to be known -- the vocabulary is open -- so a descriptor written against a newer SDK still validates on an older host.

type RuntimeInfo

type RuntimeInfo struct {
	// CoreVersion is the host core version when known; empty otherwise.
	CoreVersion string
	// Execution reports whether the component runs embedded or managed.
	Execution ExecutionMode
}

RuntimeInfo describes the host runtime a component executes under.

type Subproject

type Subproject struct {
	ExecutionTarget         ExecutionTarget        `json:"executionTarget"`
	RelativePath            string                 `json:"relativePath,omitempty"`
	PrimaryDetector         string                 `json:"primaryDetector,omitempty"`
	DetectedPackageManagers []model.PackageManager `json:"detectedPackageManagers,omitempty"`
	PlannedDetectors        []string               `json:"plannedDetectors,omitempty"`
	Ecosystem               model.Ecosystem        `json:"ecosystem,omitempty"`
}

Subproject identifies one package-manager root discovered beneath the execution target.

func (Subproject) Clone added in v0.15.0

func (s Subproject) Clone() Subproject

Clone returns a deep copy of the subproject: its slices are copied, so a component handed the copy cannot reorder the host's planned detectors.

func (Subproject) PrimaryPackageManager

func (s Subproject) PrimaryPackageManager() model.PackageManager

PrimaryPackageManager returns the first entry in DetectedPackageManagers, or PackageManagerUnknown if the list is empty.

Jump to

Keyboard shortcuts

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