Documentation
¶
Overview ¶
Package model is Bomly's domain model: the dependency graph and its node kinds, package records and the PURL-keyed registry, vulnerabilities and findings, the controlled vocabularies (ecosystems, package managers, languages, scopes), and the normalization, merge, and policy rules that every producer and consumer of those values shares.
The central types deliberately separate pipeline stages. DependencyNode is a detection-time graph node with identity, locations, scopes, and edges. PackageRegistry is a PURL-keyed set of deduplicated Package records that matchers enrich once per package version. Vulnerability records are OSV-aligned package enrichment data, including Bomly fields such as CVSS, EPSS, KEV, fixed versions, affected symbols, and reachability. Finding is a reference-style audit result: it points back to packages by PURL and, for vulnerability findings, to Vulnerability.ID rather than copying the whole package or advisory payload.
Coordinates is the shared embedded identity shape used by DependencyNode and Package. Prefer canonical PURLs, fill Coordinates where possible, and use typed values such as Ecosystem, PackageManager, PackageType, Scope, and SeverityLevel instead of raw strings. PackageManager is string-backed for compatibility; use PackageManagerOther or a custom PackageManager value when Bomly does not yet have a first-class constant for a package manager.
Node identity is derived, never hand-assembled (ADR-0041): the constructors are the only mint -- a dependency node's ID is its canonical package URL (custom purl types are first-class; express any ecosystem as a purl type), and module and manifest nodes carry kind-qualified canonical paths. Never build a node ID by string concatenation.
Attribution is per site, not per package. A package's scope and directness belong to the location it was found at: in a workspace the same version is a direct development dependency of one module and a transitive runtime dependency of another, so a node's unions answer neither question. PackageLocation carries the module root, scopes, and relationship; reachability is per-module-root evidence with the vulnerability annotation as the derived summary; and SelectUsages joins the two within one module root so a conjunctive question is a statement about a usage that exists. Read scopes through AttributedScopes rather than the node field.
Merges are classed rather than hand-written. MergeFillGap, MergeUnion, and MergeStrongest name the three rules every field in this model follows, and each field declares which class it is in. A merge written by hand is where this model has repeatedly lost data -- a first-wins rule dropping a better value, an early return leaving an ungated claim visible, an unsorted result making a document's bytes depend on read order -- so fixing a class is preferred to fixing a field.
Metadata maps carry what the typed fields do not, and the "bomly." prefix is reserved for this project (IsReservedMetadataKey). A value that lives only in a metadata map is invisible to every gate -- not normalized, not validated, not merged by a declared rule, not projected to either document format -- so anything a typed field can hold belongs in the typed field.
Every value here is also a wire value: these structs are the JSON payloads of the bomly.plugin.v1 protocol, so their tags are the wire schema and grow only additively. The component contract that carries them lives in the plugin package; the managed transport in the runtime package.
Index ¶
- Constants
- Variables
- func BuildPackageURL(purlType, namespace, name, version string) string
- func BuildPackageURLFor(ecosystem Ecosystem, manager PackageManager, namespace, name, version string) string
- func CanonicalPackageURLFromParts(existingPURL string, ecosystem Ecosystem, packageManager PackageManager, ...) string
- func CanonicalRepoPath(value string) (string, error)
- func CanonicalizePackageURL(value string) string
- func ContainsControlChar(value string) bool
- func CopyEdgesInto(dst, src *Graph, rename func(string) string) error
- func CycloneDXScope(scopes []Scope) string
- func CycloneDXScopeForExport(scopes []Scope, sourceScope string) string
- func EncodeScopeSet(scopes []Scope) string
- func FilterGraphByScopeWithReport(src *Graph, scope Scope) (*Graph, ScopeFilterReport, error)
- func FindingPolicyStatusRank(status FindingPolicyStatus) (int, bool)
- func IsNilNode(node GraphNode) bool
- func IsProjectOwned(node GraphNode) bool
- func IsReservedMetadataKey(key string) bool
- func MergeFillGap[T comparable](current, next T, publishable func(T) bool) T
- func MergeGraph(dst, src *Graph) error
- func MergeStrongest[T comparable](current, next T, rank func(T) int) T
- func MergeUnion[T any](current, next []T, key func(T) string, publishable func(T) (T, bool)) []T
- func NodeDisplayName(node GraphNode) string
- func NodePURL(node GraphNode) string
- func NodeVersion(node GraphNode) string
- func NormalizeCoordinates(pkg *Coordinates) []string
- func NormalizeCopyright(value string) string
- func NormalizeDescription(value string) string
- func NormalizeDocumentFormat(value string) string
- func NormalizeHomepage(value string) string
- func NormalizeOriginURL(raw string, repository bool) (string, bool)
- func NormalizeSourceScope(value string) string
- func NormalizeURL(raw string, form URLForm) (string, bool)
- func PackageURLBase(value string) string
- func PackageURLTypeForValues(values ...any) string
- func ReservedMetadataKeys(metadata map[string]any) []string
- func ScopeSetMatches(scopes []Scope, want Scope) bool
- func SetDetectionLicenses(dep *DependencyNode, licenses []PackageLicense)
- func SeverityMeets(candidate SeverityLevel, threshold string) bool
- func SeverityRank(severity SeverityLevel) int
- func SortDependencyDetailTransitions(transitions []DependencyDetailTransition)
- type Affected
- type AffectedSymbol
- type Assertions
- type CVSSScore
- type CWE
- type CallFrame
- type CallPath
- type Contact
- type ContactKind
- type Coordinates
- type DependencyDetailField
- type DependencyDetailReviewReason
- type DependencyDetailTransition
- type DependencyEdge
- type DependencyNode
- func AsDependencyNode(node GraphNode) (*DependencyNode, bool)
- func DependencyNodesOf(list []GraphNode) []*DependencyNode
- func NewDependencyNode(coords Coordinates) (*DependencyNode, error)
- func NewDependencyNodeFrom(proto DependencyNode) (*DependencyNode, error)
- func NewDependencyNodeFromPURL(rawPURL string) (*DependencyNode, error)
- func (n *DependencyNode) AddScope(scope Scope)
- func (n *DependencyNode) AttributedScopes() []Scope
- func (n *DependencyNode) Clone() *DependencyNode
- func (n *DependencyNode) CloneNode() GraphNode
- func (n *DependencyNode) DisplayName() string
- func (n *DependencyNode) HasScope(scope Scope) bool
- func (n *DependencyNode) Kind() NodeKind
- func (n *DependencyNode) LocationScopes() []Scope
- func (n *DependencyNode) MarshalJSON() ([]byte, error)
- func (n *DependencyNode) MatchesScopeFilter(want Scope) bool
- func (n *DependencyNode) NodeID() string
- func (n *DependencyNode) NodeLocations() []PackageLocation
- func (n *DependencyNode) NodeWarnings() []NodeWarning
- func (n *DependencyNode) PURL() purlkit.PURL
- func (n *DependencyNode) PrimaryScope() Scope
- func (n *DependencyNode) QualifiedName() string
- func (d *DependencyNode) RegistryMatchEligible() bool
- func (n *DependencyNode) SyncScopesFromLocations()
- func (n *DependencyNode) UnmarshalJSON(data []byte) error
- type DependencyOrigin
- type DependencyQuery
- type DependencyRelationship
- type DependencySource
- type Diff
- type Digest
- type DigestAlgorithm
- type DigestSubject
- type DocumentAssertions
- type DocumentSource
- type DocumentTool
- type EPSSScore
- type Ecosystem
- type EcosystemFilter
- type EdgeKind
- type ExternalReference
- type ExternalReferenceCategory
- type FailOnConstraint
- type FailOnKind
- type Finding
- type FindingKind
- type FindingPolicyDecision
- type FindingPolicyResolver
- type FindingPolicyStatus
- type FixAvailable
- type FixAvailableKind
- type FixState
- type Graph
- func (g *Graph) AddEdge(fromID, toID string) error
- func (g *Graph) AddNode(node GraphNode) error
- func (g *Graph) AddTypedEdge(fromID, toID string, kind EdgeKind) error
- func (g *Graph) CollectPathsTo(targetID string) ([]Path, error)
- func (g *Graph) DependencyNode(id string) (*DependencyNode, bool)
- func (g *Graph) DependencyNodes() []*DependencyNode
- func (g *Graph) Dependents(id string) ([]GraphNode, error)
- func (g *Graph) DirectDependencies(id string) ([]GraphNode, error)
- func (g *Graph) EdgeKindOf(fromID, toID string) EdgeKind
- func (g *Graph) InsertNode(node GraphNode) (GraphNode, error)
- func (g *Graph) Leaves() []GraphNode
- func (g *Graph) ManifestNodes() []*ManifestNode
- func (g *Graph) MarshalJSON() ([]byte, error)
- func (g *Graph) ModuleNodes() []*ModuleNode
- func (g *Graph) Node(id string) (GraphNode, bool)
- func (g *Graph) Nodes() []GraphNode
- func (g *Graph) PrettyString() string
- func (g *Graph) PrettyTree() string
- func (g *Graph) RemoveEdge(fromID, toID string) bool
- func (g *Graph) RemoveNode(id string) bool
- func (g *Graph) Roots() []GraphNode
- func (g *Graph) Size() int
- func (g *Graph) TopologicalSort() ([]GraphNode, error)
- func (g *Graph) UnmarshalJSON(data []byte) error
- func (g *Graph) WalkDependencyNodes(fn func(*DependencyNode) bool)
- func (g *Graph) WalkEdges(fn func(from, to GraphNode) bool)
- func (g *Graph) WalkNodes(fn func(GraphNode) bool)
- func (g *Graph) WalkTypedEdges(fn func(from, to GraphNode, kind EdgeKind) bool)
- type GraphContainer
- type GraphEntry
- type GraphNode
- type ImpactAnalysisJustification
- type ImpactAnalysisResponse
- type ImpactAnalysisState
- type KnownExploited
- type Language
- type LicenseType
- type LocatorKind
- type ManifestKind
- type ManifestMetadata
- type ManifestNode
- type ModuleNode
- type NPMPackageMetadata
- type NodeKind
- type NodeWarning
- type NodeWarningCode
- type Package
- func (p *Package) Clone() *Package
- func (p *Package) DisplayName() string
- func (p *Package) IdentityKey() string
- func (p *Package) LicenseValues() []string
- func (p Package) MarshalJSON() ([]byte, error)
- func (p *Package) MergeFrom(src *Package)
- func (p *Package) NormalizeAssertions()
- func (p *Package) QualifiedName() string
- func (p *Package) UnmarshalJSON(data []byte) error
- type PackageAttestation
- type PackageEOL
- type PackageLicense
- type PackageLocation
- type PackageManager
- type PackageNodeIndex
- type PackageRegistry
- func (r *PackageRegistry) Add(pkg *Package) *Package
- func (r *PackageRegistry) AddEntryPackages(entries []GraphEntry)
- func (r *PackageRegistry) All() []*Package
- func (r *PackageRegistry) Ensure(purl string) *Package
- func (r *PackageRegistry) Get(purl string) (*Package, bool)
- func (r *PackageRegistry) Len() int
- func (r *PackageRegistry) MarshalJSON() ([]byte, error)
- func (r *PackageRegistry) Merge(other *PackageRegistry)
- func (r *PackageRegistry) UnmarshalJSON(data []byte) error
- type PackageRemediation
- type PackageRemediationStatus
- type PackageRemediationSuggestion
- type PackageScorecard
- type PackageScorecardCheck
- type PackageType
- type Path
- type RangeEvent
- type Reachability
- type ReachabilityConfidence
- type ReachabilityEvidence
- type ReachabilityStatus
- type ReachabilityTier
- type Reference
- type ReferenceType
- type RemediationAction
- type ResolutionFallback
- type ResolutionMetadata
- type ResolutionMethod
- type RiskBand
- type RiskScore
- type RootAttribution
- type RootAttributor
- type Scope
- type ScopeFilterReport
- type ScopeSetDecoding
- type Severity
- type SeverityLevel
- type SeverityType
- type SourcePosition
- type SymbolKind
- type URLForm
- type Usage
- type UsageFilter
- type VEXStatus
- type VersionChange
- type VersionRange
- type VersionRangeType
- type Vulnerability
- func (v Vulnerability) Clone() Vulnerability
- func (v Vulnerability) IsExploitable() bool
- func (v Vulnerability) MarshalJSON() ([]byte, error)
- func (v Vulnerability) MatchesConstraints(constraints []FailOnConstraint) bool
- func (v Vulnerability) Normalized() Vulnerability
- func (v *Vulnerability) UnmarshalJSON(data []byte) error
- type VulnerabilityAnalysis
- func (a *VulnerabilityAnalysis) Clone() *VulnerabilityAnalysis
- func (a VulnerabilityAnalysis) IsEmpty() bool
- func (a VulnerabilityAnalysis) MarshalJSON() ([]byte, error)
- func (a VulnerabilityAnalysis) Normalized() (VulnerabilityAnalysis, bool)
- func (a *VulnerabilityAnalysis) UnmarshalJSON(data []byte) error
Examples ¶
Constants ¶
const ( // MaxPayloadBytes is the most a graph or registry payload may occupy on // the wire. It equals the SBOM ingest cap in package sbom: a graph is // what one ingestable document decodes to, and a payload that could not // have come from one is not accepted either. MaxPayloadBytes = 256 << 20 // MaxGraphNodes bounds the nodes of one graph payload. The largest real // workspaces resolve to a few tens of thousands of dependencies; this is // five times that, and a decoder that admits it still allocates in // proportion to a count it has checked. MaxGraphNodes = 1 << 18 // MaxGraphEdges bounds the edges of one graph payload: eight per node at // the node bound. Lockfile graphs average two to four edges a node, and // a dense workspace stays well under eight. MaxGraphEdges = 1 << 21 // MaxRegistryPackages bounds one registry payload. A registry holds one // package per distinct package URL and never outgrows the dependency // nodes that seed it. MaxRegistryPackages = MaxGraphNodes )
Decode bounds. A payload past any of them is refused before it is materialized, so what a reader allocates is bounded by what it accepted, not by what it was sent. The numbers are deliberately dumb -- bytes and counts -- and are frozen once pinned; there is nothing to tune in them.
const ( // ImpactAnalysisStateResolved: the vulnerability has been remediated. ImpactAnalysisStateResolved = ImpactAnalysisState(cdx.IASResolved) // ImpactAnalysisStateResolvedWithPedigree: the vulnerability has been // remediated and evidence of the changes are provided in the affected // components pedigree containing verifiable commit history and/or // diff(s). ImpactAnalysisStateResolvedWithPedigree = ImpactAnalysisState(cdx.IASResolvedWithPedigree) // ImpactAnalysisStateExploitable: the vulnerability may be directly or // indirectly exploitable. ImpactAnalysisStateExploitable = ImpactAnalysisState(cdx.IASExploitable) // ImpactAnalysisStateInTriage: the vulnerability is being investigated. ImpactAnalysisStateInTriage = ImpactAnalysisState(cdx.IASInTriage) // ImpactAnalysisStateFalsePositive: the vulnerability is not specific to // the component or service and was falsely identified or associated. ImpactAnalysisStateFalsePositive = ImpactAnalysisState(cdx.IASFalsePositive) // ImpactAnalysisStateNotAffected: the component or service is not // affected by the vulnerability. Justification should be specified for // all not_affected cases. ImpactAnalysisStateNotAffected = ImpactAnalysisState(cdx.IASNotAffected) )
const ( // ImpactAnalysisJustificationCodeNotPresent: the code has been removed // or tree-shaked. ImpactAnalysisJustificationCodeNotPresent = ImpactAnalysisJustification(cdx.IAJCodeNotPresent) // ImpactAnalysisJustificationCodeNotReachable: the vulnerable code is // not invoked at runtime. ImpactAnalysisJustificationCodeNotReachable = ImpactAnalysisJustification(cdx.IAJCodeNotReachable) // ImpactAnalysisJustificationRequiresConfiguration: exploitability // requires a configurable option to be set/unset. ImpactAnalysisJustificationRequiresConfiguration = ImpactAnalysisJustification(cdx.IAJRequiresConfiguration) // ImpactAnalysisJustificationRequiresDependency: exploitability requires // a dependency that is not present. ImpactAnalysisJustificationRequiresDependency = ImpactAnalysisJustification(cdx.IAJRequiresDependency) // ImpactAnalysisJustificationRequiresEnvironment: exploitability // requires a certain environment which is not present. ImpactAnalysisJustificationRequiresEnvironment = ImpactAnalysisJustification(cdx.IAJRequiresEnvironment) // ImpactAnalysisJustificationProtectedByCompiler: exploitability // requires a compiler flag to be set/unset. ImpactAnalysisJustificationProtectedByCompiler = ImpactAnalysisJustification(cdx.IAJProtectedByCompiler) // ImpactAnalysisJustificationProtectedAtRuntime: exploits are prevented // at runtime. ImpactAnalysisJustificationProtectedAtRuntime = ImpactAnalysisJustification(cdx.IAJProtectedAtRuntime) // ImpactAnalysisJustificationProtectedAtPerimeter: attacks are blocked // at physical, logical, or network perimeter. ImpactAnalysisJustificationProtectedAtPerimeter = ImpactAnalysisJustification(cdx.IAJProtectedAtPerimeter) // ImpactAnalysisJustificationProtectedByMitigatingControl: preventative // measures have been implemented that reduce the likelihood and/or // impact of the vulnerability. ImpactAnalysisJustificationProtectedByMitigatingControl = ImpactAnalysisJustification(cdx.IAJProtectedByMitigatingControl) )
const ( // ImpactAnalysisResponseCanNotFix: can not fix. ImpactAnalysisResponseCanNotFix = ImpactAnalysisResponse(cdx.IARCanNotFix) // ImpactAnalysisResponseWillNotFix: will not fix. ImpactAnalysisResponseWillNotFix = ImpactAnalysisResponse(cdx.IARWillNotFix) // ImpactAnalysisResponseUpdate: update to a different revision or release. ImpactAnalysisResponseUpdate = ImpactAnalysisResponse(cdx.IARUpdate) // ImpactAnalysisResponseRollback: revert to a previous revision or release. ImpactAnalysisResponseRollback = ImpactAnalysisResponse(cdx.IARRollback) // ImpactAnalysisResponseWorkaroundAvailable: there is a workaround // available. ImpactAnalysisResponseWorkaroundAvailable = ImpactAnalysisResponse(cdx.IARWorkaroundAvailable) )
const CycloneDXScopeProperty = "bomly:scopes"
CycloneDXScopeProperty is the property name carrying the full scope set through a CycloneDX document, so the projection below is not a one-way door.
The "bomly:" prefix follows the CycloneDX guidance that property names be namespaced by their producer, which is what keeps this from colliding with another tool's property of the same purpose.
const (
ExploitabilityValueExploitable = "exploitable"
)
ExploitabilityValueExploitable constraint values currently supported.
const GenericFallbackTypeQualifier = "bomly_source_type"
GenericFallbackTypeQualifier names the package URL type that could not express a package whose identity fell back to pkg:generic.
It is prefixed because it is this project's, not the specification's: a consumer reading an exported document should be able to tell a Bomly annotation from a purl-spec qualifier at a glance.
const MaxComponentNameLength = 256
MaxComponentNameLength bounds a component descriptor name, in bytes.
A component name is not only a registry key: it is written verbatim into published output as the source of a license claim (PackageLicense.Source), so its domain is what publication can carry. The two gates used to disagree -- descriptor validation asked only that a name be non-blank, while the license source was bounded -- so a 257-byte matcher was a valid component whose provenance the source gate silently erased. maxLicenseSourceLength references this constant so the two cannot drift again.
256 bytes: a real component name is a few dozen characters, and the allowance covers a long descriptive one without admitting a value that is really a payload. The bound is a resource limit and stays a dumb one.
const MetadataKeyDetectionLicenses = "bomly.detection.licenses"
MetadataKeyDetectionLicenses is the Dependency.Metadata key under which detectors that discover license facts at detection time (e.g. SBOM-backed detectors) stash []PackageLicense for consolidation to lift into the package registry.
Deprecated: use SetDetectionLicenses and DetectionLicenses, which write and read the typed field. The stash predates that field and is still read on ingest so a payload written by an older producer is not dropped, but nothing should write it.
The stash is why this deprecation exists rather than a rename. A value here is invisible to every gate -- not normalized, not validated, not merged by a declared rule, not projected to either document format -- so a license that lived only in this key was dropped by any consumer that had not learned to look for it. That is the failure the typed field removes, and keeping both spellings writable would leave one of them able to reintroduce it.
const MetadataKeyNPM = "npm"
MetadataKeyNPM is the Metadata map key for *NPMPackageMetadata.
const (
ReachabilityValueReachable = "reachable"
)
ReachabilityValueReachable constraint values currently supported.
const ReservedMetadataPrefix = "bomly."
ReservedMetadataPrefix is the key prefix reserved for Bomly's own use. Component authors namespace their keys by their own component name instead.
const (
SourceChangeValue = "source-change"
)
SourceChangeValue is the supported dependency source-change constraint.
Variables ¶
var ( ErrNilNode = errors.New("graph node is nil") ErrEmptyNodeID = errors.New("graph node id is empty") ErrNodeAlreadyExist = errors.New("graph node already exists") ErrNodeNotFound = errors.New("graph node not found") ErrSelfDependency = errors.New("self dependency is not allowed") ErrCycleDetected = errors.New("dependency creates a cycle") )
var ErrPayloadTooLarge = errors.New("payload exceeds the decode bound")
ErrPayloadTooLarge is returned, wrapped with what was too large, by the graph and registry decoders when a payload exceeds a decode bound.
Functions ¶
func BuildPackageURL ¶
BuildPackageURL builds and normalizes a package URL from its parts.
func BuildPackageURLFor ¶
func BuildPackageURLFor(ecosystem Ecosystem, manager PackageManager, namespace, name, version string) string
BuildPackageURLFor builds a package URL for an ecosystem and its package manager, deciding the package-url type itself.
Prefer this over BuildPackageURL wherever both tokens are known, which is every detector. The type is not a parameter here, so a caller cannot pick one: the mapping is purlkit's (ADR-0038) and stays there.
That matters for a reason a code-review rule could not reach. The type depends on BOTH tokens, and passing one is silently wrong in at least one live case: the swift ecosystem covers SwiftPM and CocoaPods, purlkit has no "swift" case because swift is itself a purl type, and so the package manager is what separates pkg:swift from pkg:cocoapods. A caller handing PackageURLTypeForValues only the ecosystem gets "swift" for a CocoaPods package -- wrong ecosystem, no advisory matches, and nothing to see at the call site. Taking both as parameters makes that unrepresentable rather than discouraged. See bomly-dev/bomly-cli#449.
It is additive: BuildPackageURL keeps working for callers that genuinely have only a type string, such as an SBOM ingest reading one off a document.
func CanonicalPackageURLFromParts ¶
func CanonicalPackageURLFromParts(existingPURL string, ecosystem Ecosystem, packageManager PackageManager, typ PackageType, org, name, version string) string
CanonicalPackageURLFromParts returns the canonical package URL derived from raw identity fields. existingPURL takes precedence when it canonicalizes.
func CanonicalRepoPath ¶
CanonicalRepoPath is the constructor-enforced gate for every path that participates in node identity: the canonical repository-relative, slash-separated form. Backslashes normalize to slashes and the path is cleaned; an empty result, an absolute path, a drive-letter path, a parent escape, or a path carrying '#' or control characters is rejected — the module-ID grammar joins a path and a name with '#', and a raw checkout path would make identities vary across machines.
func CanonicalizePackageURL ¶
CanonicalizePackageURL normalizes a package URL string when possible. It delegates to purlkit, the single home for package-URL behavior.
func ContainsControlChar ¶
ContainsControlChar reports whether value carries a control character. It is the gate every single-line free-text field shares -- contact names, document fields, license sources, and the component descriptor names the plugin package validates -- so a value that would corrupt a line-oriented document, or be acted on by a terminal that prints it, is refused the same way at every entry point.
"Control character" is the standard library's definition (unicode.IsControl, the Unicode Cc category): C0, DEL, and the C1 range U+0080-U+009F. C1 is not hypothetical here -- U+009B is the single-character form of the control sequence introducer. Format characters (Cf) are a different category and are not refused. Invalid UTF-8 decodes to U+FFFD, which is not a control, so callers that need valid UTF-8 check it themselves.
func CopyEdgesInto ¶
CopyEdgesInto copies every edge of src into dst, keeping each edge's kind and mapping node IDs through rename. A nil rename copies IDs unchanged; a rename that returns "" drops the edge, which is how a filtered graph omits edges to nodes it did not keep.
This is the one primitive for rebuilding a graph's edges. Every site that used to walk edges and call AddEdge -- the container merge, the JSON decoder, the scope filter -- is a place a new edge field would be dropped silently, and there were four of them. Routing them all through here means the next field added to an edge is carried by all four at once.
An edge that becomes a self-edge after renaming is skipped, not an error: folding two nodes into one legitimately collapses the edge between them.
func CycloneDXScope ¶
CycloneDXScope projects a scope set onto CycloneDX's scalar component scope. It returns "" when the set says nothing, which a caller writes as no scope at all rather than as a guess.
The rule is that a package reachable at runtime is required, and a package reachable only from development roots is excluded -- CycloneDX's word for a component that is present in the source tree but not in what ships. Runtime wins over development in a mixed set for the same reason MergeScope prefers it: a package reachable at runtime ships, whatever else is also true of it.
"optional" is never produced. In CycloneDX it asserts that a component is not installed and cannot be called by any means -- a claim no Bomly detector makes, because a detector reports what a manifest or lockfile resolved, not what is absent from the system that runs it. Writing it would put an assertion in a document that nothing established.
func CycloneDXScopeForExport ¶
CycloneDXScopeForExport returns the scalar scope a CycloneDX export writes for a component: the source document's own word when Bomly's scope set still means what that word meant, and Bomly's projection of the set otherwise.
ADR-0037 asks that an ingested scope scalar be re-emitted verbatim unless Bomly's own scope set changed, so "optional" and "excluded" never collapse across a round trip that asserted neither. "Still means the same" is decided by the same rule that read the word in: the set ScopesFromCycloneDX derives from it must equal the set the node carries now. A node ingested as "optional" carries {development} and re-exports as "optional"; once propagation adds runtime to it, the set says something the word did not, and the projection ("required") is written instead. A source word outside the CycloneDX vocabulary -- another format's, or nothing -- never reaches a CycloneDX document; the projection does.
The result is always "" or one of cyclonedx-go's three scope spellings, in the library's case, whatever case the source wrote.
func EncodeScopeSet ¶
EncodeScopeSet renders a scope set as a carrier value: the canonical scope tokens, sorted and comma-separated. It returns "" when there is nothing to carry, which a caller writes as no property at all.
Sorted because a document is built from this, and two runs that found the same scopes in a different order must produce the same bytes.
func FilterGraphByScopeWithReport ¶
func FilterGraphByScopeWithReport(src *Graph, scope Scope) (*Graph, ScopeFilterReport, error)
FilterGraphByScopeWithReport is FilterGraphByScope, and also says which dependencies a runtime view kept because they asserted no scope.
Example ¶
A scope filter selects on assertions: a node that asserted no scope is kept by a runtime view, and the report says how many were kept that way.
package main
import (
"fmt"
"github.com/bomly-dev/bomly-sdk/model"
)
func mustNode(purl string) *model.DependencyNode {
node, err := model.NewDependencyNodeFromPURL(purl)
if err != nil {
panic(err)
}
return node
}
func main() {
g := model.New()
runtime := mustNode("pkg:npm/react@18.2.0")
runtime.Scopes = []model.Scope{model.ScopeRuntime}
dev := mustNode("pkg:npm/jest@29.0.0")
dev.Scopes = []model.Scope{model.ScopeDevelopment}
unscoped := mustNode("pkg:npm/lodash@4.17.21")
for _, node := range []*model.DependencyNode{runtime, dev, unscoped} {
_ = g.AddNode(node)
}
filtered, report, err := model.FilterGraphByScopeWithReport(g, model.ScopeRuntime)
if err != nil {
panic(err)
}
for _, dep := range filtered.DependencyNodes() {
fmt.Println(dep.NodeID())
}
fmt.Println("kept on absence:", len(report.Unasserted))
}
Output: pkg:npm/lodash@4.17.21 pkg:npm/react@18.2.0 kept on absence: 1
func FindingPolicyStatusRank ¶
func FindingPolicyStatusRank(status FindingPolicyStatus) (int, bool)
FindingPolicyStatusRank returns the enforcement rank for a finding policy status. An omitted status retains the historical fail behavior. The boolean is false for unknown values.
func IsNilNode ¶
IsNilNode reports whether a node value carries no node, a typed nil included.
A typed nil is not an untyped one: comparing the interface against nil is false for a (*DependencyNode)(nil), and the next method call dereferences it. Every helper that accepts a GraphNode from a caller's slice needs this, so it is exported rather than repeated.
func IsProjectOwned ¶
IsProjectOwned reports whether a node stands for the scanned project's own code -- its root package, a workspace member, a reactor module -- rather than a package it consumes.
It reads the node kind. ADR-0041 removed the FirstParty flag because ownership is what the kind means: the project's own artifacts are module nodes, and a dependency node is a consumed package by construction. The application package type is not sufficient on its own -- an application-typed *import* is a consumed package, and treating it as owned is what kept such packages out of diffing and matching.
func IsReservedMetadataKey ¶
IsReservedMetadataKey reports whether a key is in Bomly's reserved namespace. The comparison is case-insensitive, since a key differing only in case is a collision a reader would not see.
func MergeFillGap ¶
func MergeFillGap[T comparable](current, next T, publishable func(T) bool) T
MergeFillGap returns the current value when it is stated, and the replacement only when there is a gap to fill.
The gate matters as much as the rule. The destination is checked for publishability before the gap is measured, so an unpublishable non-empty value does not count as "stated": leaving it in place would block a valid replacement and then be dropped at encode, losing both. That defect was found in the M1 review and is the reason this takes a validity test rather than comparing against the zero value.
func MergeGraph ¶
MergeGraph adds all nodes and relationships from src into dst.
func MergeStrongest ¶
func MergeStrongest[T comparable](current, next T, rank func(T) int) T
MergeStrongest returns whichever value ranks higher, treating an unranked value as absent so a stated value always beats an unstated one.
rank must be a total order on the vocabulary. Ties keep the current value, which makes the result independent of the order the two sides arrived in -- a property two graphs merged in either direction depend on.
func MergeUnion ¶
MergeUnion appends the members of next that are not already in current, keyed by key, and returns the result sorted by that key.
It never returns early. A merge that returns when next is empty leaves the destination exactly as it was -- including any member that would not survive its own gate -- so an ungated claim stays visible in process and disappears only at encode. Running the whole pass unconditionally is what makes the gate total.
Sorted because documents are built from these: two runs that found the same members in a different order must produce the same bytes.
func NodeDisplayName ¶
NodeDisplayName returns the name a node shows under: the ecosystem-native display name for a node with coordinates, and the path for a manifest, which is the only name a manifest has.
func NodePURL ¶
NodePURL returns the package URL a node publishes, or "" when it has none.
The three kinds answer differently, which is why this lives here: a dependency node's ID is its canonical package URL; a module's ID is the structural "module:<path>#..." grammar and its package URL is a separate field, derived only when its coordinates genuinely allow one; a manifest is a file and has none. Written per consumer, the switch drifts -- the CLI's interactive view rendered a module's NodeID under a column labelled "PURL", handing the viewer a string no consumer can parse as a package URL, while its SBOM and JSON paths had the projection right.
A module whose coordinates could not mint a package URL returns "" rather than a fallback. NewModuleNode already declined to fabricate one for it (a module is the project's own record, and the generic type is a registry lookup fabrication), and this reports what the node publishes, not what it might have.
func NodeVersion ¶
NodeVersion returns the version a node carries, or "" when it carries none.
func NormalizeCoordinates ¶
func NormalizeCoordinates(pkg *Coordinates) []string
NormalizeCoordinates applies ecosystem-aware identity normalization to the coordinate fields in place and returns which rules applied. It is the pre-minting step of node construction — normalize, then mint the canonical package URL, then construct — and records nothing itself: the constructors store the provenance breadcrumbs on the node.
func NormalizeCopyright ¶ added in v0.14.0
NormalizeCopyright is the gate for a component's copyright text. The value is free text from untrusted SBOM documents and registry records, written into both SBOM formats and rendered into terminals -- the same exposure as a description, so it clears the same rule: trimmed, bounded, and stripped of control characters other than line breaks and tabs.
Line breaks survive because a copyright notice is legitimately multi-line: a package with several holders lists one per line, and SPDX carries the field as <text> for exactly that reason. The single-line rule (ContainsControlChar) would refuse such a notice outright.
Over-long input yields "" rather than a truncation: half a copyright notice attributed to a package drops holders it names, which is a false assertion where no notice is merely a missing one.
func NormalizeDescription ¶
NormalizeDescription is the gate for a component description. Descriptions arrive from untrusted registry records and SBOM documents and are rendered into terminals and written into published documents, so the value is trimmed, bounded, and stripped of control characters that would corrupt the output. Line breaks and tabs survive: both formats carry multi-line descriptions, and removing them would damage a legitimate value.
Over-long input yields "" rather than a truncation, because half a description attributed to a package is a false assertion where no description is merely a missing one.
The result is a fixed point within the bound; normalizePublishedText says why that has to be checked on the output.
func NormalizeDocumentFormat ¶ added in v0.14.0
NormalizeDocumentFormat holds a document format token to its gate: trimmed, and refused when it is empty, longer than a vocabulary token, not valid UTF-8, or carries a control or whitespace character. The vocabulary itself is package sbom's (its Target values); this package carries the token without interpreting it, which is why the gate is about shape alone.
func NormalizeHomepage ¶
NormalizeHomepage is the gate for a component homepage: URLFormReference, which keeps a bare host and a query -- both normal for a project page -- while rejecting credentials, local paths, and non-http schemes. It returns "" when the value cannot be published.
func NormalizeOriginURL ¶
NormalizeOriginURL is the origin-specific spelling of NormalizeURL, kept as the name detectors and plugins already call. The repository argument selects URLFormRepository; false selects URLFormArtifact.
func NormalizeSourceScope ¶
NormalizeSourceScope is the gate for DependencyNode.SourceScope: the scope word a source document used, kept in that document's vocabulary. A scope scalar is a single token in every format that has one, so the value is trimmed and refused when it is empty, longer than a vocabulary token, not valid UTF-8, or carries a control or whitespace character -- any of which means it was not a scope a document stated. It is not lowercased: what is preserved is the claim as written, and the export helper below applies the target format's spelling when it re-emits it.
func NormalizeURL ¶
NormalizeURL is the single rule every published URL satisfies. Apply it when recording a URL and again when reading one back, so a value that arrives from a plugin or a hand-built graph is held to the same standard as one from a built-in component.
A value passes only when it is an absolute http or https URL with a host and no embedded credentials; the result is re-serialized from the parse rather than returned as given. Everything else -- local paths, file://, git@host:org/repo, ssh://, git+ssh://, "git+" prefixes, and URLs carrying userinfo -- is rejected, so filesystem layout and credentials cannot reach a published document. The form argument selects the remaining rules; see URLForm.
func PackageURLBase ¶
PackageURLBase strips version, qualifiers, and subpath from a package URL. It delegates to purlkit.Base, which works on the parsed structure — the previous string surgery mishandled subpath-carrying and version-less package URLs.
func PackageURLTypeForValues ¶
PackageURLTypeForValues maps ecosystem/build-system values to a package-url type.
The explicit switch below is the authority: it is consulted for every value before the loose fallback runs, so the most specific mapping wins regardless of the order the caller passes ecosystem / package manager / package type in. The fallback then returns the first non-empty value verbatim, which is only correct where the Bomly identifier happens to be the purl type as well (npm, maven, apk, rpm, ...). Any ecosystem whose purl type differs from its Bomly name needs an explicit case here — without one we emit a type that is not in the purl spec, and consumers keyed on the type (OSV, SBOM ingest) silently fail to match. See issue #317.
Ecosystems that span more than one registry are the exception: erlang covers both Hex (rebar) and OTP (*.app), so it is mapped at the package-manager level only. A bare erlang value with no manager to disambiguate keeps the non-spec pkg:erlang rather than guessing a registry the package may not be published to.
func ReservedMetadataKeys ¶
ReservedMetadataKeys returns the reserved keys present in a metadata map, sorted. A component runtime uses it to warn an external plugin that is writing into Bomly's namespace, rather than letting the collision be found later as data read as the wrong thing.
func ScopeSetMatches ¶
ScopeSetMatches reports whether a scope set belongs in a view narrowed to want. It is where the absence rule lives, so that the graph filter and the usage filter cannot drift apart on it.
A runtime view keeps a set that names runtime, and also one that names nothing it can act on -- no scope at all, or only scopes this build cannot read, which is what a newer Bomly's token looks like here. Neither states that the dependency is outside what ships. Every other view matches by membership only, because a package that might ship must not appear in the list a user reads as the one they can deprioritize.
The runtime arm is written as membership rather than as a test on the effective scope, and the two are not interchangeable: MergeScope folds any two non-runtime scopes to development, so a set holding two tokens this build cannot read -- neither of them development -- has a PrimaryScope of ScopeDevelopment, and an effective-scope test would drop it from a runtime view. That is this function's own failure mode arriving by another door.
A want of ScopeUnknown is not a filter and matches everything, which is how a caller spells "no scope was requested".
func SetDetectionLicenses ¶
func SetDetectionLicenses(dep *DependencyNode, licenses []PackageLicense)
SetDetectionLicenses records detection-time license facts on dep, so consolidation can lift them into the package registry. No-op when dep is nil or licenses is empty.
It now writes the typed DependencyNode.Licenses field rather than the metadata stash, which is the migration ADR-0037 calls for: the path for a metadata key is a typed field. Callers of this helper need no change, and payloads written by an older producer are still read — see DetectionLicenses.
func SeverityMeets ¶
func SeverityMeets(candidate SeverityLevel, threshold string) bool
SeverityMeets reports whether candidate's severity is at or above threshold. Threshold "any" matches every candidate, including unknown.
func SeverityRank ¶
func SeverityRank(severity SeverityLevel) int
SeverityRank returns a comparable rank for a severity string. Unknown / empty values rank below "low". The GitHub-aligned levels share the ladder with the CVSS bands: error ≡ high, warning ≡ medium, note ≡ low.
func SortDependencyDetailTransitions ¶
func SortDependencyDetailTransitions(transitions []DependencyDetailTransition)
SortDependencyDetailTransitions orders detail changes deterministically.
Types ¶
type Affected ¶
type Affected struct {
Ranges []VersionRange `json:"ranges,omitempty"`
Versions []string `json:"versions,omitempty"`
EcosystemSpecific map[string]any `json:"ecosystem_specific,omitempty"`
DatabaseSpecific map[string]any `json:"database_specific,omitempty"`
}
Affected describes one OSV affected entry: the version ranges and explicit versions impacted by the vulnerability.
type AffectedSymbol ¶
type AffectedSymbol struct {
Symbol string `json:"symbol,omitempty"`
Kind SymbolKind `json:"kind,omitempty"`
Package string `json:"package,omitempty"`
Module string `json:"module,omitempty"`
Definition *SourcePosition `json:"definition,omitempty"`
}
AffectedSymbol identifies one vulnerable symbol within a package. Matchers that have symbol-level data populate this on a Vulnerability; reachability analyzers use it to know which symbols to look for in app code.
func (AffectedSymbol) Clone ¶
func (s AffectedSymbol) Clone() AffectedSymbol
Clone returns a deep copy of the affected symbol.
type Assertions ¶ added in v0.14.0
type Assertions struct {
// Description is the package's own summary of itself. SPDX
// PackageDescription / CycloneDX component description.
Description string `json:"description,omitempty"`
// Homepage is the package's project page. SPDX PackageHomePage /
// CycloneDX external reference of type website.
Homepage string `json:"homepage,omitempty"`
// Supplier is who distributed the package. SPDX PackageSupplier /
// CycloneDX supplier.
Supplier *Contact `json:"supplier,omitempty"`
// Originator is who originally authored the package, which is often not
// the supplier. SPDX PackageOriginator / CycloneDX author or publisher.
Originator *Contact `json:"originator,omitempty"`
// ExternalReferences are the references a source attached to the
// package: advisories, repositories, package-manager coordinates. SPDX
// externalRefs / CycloneDX externalReferences.
ExternalReferences []ExternalReference `json:"external_references,omitempty"`
// CPEs are the CPE identifiers a source asserted for the package.
CPEs []string `json:"cpes,omitempty"`
// Digests are the integrity claims a source made over the package's
// artifact, source or metadata.
Digests []Digest `json:"digests,omitempty"`
// Licenses are the license claims a source made, each typed declared or
// concluded.
Licenses []PackageLicense `json:"licenses,omitempty"`
// Copyright is the copyright text a source stated. Gate:
// NormalizeCopyright -- trimmed and bounded, control characters other
// than line breaks and tabs dropped, an over-long notice cleared rather
// than truncated.
Copyright string `json:"copyright,omitempty"`
}
Assertions are the component-level claims a source makes about one package: what a document, a lockfile or a registry said about it, as opposed to what it is (Coordinates) or where it was found (locations). They are one type because they are one set of claims with one set of gates and merge rules, carried by both DependencyNode -- where a detecting or ingesting source asserts them, before matching has produced a package -- and Package, where matching enriches them. Before this type existed the two carried the same eleven fields separately and each re-stated the gates (ADR-0037).
Embedding keeps both wire shapes flat: the JSON keys are the same ones each struct wrote before, promoted through the embedded field.
Gates, applied on both wire directions and again when a node seeds a registry package: NormalizeDescription (trimmed, bounded, control characters dropped); NormalizeHomepage (URLFormReference, so a bare host and a query are fine while credentials and local paths are cleared); Contact.Normalized for both contacts, which yields nil for an unpublishable party and never retains an email address; ExternalReference.Normalized; Digest.Normalized; PackageLicense.Normalized; and for CPEs a dumb one -- trimmed, non-empty, no control character -- because no pinned dependency owns the CPE grammar and a transcription of it here would be a vocabulary Bomly does not own.
Merge classes: Description, Homepage, Supplier, Originator and Copyright are scalars, fill-gaps -- both witnesses are gated before the gap is measured, so a value that could not be published never blocks one that can. ExternalReferences, CPEs, Digests and Licenses are sets, unioned: every witness's claims survive, because two sources can each know something the other does not, and a declaration and a conclusion are two claims about one package rather than one overriding the other.
func (Assertions) Clone ¶ added in v0.14.0
func (a Assertions) Clone() Assertions
Clone returns a deep copy.
func (*Assertions) MergeFrom ¶ added in v0.14.0
func (a *Assertions) MergeFrom(src Assertions)
MergeFrom folds src into a under the declared merge classes: scalars keep a's value and take src's only to fill a gap, sets union. Both sides are gated first -- a holder built in process never passed a codec, so a may hold an unpublishable value that is non-empty, would block a valid incoming one, and would then be dropped at encode.
func (Assertions) Normalized ¶ added in v0.14.0
func (a Assertions) Normalized() Assertions
Normalized returns the assertions with every field held to its gate. Values that cannot be published are cleared rather than corrected, following the codecs on DependencyOrigin and Contact; the sets are deduplicated and sorted so the result is byte-stable.
type CVSSScore ¶
type CVSSScore struct {
Vector string `json:"vector,omitempty"`
Score float64 `json:"score,omitempty"`
Version SeverityType `json:"version,omitempty"`
Source string `json:"source,omitempty"`
}
CVSSScore captures one CVSS vector and score.
type CWE ¶
type CWE struct {
CVE string `json:"cve,omitempty"`
ID string `json:"id,omitempty"`
Source string `json:"source,omitempty"`
Type string `json:"type,omitempty"`
}
CWE identifies a Common Weakness Enumeration entry for a vulnerability.
type CallFrame ¶
type CallFrame struct {
Function string `json:"function,omitempty"`
Package string `json:"package,omitempty"`
Receiver string `json:"receiver,omitempty"`
Position SourcePosition `json:"position,omitempty"`
}
CallFrame represents one stack frame in a reachability call path.
type CallPath ¶
type CallPath struct {
Sink AffectedSymbol `json:"sink"`
Frames []CallFrame `json:"frames,omitempty"`
}
CallPath is one entry-point → sink path. Frames[0] is the entry point.
type Contact ¶
type Contact struct {
// Kind says whether the party is an organization or a person, or that
// the document explicitly declined to say. Parsed by ParseContactKind;
// an unrecognized kind is dropped to unknown, which has no valid SPDX
// rendering and so omits the field rather than emitting a bad one.
Kind ContactKind `json:"kind,omitempty"`
// Name is the party's name as the source stated it, minus any email
// address. Bounded, and rejected outright if it carries a control
// character, which would corrupt SPDX's line-oriented tag form.
Name string `json:"name,omitempty"`
// URL is the party's own URL, when the source carried one. CycloneDX's
// organizational entity has a url list; SPDX has no slot for it. Held to
// URLFormReference and additionally refused when it carries an email
// address, so the no-email rule above cannot be sidestepped through the
// query or fragment. An unpublishable URL is cleared on its own; unlike
// the name, it does not take the contact with it.
URL string `json:"url,omitempty"`
}
Contact names a party a document makes a claim about: who supplied a package (SPDX PackageSupplier, CycloneDX supplier) or who originally authored it (SPDX PackageOriginator, CycloneDX author/publisher).
No email address ¶
A contact deliberately carries no email address, though both formats have a slot for one. ADR-0037 defers supplier-contact privacy to its own review, and an email is personal data that would flow from an ingested document into Bomly's JSON output, its logs, and every re-export. Storing it now and deciding later is not neutral -- the exposure happens at storage, not at emission -- so the field does not exist yet.
The consequence is stated rather than hidden: an SPDX supplier written as "Organization: Acme Inc (info@acme.com)" round-trips as "Organization: Acme Inc". The name survives, the address does not. When the privacy review lands, an email field is an additive change here. # Gate and merge class
Every field is gated by Contact.Normalized, applied on both wire directions and again wherever a contact is copied onto another record. The gate acts on the contact as a whole, not field by field: a name that cannot be published takes the contact with it and yields nil, rather than leaving a party with no name attached to a package. NOASSERTION is the one kind that stands without a name, because withholding is itself the claim.
A contact is a fill-gaps scalar on its holder: the first publishable supplier wins, and a later witness contributes one only where none was recorded. Both witnesses are gated before the gap is measured, so an unpublishable contact never blocks a valid one.
func ParseSPDXContact ¶
ParseSPDXContact reads SPDX's PackageSupplier/PackageOriginator form. It accepts "Organization: <name>", "Person: <name>", and "NOASSERTION", and strips the optional "(<email>)" suffix the format allows -- see the type's documentation for why the address is not retained. It returns false when the value carries no publishable claim.
func (Contact) MarshalJSON ¶
MarshalJSON applies the same rule on the way out.
func (Contact) Normalized ¶
Normalized returns the contact with its claim re-checked, or false when it says nothing publishable. It is the gate for a contact that arrived from a plugin, an ingested document, or a hand-built value.
func (Contact) SPDXString ¶
SPDXString renders the contact in SPDX's PackageSupplier/PackageOriginator form, or "" when the contact has no SPDX projection. SPDX requires the kind prefix, so a contact of unknown kind has no valid rendering -- "" means omit the field rather than emit something that will not validate.
func (*Contact) UnmarshalJSON ¶
UnmarshalJSON applies the contact rule as a value arrives, so a party that would be rejected on read cannot be stored, forwarded, or written back out. A contact that says nothing publishable decodes to the zero value, following DependencyOrigin.
type ContactKind ¶
type ContactKind string
ContactKind says what sort of party a Contact names. SPDX writes the kind inline ("Organization: Acme Inc"), and CycloneDX implies it by which field carries the value, so the SDK stores it explicitly and each codec projects it.
const ( // ContactKindUnknown means the source named a party without saying // whether it is a person or an organization. ContactKindUnknown ContactKind = "" // ContactKindOrganization names a company, foundation, or team. ContactKindOrganization ContactKind = "organization" // ContactKindPerson names an individual. ContactKindPerson ContactKind = "person" // ContactKindNoAssertion is SPDX's explicit "the document declines to // say". It is not the same as an absent contact: one is a statement that // the information was withheld, the other is silence, and SPDX // round-trips the difference. ContactKindNoAssertion ContactKind = "noassertion" )
func ParseContactKind ¶
func ParseContactKind(value string) (ContactKind, error)
ParseContactKind normalizes a contact kind. An empty value is unknown, which is legal; anything else unrecognized is an error.
type Coordinates ¶
type Coordinates struct {
PURL string `json:"purl,omitempty"`
Ecosystem Ecosystem `json:"ecosystem,omitempty"`
PackageManager PackageManager `json:"package_manager,omitempty"`
Type PackageType `json:"type,omitempty"`
Org string `json:"org,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Language Language `json:"language,omitempty"`
}
Coordinates is the shared identity view embedded by Dependency and Package. It intentionally excludes graph-only fields (scopes, locations, package refs) and enrichment-only fields (licenses, vulnerabilities, scorecard) so detection-time graph nodes and matching-stage package records remain distinct domain models.
func NodeCoordinates ¶
func NodeCoordinates(node GraphNode) (Coordinates, bool)
NodeCoordinates returns the package coordinates a node carries, and reports whether it carries any.
A manifest node does not: a file is not a package. A typed nil does not either, which is why the check is here rather than at each call site -- comparing a GraphNode against nil is false for a (*DependencyNode)(nil), and the next field read panics.
func (Coordinates) CanonicalPURL ¶
func (i Coordinates) CanonicalPURL() string
CanonicalPURL returns the canonical package URL for the identity.
func (Coordinates) DisplayName ¶
func (i Coordinates) DisplayName() string
DisplayName returns the package name in its ecosystem-native form: "@org/name" for npm-family packages, "org/name" for path-style ecosystems (Go, Composer), and "org:name" otherwise. Unlike QualifiedName it is a presentation label only and must never be used as an identity key.
func (Coordinates) EcosystemName ¶
func (i Coordinates) EcosystemName() string
EcosystemName returns the package name in the form its ecosystem uses as an identity: "@org/name" for npm, "org:name" for Maven-family coordinates, and "org/name" for the path-style namespaced ecosystems (Go, Composer, Swift, GitHub Actions). This is the name external advisory databases, SBOM documents, and scanners such as Grype and Syft key on, so anything building a lookup for a package must derive it from here rather than from the bare Name — Name alone drops the npm scope and matches the unscoped package's advisories.
Joining is opt-in per ecosystem, and everything else keeps the bare Name, because Org is not always part of the package name. For OS packages Org is the distro that shipped the package (`Org: "alpine"` from `pkg:apk/alpine/libcrypto3`), and Grype's distro-namespace matchers query `libcrypto3`; joining would miss every OS advisory. The same holds for any other ecosystem whose PURL namespace names a vendor or channel rather than part of the package's own identity.
func (Coordinates) GenericPURL ¶
func (i Coordinates) GenericPURL() string
GenericPURL returns a pkg:generic package URL for the identity, for the case where the ecosystem's own type profile rejects the coordinates.
It is deliberately separate from CanonicalPURL: that answers "what is this package's canonical identity in its own ecosystem", and answering it with a generic URL would make every caller unable to tell the two apart. Node construction is the only place that reaches for this, and it records a warning when it does.
A qualifier names the type that could not express the package. Two ecosystems whose profiles both reject otherwise identical coordinates would otherwise mint the same identity -- a bare Swift "internal-tools@2.0.0" and a bare Go one both becoming pkg:generic/internal-tools@2.0.0 -- and folding two distinct packages into one node is a worse outcome than the loose type this fallback already accepts. A degraded identity still has to be an identity.
A qualifier rather than the namespace, because coordinates are projected from the identity verbatim once it is minted: a discriminator in the namespace comes back as Coordinates.Org, so a bare Swift package would read as organization "swift" and display as "swift:internal-tools" -- an organization no manifest declared. A qualifier is part of the identity, so it keeps the two records distinct, and it is not projected, so the coordinates still say what the detector found. It also rides the wire, which is what lets the warning below be derived after a decode.
func (Coordinates) QualifiedName ¶
func (i Coordinates) QualifiedName() string
QualifiedName returns the package name prefixed with its organization when present.
type DependencyDetailField ¶
type DependencyDetailField string
DependencyDetailField identifies one dependency property that changed independently of package identity or version.
const ( // DependencyDetailRelationship is a direct, transitive, or unknown // relationship change. DependencyDetailRelationship DependencyDetailField = "relationship" // DependencyDetailSource is a registry, workspace, file, Git, URL, or // project source change. DependencyDetailSource DependencyDetailField = "source" // DependencyDetailRegistryEligibility indicates that external registry // matching eligibility changed. DependencyDetailRegistryEligibility DependencyDetailField = "registry_eligibility" )
type DependencyDetailReviewReason ¶
type DependencyDetailReviewReason string
DependencyDetailReviewReason explains why a dependency detail change should receive extra review.
const ( // DependencyDetailReviewSourceGit indicates that the dependency now comes // from a Git repository. DependencyDetailReviewSourceGit DependencyDetailReviewReason = "source-changed-to-git" // DependencyDetailReviewSourceURL indicates that the dependency now comes // from an arbitrary URL. DependencyDetailReviewSourceURL DependencyDetailReviewReason = "source-changed-to-url" )
type DependencyDetailTransition ¶
type DependencyDetailTransition struct {
Before *DependencyNode `json:"before,omitempty"`
After *DependencyNode `json:"after,omitempty"`
ChangedFields []DependencyDetailField `json:"changedFields,omitempty"`
BeforeRelationship DependencyRelationship `json:"beforeRelationship,omitempty"`
AfterRelationship DependencyRelationship `json:"afterRelationship,omitempty"`
BeforeRegistryEligible bool `json:"beforeRegistryEligible"`
AfterRegistryEligible bool `json:"afterRegistryEligible"`
}
DependencyDetailTransition captures same-identity dependency detail changes. Version changes remain represented separately by VersionChange.
func CloneDependencyDetailTransitions ¶
func CloneDependencyDetailTransitions(transitions []DependencyDetailTransition) []DependencyDetailTransition
CloneDependencyDetailTransitions returns a deep copy of dependency detail transitions suitable for crossing component and plugin boundaries.
func CompareDependencyDetails ¶
func CompareDependencyDetails(baseGraph, headGraph *Graph, before, after *DependencyNode) (DependencyDetailTransition, bool)
CompareDependencyDetails returns a transition when relationship, source, or registry-matching eligibility differs between two dependency records. It is exported so trusted fuzzy identity reconciliation can use the same canonical classifier as Compare.
func (DependencyDetailTransition) NeedsReview ¶
func (t DependencyDetailTransition) NeedsReview() bool
NeedsReview reports whether this detail change has at least one review reason.
func (DependencyDetailTransition) ReviewReasons ¶
func (t DependencyDetailTransition) ReviewReasons() []DependencyDetailReviewReason
ReviewReasons returns the reasons this detail change needs extra review. The result is deterministic and does not treat missing evidence, coverage gains, or relationship-only changes as review signals.
type DependencyEdge ¶
type DependencyEdge struct {
FromID string `json:"fromId"`
ToID string `json:"toId"`
Kind EdgeKind `json:"kind,omitempty"`
}
DependencyEdge captures one directed relationship between node IDs.
Kind is additive and omitted when unknown, so a payload written before the field keeps its exact bytes. On decode an absent kind is derived from the nodes the edge joins, which is why adding the field did not need a wire break: the structure already carried the answer.
type DependencyNode ¶
type DependencyNode struct {
Coordinates
// Assertions are the component-level claims the detecting or ingesting
// source made about this dependency: description, homepage, supplier,
// originator, external references, CPEs, digests, licenses, copyright.
// They live on the node as well as on Package because an ingested
// document asserts them per component, before matching has produced a
// registry package to hold them (ADR-0037); consolidation lifts them
// into the registry package. See Assertions for the gates, applied on
// both wire directions and again when a node seeds a package, and the
// merge classes.
Assertions
Relationship DependencyRelationship
Source DependencySource
Scopes []Scope
// SourceScope is the scope the source document asserted about this
// component, in that document's own vocabulary -- "optional", for a
// CycloneDX component -- when a document asserted one. It is a preserved
// claim, never an input to filtering: Scopes is what filters read, and
// ScopesFromCycloneDX derives it.
//
// The field exists because a projection cannot round-trip the word on its
// own. A CycloneDX "optional" ingests as {development}, and projecting
// that set alone writes "excluded" back out -- collapsing two distinct
// source words the document had kept apart (ADR-0037). Holding the word
// itself is what makes "optional" in, "optional" out possible;
// CycloneDXScopeForExport is the one place that decides when the word is
// re-emitted and when the projection is.
//
// Gate: NormalizeSourceScope, on both wire directions and when a
// prototype is copied -- a single token, bounded, no control or
// whitespace characters. Merge class: scalar, fill-gaps. Two documents
// disagreeing about a component's scope is not resolved by picking one.
SourceScope string
Locations []PackageLocation
FoundBy string
// ResolvedURL is the manifest's resolution field verbatim — it may be a
// pseudo-URL, a registry or index root, or a local path, and is never
// published. It is raw evidence; Origins carry the validated assertions.
ResolvedURL string
// Origins is where this dependency was resolved from: metadata, never
// identity (ADR-0041). Union-merged and deduplicated by normalized
// value; the ADR-0033 publication gates are the only door in. A list
// with more than one element is an observable fact — the shape of a
// dependency-confusion signal — not a reason to split the node.
Origins []DependencyOrigin
Metadata map[string]any
// Matched is true when the referenced package was enriched by a matcher.
Matched bool
// PackageRef is the PURL of this dependency's matching artifact. It is
// derived — seeding sets it to NodeID(), which is the same canonical
// PURL — and retained for wire compatibility with older readers.
PackageRef string
// contains filtered or unexported fields
}
DependencyNode is the union's third-party package record: one resolved dependency, the unit of matching and enrichment (ADR-0041). Its identity — and therefore its published graph ID — is its canonical package URL, minted only by the constructors below; there is no ID override, no occurrence suffix, and no identity outside the PURL. Matching enrichment (licenses, vulnerabilities, scorecard) lives on the referenced Package, not here.
func AsDependencyNode ¶
func AsDependencyNode(node GraphNode) (*DependencyNode, bool)
AsDependencyNode narrows a node to a dependency node, reporting whether it is one. A typed nil is not.
func DependencyNodesOf ¶
func DependencyNodesOf(list []GraphNode) []*DependencyNode
DependencyNodesOf narrows a slice of graph nodes to the dependency nodes among them.
Graph traversal yields the union -- DirectDependencies, Dependents, Roots, Leaves -- and most logic over the result is about consumed packages specifically: scope propagation, relationship marking, enrichment. Narrowing in one named place keeps every site agreeing about what a structural node means there: it is skipped, not defaulted.
func NewDependencyNode ¶
func NewDependencyNode(coords Coordinates) (*DependencyNode, error)
NewDependencyNode constructs a dependency node from coordinates: the fields are normalized (per-ecosystem case, separator, and format rules — the same pass NormalizeCoordinates exposes), the canonical package URL is minted, and the identity is validated against the purl specification. A node that cannot mint a valid package URL is an error, not a silently empty ID; a missing version is a recorded warning, because the specification leaves version optional and first-party-adjacent records legitimately lack one.
func NewDependencyNodeFrom ¶
func NewDependencyNodeFrom(proto DependencyNode) (*DependencyNode, error)
NewDependencyNodeFrom constructs a dependency node from a prototype: the identity is minted from the prototype's coordinates, and every other field it states is copied onto the result.
A node's identity is fixed at construction, so a producer that used to describe a package as one struct literal now has to construct first and assign after. Doing that by hand at each site is how a detector silently stops recording what it detected -- four npm-family lockfile parsers lost ResolvedURL and their integrity digests exactly that way, in one release, each for the same reason, and only a fixture assertion noticed.
The field list lives here because this type owns it: a field added to the model is copied by every producer at once, rather than in as many places as remembered.
func NewDependencyNodeFromPURL ¶
func NewDependencyNodeFromPURL(rawPURL string) (*DependencyNode, error)
NewDependencyNodeFromPURL constructs a dependency node from a raw package URL — the qualifier-capable path. The URL-valued evidence qualifiers (repository_url, download_url, vcs_url) are relocated through the ADR-0033 origin constructors into Origins — a value the gates reject (a signed or tokenized link) is discarded entirely with a recorded warning, never sanitized into something publishable — and every other qualifier stays on the identity. Coordinates are back-filled from the parsed identity.
func (*DependencyNode) AddScope ¶
func (n *DependencyNode) AddScope(scope Scope)
AddScope records a scope on the dependency if not already present.
func (*DependencyNode) AttributedScopes ¶
func (n *DependencyNode) AttributedScopes() []Scope
AttributedScopes is the node's scope set, preferring the union over its locations when the sites carry attribution and falling back to the stored node-level set when they do not.
This is the direction the model is moving: the node-level set is a cache of what the sites say, not an independent claim. Reading through this rather than Scopes directly means a caller keeps working both before and after the producers migrate.
func (*DependencyNode) Clone ¶
func (n *DependencyNode) Clone() *DependencyNode
Clone returns a deep copy of the dependency node.
func (*DependencyNode) CloneNode ¶
func (n *DependencyNode) CloneNode() GraphNode
CloneNode implements GraphNode.
func (*DependencyNode) DisplayName ¶
func (n *DependencyNode) DisplayName() string
DisplayName returns the most human-friendly identifier available, using the ecosystem-native name form (e.g. "@org/name" for npm).
func (*DependencyNode) HasScope ¶
func (n *DependencyNode) HasScope(scope Scope) bool
HasScope reports whether the dependency carries the given scope.
func (*DependencyNode) Kind ¶
func (n *DependencyNode) Kind() NodeKind
Kind returns NodeKindDependency.
func (*DependencyNode) LocationScopes ¶
func (n *DependencyNode) LocationScopes() []Scope
LocationScopes returns the union of the scopes recorded across a node's locations, sorted and deduplicated. It returns nil when no location carries attribution, which is what a producer that has not migrated yet leaves.
func (*DependencyNode) MarshalJSON ¶
func (n *DependencyNode) MarshalJSON() ([]byte, error)
MarshalJSON encodes a dependency node in its flat wire form.
func (*DependencyNode) MatchesScopeFilter ¶
func (n *DependencyNode) MatchesScopeFilter(want Scope) bool
MatchesScopeFilter reports whether the dependency belongs in a graph view narrowed to want.
A runtime view is ScopeSetMatches: the absence rule is the same wherever a scope set is matched. Every other view additionally requires that the set not name runtime, because Scopes is a union across declaration sites: a package reached from a development root and from a runtime root ships, and listing it in a development view would present a shipping package as one to deprioritize. That is the one place this differs from matching a single site's scopes, where naming a scope is the whole question.
The extra condition is spelled out rather than delegated to PrimaryScope, which cannot answer it: MergeScope's fall-through returns ScopeDevelopment for any two non-runtime scopes, so a set of two tokens this build cannot read has an effective scope of development and a comparison against it would put a dependency nobody scoped development into the very view that must be affirmative. Membership is what "affirmative" means here.
func (*DependencyNode) NodeID ¶
func (n *DependencyNode) NodeID() string
NodeID returns the canonical package URL: the node's identity and its published graph ID are the same string.
func (*DependencyNode) NodeLocations ¶
func (n *DependencyNode) NodeLocations() []PackageLocation
NodeLocations returns the dependency's witnessed locations.
func (*DependencyNode) NodeWarnings ¶
func (n *DependencyNode) NodeWarnings() []NodeWarning
NodeWarnings returns the constructor-recorded recoverable conditions.
func (*DependencyNode) PURL ¶
func (n *DependencyNode) PURL() purlkit.PURL
PURL returns a copy of the parsed canonical identity.
func (*DependencyNode) PrimaryScope ¶
func (n *DependencyNode) PrimaryScope() Scope
PrimaryScope returns the merged precedence scope across all recorded scopes.
func (*DependencyNode) QualifiedName ¶
func (n *DependencyNode) QualifiedName() string
QualifiedName returns the name prefixed with its organization when present.
func (*DependencyNode) RegistryMatchEligible ¶
func (d *DependencyNode) RegistryMatchEligible() bool
RegistryMatchEligible reports whether this dependency may be sent to external package matchers. Ownership and structure are the node kind under the union — module and manifest nodes cannot reach this method — so only the source classification decides. Project, workspace, file, Git, and arbitrary URL records are normally excluded. Swift source-control packages remain eligible because their repository URL is the canonical SwiftURL package identity used by vulnerability sources. An omitted source stays eligible for protocol-v1 and legacy detector compatibility. Graph insertion folds eligibility toward eligible: when records of one identity disagree, the eligible witness's source survives.
func (*DependencyNode) SyncScopesFromLocations ¶
func (n *DependencyNode) SyncScopesFromLocations()
SyncScopesFromLocations rewrites the node-level scope set from its locations, so the cache matches what the sites say. It does nothing when no location carries scopes, which keeps it safe to call on a graph whose producers have not migrated -- rather than emptying a set that is the only record there is.
func (*DependencyNode) UnmarshalJSON ¶
func (n *DependencyNode) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a dependency node through the constructor gates. A payload of a different node kind, or one whose identity cannot mint a well-formed package URL, is an error.
type DependencyOrigin ¶
type DependencyOrigin struct {
// ArtifactURL is the exact file the package was downloaded from.
ArtifactURL string `json:"artifact_url,omitempty"`
// Repository is the source repository the package was resolved from.
Repository string `json:"repository,omitempty"`
// Revision is the revision pinned in Repository, when the lockfile
// recorded one. Never set without Repository.
Revision string `json:"revision,omitempty"`
}
DependencyOrigin is where a dependency was resolved from, as asserted by the manifest the detector read. It is distilled at detection time from the manifest's structured source fields -- not derivable later from the raw ResolvedURL, which merges several fields and loses their meaning. The name follows the two standards that record this concept as a structured value: Go modules' Origin (URL, ref, hash) and PEP 610's "Direct URL Origin".
A dependency has one origin: either it was downloaded as an artifact or it was resolved from a repository, never both. An empty origin means the manifest had nothing publishable to say, which is the normal case for a dependency whose lockfile records only a registry or index root. Consumers such as SBOM export should publish nothing rather than guess.
This is detection data. Registry-side enrichment that resolves a source repository from package identity is a different, weaker claim and lives on its own fields (for example PackageScorecard.Repository), never here.
func ArtifactOrigin ¶
func ArtifactOrigin(rawURL string) *DependencyOrigin
ArtifactOrigin records the exact artifact a package was resolved from. Callers pass the lockfile field verbatim. It returns nil when the value is not a publishable location, since a missing origin is correct output and a wrong one is not.
func MergeOrigins ¶
func MergeOrigins(existing, additions []DependencyOrigin) []DependencyOrigin
MergeOrigins unions two origin lists into one, deduplicating by the normalized value and dropping entries that do not survive validation — the publication gates above remain the only door into a stored list. Merge class: union keyed by the normalized origin; order is deterministic — existing entries first, then new additions in arrival order. Two lists asserting the same location in different spellings collapse to one entry because the key is the normalized form, not the input bytes.
func RepositoryOrigin ¶
func RepositoryOrigin(rawURL, revision string) *DependencyOrigin
RepositoryOrigin records the source repository a package was resolved from, plus the revision that was pinned. It returns nil when the URL is not a publishable location; an unusable revision drops only the revision, keeping the repository.
func (*DependencyOrigin) Clone ¶
func (o *DependencyOrigin) Clone() *DependencyOrigin
Clone returns a deep copy.
func (*DependencyOrigin) Empty ¶
func (o *DependencyOrigin) Empty() bool
Empty reports whether o names no publishable location -- including an origin whose values do not survive validation, so a caller that checks Empty can read Normalized without a second nil check.
func (DependencyOrigin) MarshalJSON ¶
func (o DependencyOrigin) MarshalJSON() ([]byte, error)
MarshalJSON applies the same rule on the way out, so a hand-built value that never passed through the constructors cannot leave this process either.
func (*DependencyOrigin) Normalized ¶
func (o *DependencyOrigin) Normalized() *DependencyOrigin
Normalized returns o with every value re-validated, or nil when nothing publishable survives. Read origin through this rather than reading the fields directly: it is what keeps a plugin-supplied or hand-built value from reaching a published document unchecked. An artifact wins over a repository in the case -- which the constructors never produce -- where both are set.
func (*DependencyOrigin) UnmarshalJSON ¶
func (o *DependencyOrigin) UnmarshalJSON(data []byte) error
UnmarshalJSON applies the origin rule as a value arrives, so a location that would be rejected on read cannot be stored, forwarded to another component, or written back out. A value that fails validation decodes to an empty origin -- including a payload from an older build that still carries the removed "disputed" field, whose remaining values stand on their own.
type DependencyQuery ¶
DependencyQuery identifies a specific component target.
type DependencyRelationship ¶
type DependencyRelationship string
DependencyRelationship describes how a dependency occurrence relates to the application or manifest root that owns its graph.
const ( // DependencyRelationshipDirect identifies a dependency declared by a root. DependencyRelationshipDirect DependencyRelationship = "direct" // DependencyRelationshipTransitive identifies a dependency reached through another dependency. DependencyRelationshipTransitive DependencyRelationship = "transitive" // DependencyRelationshipUnknown identifies a dependency whose parent could not be recovered. DependencyRelationshipUnknown DependencyRelationship = "unknown" )
func MergeDependencyRelationship ¶
func MergeDependencyRelationship(current, next DependencyRelationship) DependencyRelationship
MergeDependencyRelationship combines occurrence relationships for a merged graph, retaining the strongest known project relationship.
func ParseDependencyRelationship ¶
func ParseDependencyRelationship(value string) DependencyRelationship
ParseDependencyRelationship normalizes a dependency relationship value.
func RelationshipForPath ¶
func RelationshipForPath(path []GraphNode) DependencyRelationship
RelationshipForPath returns the explicit target relationship when present, otherwise derives directness from a root-to-target path.
type DependencySource ¶
type DependencySource string
DependencySource describes how a dependency occurrence is resolved.
const ( DependencySourceRegistry DependencySource = "registry" DependencySourceProject DependencySource = "project" DependencySourceWorkspace DependencySource = "workspace" DependencySourceFile DependencySource = "file" DependencySourceGit DependencySource = "git" DependencySourceURL DependencySource = "url" )
type Diff ¶
type Diff struct {
Added []*DependencyNode
Removed []*DependencyNode
Updated []VersionChange
Transitions []DependencyDetailTransition
}
Diff summarizes the dependency changes between two graphs. Diffs are dependency-only: manifest and module nodes are structural and do not participate.
func Compare ¶
Compare returns added, removed, version-changed, and detail-changed dependencies between base and head. Only dependency nodes participate: manifest and module nodes are structural.
Example ¶
Compare reports what changed between two graphs, pairing version bumps.
package main
import (
"fmt"
"github.com/bomly-dev/bomly-sdk/model"
)
func mustNode(purl string) *model.DependencyNode {
node, err := model.NewDependencyNodeFromPURL(purl)
if err != nil {
panic(err)
}
return node
}
func main() {
base, head := model.New(), model.New()
_ = base.AddNode(mustNode("pkg:npm/react@18.2.0"))
_ = base.AddNode(mustNode("pkg:npm/left-pad@1.3.0"))
_ = head.AddNode(mustNode("pkg:npm/react@18.3.0"))
_ = head.AddNode(mustNode("pkg:npm/zod@3.0.0"))
diff := model.Compare(base, head)
for _, change := range diff.Updated {
fmt.Println("updated:", change.Before.NodeID(), "->", change.After.NodeID())
}
for _, node := range diff.Added {
fmt.Println("added:", node.NodeID())
}
for _, node := range diff.Removed {
fmt.Println("removed:", node.NodeID())
}
}
Output: updated: pkg:npm/react@18.2.0 -> pkg:npm/react@18.3.0 added: pkg:npm/zod@3.0.0 removed: pkg:npm/left-pad@1.3.0
type Digest ¶
type Digest struct {
Algorithm DigestAlgorithm `json:"algorithm,omitempty"`
Value string `json:"value,omitempty"`
// Subject says what the digest covers. Empty means the published artifact,
// which is what most ecosystems record and what a consumer should assume.
// It exists because some ecosystems record a hash that is not a hash of a
// file: a Go module's "h1:" value is SHA-256 over a manifest of the source
// tree's file hashes, not over the module zip, so a consumer that treats it
// as an artifact digest and compares it against a downloaded file will
// always find a mismatch.
//
// Gate: ParseDigestSubject, through Digest.Normalized. The vocabulary is
// closed, and an unrecognized subject rejects the whole digest rather
// than being cleared -- empty is itself a claim ("the published
// artifact"), so treating an uninterpretable label as absent would
// publish something the producer never said.
//
// Merge class: part of the digest's set identity. Two records with the
// same algorithm and value but different subjects are distinct claims and
// both survive a union, because they say different things about what was
// hashed.
Subject DigestSubject `json:"subject,omitempty"`
}
Digest captures integrity information for a package artifact.
func (Digest) MarshalJSON ¶
MarshalJSON applies the same rule on the way out, so a hand-built value that bypassed the constructors is still held to it at the wire.
func (Digest) Normalized ¶
Normalized returns the digest with its algorithm resolved to the canonical token and its value trimmed, or false when the digest cannot be published.
func (*Digest) UnmarshalJSON ¶
UnmarshalJSON resolves the algorithm spelling as a value arrives, so a producer that wrote CycloneDX's "SHA-256" or SPDX's "SHA256" is understood rather than silently carried as an algorithm nothing matches. A digest that cannot be published decodes to the zero value, following DependencyOrigin: both formats close their hash enumeration, so an unpublishable digest has nowhere to go, and dropping it is better than failing the whole payload.
func (Digest) Validate ¶
Validate reports why a digest cannot be published, or nil when it can.
The value itself is checked for shape, not for length-per-algorithm: the encoding is not fixed. Ecosystems record digests in hex, in base64 (npm's "sha512-..." integrity strings), and over subjects that are not files at all (a Go module "h1:" dirhash), so a per-algorithm hex length would reject values that are correct for their ecosystem.
type DigestAlgorithm ¶
type DigestAlgorithm string
DigestAlgorithm identifies an artifact digest algorithm. The vocabulary is the registry in digest.go, aligned with the SPDX 2.3 and CycloneDX 1.5/1.6 hash vocabularies; see DigestAlgorithms.
const ( DigestAlgorithmMD2 DigestAlgorithm = "md2" DigestAlgorithmMD4 DigestAlgorithm = "md4" DigestAlgorithmMD5 DigestAlgorithm = "md5" DigestAlgorithmMD6 DigestAlgorithm = "md6" DigestAlgorithmSHA1 DigestAlgorithm = "sha1" DigestAlgorithmSHA224 DigestAlgorithm = "sha224" DigestAlgorithmSHA256 DigestAlgorithm = "sha256" DigestAlgorithmSHA384 DigestAlgorithm = "sha384" DigestAlgorithmSHA512 DigestAlgorithm = "sha512" DigestAlgorithmSHA3256 DigestAlgorithm = "sha3-256" DigestAlgorithmSHA3384 DigestAlgorithm = "sha3-384" DigestAlgorithmSHA3512 DigestAlgorithm = "sha3-512" DigestAlgorithmBLAKE2b256 DigestAlgorithm = "blake2b-256" DigestAlgorithmBLAKE2b384 DigestAlgorithm = "blake2b-384" DigestAlgorithmBLAKE2b512 DigestAlgorithm = "blake2b-512" DigestAlgorithmBLAKE3 DigestAlgorithm = "blake3" DigestAlgorithmADLER32 DigestAlgorithm = "adler32" DigestAlgorithmStreebog256 DigestAlgorithm = "streebog-256" DigestAlgorithmStreebog512 DigestAlgorithm = "streebog-512" )
The digest algorithm registry. Both SBOM formats define a closed hash vocabulary, so an algorithm Bomly cannot name in the target format cannot be published at all -- which makes the registry, not a pair of string constants, the thing that decides whether a digest survives export.
Canonical SDK spellings are lowercase and keep the family separator that the formats use ("sha3-256", not "sha3256"), so a token reads the way the algorithm is named in its own literature.
func DigestAlgorithms ¶
func DigestAlgorithms() []DigestAlgorithm
DigestAlgorithms returns every registered algorithm in canonical order.
func ParseDigestAlgorithm ¶
func ParseDigestAlgorithm(value string) (DigestAlgorithm, error)
ParseDigestAlgorithm resolves any spelling either format uses -- and the canonical SDK token -- to the canonical token. It errors on an algorithm no format defines, because such a digest has no export projection and a consumer is better told than handed a value it cannot publish.
func (DigestAlgorithm) CycloneDXName ¶
func (a DigestAlgorithm) CycloneDXName() string
CycloneDXName returns the algorithm's CycloneDX 1.5/1.6 spelling, or "" when CycloneDX has no such member -- which is the case for the SPDX-only algorithms MD2, MD4, MD6, SHA224, and ADLER32. Treat "" as "omit this digest", as for SPDXName.
func (DigestAlgorithm) SPDXName ¶
func (a DigestAlgorithm) SPDXName() string
SPDXName returns the algorithm's SPDX 2.3 spelling, or "" when SPDX has no such member. A caller emitting a checksum must treat "" as "omit this digest": SPDX's algorithm field is a closed enumeration, so there is no spelling that would validate.
func (DigestAlgorithm) String ¶
func (a DigestAlgorithm) String() string
String returns the canonical token.
func (DigestAlgorithm) Valid ¶
func (a DigestAlgorithm) Valid() bool
Valid reports whether a is a registered algorithm.
type DigestSubject ¶
type DigestSubject string
DigestSubject identifies what a digest was computed over.
const ( // DigestSubjectArtifact is a digest of the published file itself. It is // the zero value: a producer that does not say means the artifact. DigestSubjectArtifact DigestSubject = "" // DigestSubjectSourceTree is a digest over a source tree or over a // manifest of its file hashes, such as a Go module "h1:" dirhash. DigestSubjectSourceTree DigestSubject = "source-tree" // DigestSubjectMetadata is a digest of a package's metadata document // rather than of the package itself, such as a manifest or lockfile entry. DigestSubjectMetadata DigestSubject = "metadata" )
func ParseDigestSubject ¶
func ParseDigestSubject(value string) (DigestSubject, error)
ParseDigestSubject normalizes a digest subject. The vocabulary is closed: Subject says what a hash covers, and it takes part in a digest's identity, so an unrecognized value is an integrity claim no consumer can interpret rather than a label to carry along.
func (DigestSubject) String ¶
func (s DigestSubject) String() string
String returns the subject token.
func (DigestSubject) Valid ¶
func (s DigestSubject) Valid() bool
Valid reports whether s is a recognized subject.
type DocumentAssertions ¶
type DocumentAssertions struct {
// Identity is the document's own identifier: SPDX's documentNamespace, or
// a CycloneDX BOM-Link ("urn:cdx:<serial>/<version>"). It is held to the
// IRI rule rather than the web-URL rule, because a BOM-Link is a URN and
// the web gate would reject the identifier a merged export links back to.
Identity string `json:"identity,omitempty"`
// Name is the document's stated name.
Name string `json:"name,omitempty"`
// DataLicense is the license of the document's own data, which SPDX
// requires and CycloneDX does not model. Held to the same expression rule
// as a package license, so an unparseable value is dropped rather than
// written into a field consumers read as an SPDX expression.
DataLicense string `json:"data_license,omitempty"`
// Created is the document's timestamp, as the source stated it. Kept
// verbatim: re-rendering a timestamp is a change to a claim, and the two
// formats agree on RFC 3339 anyway.
Created string `json:"created,omitempty"`
// Creators are the parties credited with producing the document. Contact
// carries no email, per ADR-0037's deferred privacy review.
Creators []Contact `json:"creators,omitempty"`
// Tools are the tools credited with producing the document.
Tools []DocumentTool `json:"tools,omitempty"`
// Comment is the document-level comment.
Comment string `json:"comment,omitempty"`
// Version is the document's own version number: CycloneDX's top-level
// version, which a BOM-Link's "/<n>" tail repeats, and which SPDX 2.x
// leaves implicit at 1. Zero means the source stated none; the default is
// the exporting format's to apply, not this carrier's, so an entry that
// never stated a version keeps writing the bytes it wrote before the
// field existed.
//
// Gate: a positive integer, else absent. Merge class: fill-gaps, as one
// provenance tuple with Identity and Checksum -- see
// MergeDocumentAssertions.
Version int `json:"version,omitempty"`
// Checksum is a digest over the source document's original bytes,
// computed at ingest while those bytes are in hand: it cannot be
// recovered from the parsed model later, and an SPDX externalDocumentRef
// is invalid without one, so a merged export that lacks it cannot name
// its sources at all.
//
// Gate: Digest.Normalized, the same one a package digest passes, plus
// the artifact subject: a digest over a source tree or a metadata record
// is not a hash of the document's bytes, and the SPDX reference has no
// slot to say so. Merge class: fill-gaps, as one provenance tuple with
// Identity and Version --
// a checksum is a claim about one document's bytes and never attaches
// to another document's identity. See MergeDocumentAssertions.
Checksum *Digest `json:"checksum,omitempty"`
// Sources are the documents this one was built from, when it said so:
// SPDX externalDocumentRefs, or CycloneDX external references of type
// "bom". A merged export writes one link per source (ADR-0037); without
// somewhere to read them back into, a single ingest of that export lost
// every trace of its inputs.
//
// Gate: each entry passes DocumentSource.Normalized; entries with the
// same (Identity, Version) key fold, the checksum filling a gap; the
// list is sorted for byte-stable output and bounded by
// maxDocumentSources, applied to the input before any work is done on
// it. An entry naming this document itself -- the same identity and
// the same known version exactly, per isSelfSource -- is dropped: a
// document is not built from itself, and recording it would write a
// cycle. Any other key of the same namespace, a prior version included,
// is a different document and is kept, as is an unversioned entry while
// the document's own version is still unknown.
// Merge class: set, keyed by (Identity, Version) -- a document built
// from a merged document inherits that document's sources beside its
// own identity, so provenance survives more than one hop.
Sources []DocumentSource `json:"sources,omitempty"`
// Format is the format and specification version the source document was
// decoded as -- the token package sbom names a decode target by, such as
// "cyclonedx-1.6+json" or "spdx-2.3+json". It describes the source, so a
// conversion never re-emits it: the target format's own header says what
// the output is, and this field says what the input was.
//
// Gate: NormalizeDocumentFormat -- a single bounded token with no
// whitespace or control characters, the same rule a source scope word
// takes. Merge class: scalar, fill-gaps.
Format string `json:"format,omitempty"`
}
DocumentAssertions are the claims a source document makes about itself, carried per GraphEntry so a merged export can say which claim came from which document.
func MergeDocumentAssertions ¶
func MergeDocumentAssertions(dst, src DocumentAssertions) DocumentAssertions
MergeDocumentAssertions combines two sets of document claims.
Scalars fill gaps only: two documents disagreeing about their own name is not something to resolve by picking one, so the first stated value stands and the second is dropped rather than overwriting it. Creators and tools union, because two documents having produced a merged one is the normal case and both deserve credit.
Both sides are gated on the way in. An unpublishable value must not become visible in-process just because it arrived through a merge rather than through a constructor.
func (DocumentAssertions) Clone ¶
func (d DocumentAssertions) Clone() DocumentAssertions
Clone returns a deep copy.
func (DocumentAssertions) IsEmpty ¶
func (d DocumentAssertions) IsEmpty() bool
IsEmpty reports whether the assertions carry nothing.
func (DocumentAssertions) MarshalJSON ¶
func (d DocumentAssertions) MarshalJSON() ([]byte, error)
MarshalJSON applies every field's gate on the way out, so a hand-built value that bypassed Normalized is still held to it at the wire. Without this a negative version reached a reader unchanged, and a checksum the digest codec had zeroed still encoded as "checksum":{} -- a non-nil record an exporter would read as a checksum being present.
func (DocumentAssertions) Normalized ¶
func (d DocumentAssertions) Normalized() (DocumentAssertions, bool)
Normalized returns the assertions with every field held to its gate, and reports whether anything publishable remains.
Each field is gated independently: a document with an unusable data license and a good identity keeps the identity. Dropping the whole record because one field failed would lose the link a merged export needs.
func (*DocumentAssertions) UnmarshalJSON ¶
func (d *DocumentAssertions) UnmarshalJSON(data []byte) error
UnmarshalJSON applies the same gates on the way in, so a payload from a plugin or an older producer is held to them whether or not the caller remembers to call Normalized. A record that gates to nothing decodes to the zero value rather than failing the payload: the entry it belongs to is still a graph, and a document with no publishable claims is merely absent.
type DocumentSource ¶
type DocumentSource struct {
// Identity is the source document's own identifier. Merge class: part
// of the set key.
Identity string `json:"identity,omitempty"`
// Version is the source document's version, when the reference stated
// it or a BOM-Link identity's tail carries it. Merge class: part of the
// set key -- an unstated version is its own key, distinct from every
// stated one, which for a BOM-Link cannot arise since the tail fills it.
Version int `json:"version,omitempty"`
// Checksum is a digest over the source document's original bytes, when
// the reference carried one -- SPDX always does. Merge class: scalar,
// fill-gaps within the key; the first stated digest stands.
Checksum *Digest `json:"checksum,omitempty"`
}
DocumentSource names one document another document was built from: the link tuple a merged export needs to reference it. It is the same tuple DocumentAssertions carries for the document itself -- identity, version, checksum -- because a reference is written from exactly those. An SPDX externalDocumentRef requires the checksum on every entry, so a list of bare identities could not be re-exported as valid SPDX references at all; and the wire is frozen once shipped, so the record has to carry it from the start.
Gates: Identity is required and held to the IRI rule Identity is held to; Version is a positive integer that agrees with a BOM-Link identity's tail; Checksum passes the digest gate with the artifact subject. Each is the rule the document's own field follows, stated once in the shared helpers.
Merge class, as an element of DocumentAssertions.Sources: a set keyed by (Identity, Version) exactly. Two entries with the same key are one source and fill each other's gaps; an entry with no stated version is a distinct key from every stated version of the same identity, never folded into one. That is what keeps the set commutative and associative under pairwise merges: folding an unversioned entry into "the one stated version so far" gave a different answer depending on which version a later merge brought, and once folded the ambiguity could not be restored.
func (DocumentSource) Clone ¶
func (s DocumentSource) Clone() DocumentSource
Clone returns a deep copy.
func (DocumentSource) MarshalJSON ¶
func (s DocumentSource) MarshalJSON() ([]byte, error)
MarshalJSON applies the gates on the way out, so a hand-built source is held to them at the wire like every other untrusted-input field.
func (DocumentSource) Normalized ¶
func (s DocumentSource) Normalized() (DocumentSource, bool)
Normalized returns the source with each field held to its gate, and reports whether it still names a document. A source with no publishable identity names nothing and is dropped whole; the other two fields drop individually.
func (*DocumentSource) UnmarshalJSON ¶
func (s *DocumentSource) UnmarshalJSON(data []byte) error
UnmarshalJSON applies the gates on the way in. A source that names nothing decodes to the zero value, which the parent's gate then drops.
type DocumentTool ¶
type DocumentTool struct {
// Vendor is the organization that publishes the tool. Optional.
Vendor string `json:"vendor,omitempty"`
// Name is the tool's name. A tool without one is not a tool.
Name string `json:"name,omitempty"`
// Version is the tool's version, when the document stated it.
Version string `json:"version,omitempty"`
}
DocumentTool is one tool that produced a document.
Both formats record this, and neither models it the same way -- SPDX writes a creator string, CycloneDX a structured tool entry -- so the structured form is kept and the flat one rendered from it, never the reverse.
func (DocumentTool) Normalized ¶
func (t DocumentTool) Normalized() (DocumentTool, bool)
Normalized returns the tool with its fields bounded and trimmed, and reports whether anything publishable remains. A tool with no name is dropped: a version with nothing to attach it to says nothing.
type EPSSScore ¶
type EPSSScore struct {
CVE string `json:"cve,omitempty"`
EPSS float64 `json:"epss"`
Percentile float64 `json:"percentile,omitempty"`
Date string `json:"date,omitempty"`
}
EPSSScore captures Exploit Prediction Scoring System data for a vulnerability.
type Ecosystem ¶
type Ecosystem string
Ecosystem groups package managers under a registry-specific dependency model.
const ( EcosystemUnknown Ecosystem = "" EcosystemNPM Ecosystem = "npm" EcosystemMaven Ecosystem = "maven" EcosystemGo Ecosystem = "go" EcosystemPython Ecosystem = "python" EcosystemALPM Ecosystem = "alpm" EcosystemAPK Ecosystem = "apk" EcosystemCPP Ecosystem = "cpp" EcosystemConda Ecosystem = "conda" EcosystemDart Ecosystem = "dart" EcosystemDPKG Ecosystem = "dpkg" EcosystemElixir Ecosystem = "elixir" EcosystemErlang Ecosystem = "erlang" EcosystemGitHub Ecosystem = "github-actions" EcosystemHaskell Ecosystem = "haskell" EcosystemHomebrew Ecosystem = "homebrew" EcosystemLua Ecosystem = "lua" EcosystemDotNet Ecosystem = "dotnet" EcosystemNix Ecosystem = "nix" EcosystemOCaml Ecosystem = "ocaml" EcosystemPHP Ecosystem = "php" EcosystemPortage Ecosystem = "portage" EcosystemProlog Ecosystem = "prolog" EcosystemR Ecosystem = "r" EcosystemRPM Ecosystem = "rpm" EcosystemRuby Ecosystem = "ruby" EcosystemRust Ecosystem = "rust" EcosystemScala Ecosystem = "scala" EcosystemSBOM Ecosystem = "sbom" EcosystemSnap Ecosystem = "snap" EcosystemSwift Ecosystem = "swift" EcosystemTerraform Ecosystem = "terraform" EcosystemWordPress Ecosystem = "wordpress" EcosystemOther Ecosystem = "other" )
Keep this list aligned with the Syft-backed support matrix in docs/SUPPORT_MATRIX.md and the Syft manifest mappings in internal/detectors/syft/detector.go.
func EcosystemForPURLType ¶
EcosystemForPURLType resolves the Bomly ecosystem a package URL type names, and returns EcosystemUnknown when no ecosystem is decidable from the type alone. It is the reverse of PackageURLTypeForValues.
This is the durable home for a join consumers used to transcribe: bomly-cli carried three copies of it, and they had already drifted — one answered Elixir for pkg:hex, which is exactly the guess this refuses, and none of them had learned hackage, cran, opam, deb or otp, so five ecosystems came back unknown (ADR-0040; issue #69).
Two purlkit tables answer, in that order. The type join covers the purl types whose spec name differs from Bomly's ecosystem token (golang → go, gem → ruby, …); the canonical alias table covers the direct ones (npm, apk, rpm, conda, …), which the type join deliberately omits. Without the second lookup a node built from a bare package URL would carry no ecosystem, and ecosystem-specific behavior — an npm scope in EcosystemName(), for one — would silently degrade.
Ambiguity is refused rather than guessed. pkg:hex serves Elixir and Erlang alike and resolves to EcosystemUnknown: relabelling every round-tripped Erlang dependency as Elixir is worse than declining to answer. pkg:generic names no ecosystem either — an identity that fell back to it records the type it could not express in the GenericFallbackTypeQualifier qualifier, and that value resolves here. A type outside both tables resolves to EcosystemUnknown, which leaves a detector's own token to stand: the ecosystem vocabulary is open where the tables have no say.
func ParseEcosystem ¶
ParseEcosystem normalizes a user-provided ecosystem value.
type EcosystemFilter ¶
EcosystemFilter specifies inclusion and exclusion rules for filtering ecosystems.
func (EcosystemFilter) Excludes ¶
func (f EcosystemFilter) Excludes(name Ecosystem) bool
Excludes reports whether a detector name is explicitly denied.
func (EcosystemFilter) Includes ¶
func (f EcosystemFilter) Includes(name Ecosystem) bool
Includes reports whether a detector name is explicitly allowed.
type EdgeKind ¶
type EdgeKind string
EdgeKind says what an edge between two nodes asserts.
Every edge used to mean the same thing, because every node was a dependency and the only relationship was "depends on". With the typed node union a graph also holds manifests and modules, and the edge from a manifest to the module it declares is not a dependency claim -- exporting it as one puts a relationship in a document that no detector asserted.
const ( // EdgeKindUnknown is an edge whose kind was never stated. It is what a // payload written before this field carried, and it is derived from the // nodes it joins rather than published as-is. EdgeKindUnknown EdgeKind = "" // EdgeKindDependsOn is the dependency claim: the source needs the target. EdgeKindDependsOn EdgeKind = "depends-on" // EdgeKindDescribes joins a manifest to a module it declares. It is a // structural edge, not a dependency: a package.json does not depend on the // workspace member it describes. EdgeKindDescribes EdgeKind = "describes" )
func DeriveEdgeKind ¶
DeriveEdgeKind names what an edge between two nodes asserts, from the kinds of the nodes themselves.
This is what makes the field safe to add: a graph built before the field existed, or by a caller that does not set it, still exports correct relationships, because the structure already carries the answer. Only a manifest-to-module edge is structural; everything else is a dependency claim, including a manifest that names a dependency directly, which is what a lockfile with no workspace layer produces.
func MergeEdgeKind ¶
MergeEdgeKind combines two kinds for one edge, which happens when graphs merge or duplicate nodes fold.
A stated kind beats an unstated one, so folding a legacy edge into a typed one keeps the type. Two different stated kinds disagree about what the edge means; the dependency claim wins, because it is the stronger assertion and losing it would drop the edge from a dependency-only export.
func ParseEdgeKind ¶
ParseEdgeKind normalizes an edge kind read from a payload. An empty value is unknown, which is legal and is what every pre-field payload carries; anything else unrecognized is an error, so a kind Bomly cannot read fails a decode rather than silently becoming a dependency claim.
type ExternalReference ¶
type ExternalReference struct {
// Category is SPDX's referenceCategory. Empty for a CycloneDX-sourced
// reference, which has no such axis.
Category ExternalReferenceCategory `json:"category,omitempty"`
// Type is the reference type: SPDX's referenceType or CycloneDX's type.
// The vocabulary is open -- both specifications add types, and a type
// this build does not know still round-trips -- so it is bounded and
// checked for shape rather than matched against a closed list.
Type string `json:"type,omitempty"`
// Locator is what the reference points at. Its shape is decided by
// LocatorKindFor, not by inspecting the value: a locator that fails its
// declared grammar is a rejected reference, not one to reclassify.
Locator string `json:"locator,omitempty"`
// Comment is the source document's note about this reference. SPDX has a
// comment field; CycloneDX 1.6 has one too.
Comment string `json:"comment,omitempty"`
// Hashes are the reference's own integrity claims. CycloneDX carries
// these natively; SPDX 2.3 has no slot for them, so a caller emitting
// SPDX has nowhere to put them and omits them.
//
// Gate: Digest.Normalized, through mergeDigestSet. Merge class: set,
// unioned by the digest's own identity.
Hashes []Digest `json:"hashes,omitempty"`
}
ExternalReference is one external reference a source document attached to a component: an advisory, a repository, a package-manager coordinate, a CPE.
Gate and merge class ¶
Every field is gated by ExternalReference.Normalized, applied on both wire directions. A reference whose locator cannot be published is dropped entirely rather than published without it, since a reference with no locator points at nothing.
References are a set. Their identity is the (category, type, locator) triple, so the same locator recorded under two types stays two references -- they say different things about the component. Hashes union within a matching reference, and the comment fills a gap.
func MergeExternalReferences ¶
func MergeExternalReferences(existing, additions []ExternalReference) []ExternalReference
MergeExternalReferences unions reference sets, keeping the first record of each distinct triple. A later record with the same triple contributes its hashes and fills a missing comment: it is the same assertion, seen twice.
Both sides are re-gated, and no early return when one is empty -- an existing slice may hold references that never passed the gate, and returning it untouched would leave them visible to in-process consumers.
func (ExternalReference) LocatorKind ¶
func (r ExternalReference) LocatorKind() LocatorKind
LocatorKind returns the shape this reference's locator is held to.
func (ExternalReference) MarshalJSON ¶
func (r ExternalReference) MarshalJSON() ([]byte, error)
MarshalJSON applies the same rule on the way out.
func (ExternalReference) Normalized ¶
func (r ExternalReference) Normalized() (ExternalReference, bool)
Normalized returns the reference with every field re-checked, or false when it says nothing publishable. It is the gate for a reference that arrived from a plugin, an ingested document, or a hand-built value.
func (*ExternalReference) UnmarshalJSON ¶
func (r *ExternalReference) UnmarshalJSON(data []byte) error
UnmarshalJSON applies the reference rule as a value arrives, so a locator that would be rejected on read cannot be stored, forwarded, or written back out. A reference that says nothing publishable decodes to the zero value, following DependencyOrigin.
type ExternalReferenceCategory ¶
type ExternalReferenceCategory string
ExternalReferenceCategory is SPDX's referenceCategory axis: the grouping it puts an external reference in, alongside the reference type.
It is retained rather than re-derived because SPDX's external reference is a triple -- category, type, locator -- and the same type string can appear under more than one category in principle. Dropping the category on ingest would mean guessing it again on export.
CycloneDX has no equivalent axis. A reference that came from a CycloneDX document carries ExternalReferenceCategoryUnknown, which is a fact about the source, not a gap to fill in.
const ( // ExternalReferenceCategoryUnknown means the source document has no // category axis. Every CycloneDX-sourced reference is this. ExternalReferenceCategoryUnknown ExternalReferenceCategory = "" // ExternalReferenceCategorySecurity is SPDX's SECURITY. ExternalReferenceCategorySecurity ExternalReferenceCategory = "security" // ExternalReferenceCategoryPackageManager is SPDX's PACKAGE-MANAGER. ExternalReferenceCategoryPackageManager ExternalReferenceCategory = "package-manager" // ExternalReferenceCategoryPersistentID is SPDX's PERSISTENT-ID. ExternalReferenceCategoryPersistentID ExternalReferenceCategory = "persistent-id" // ExternalReferenceCategoryOther is SPDX's OTHER. ExternalReferenceCategoryOther ExternalReferenceCategory = "other" )
func ParseExternalReferenceCategory ¶
func ParseExternalReferenceCategory(value string) (ExternalReferenceCategory, error)
ParseExternalReferenceCategory normalizes a category, accepting SPDX's own spelling and the canonical token. An empty value is unknown, which is legal and is what every CycloneDX-sourced reference carries; anything else unrecognized is an error.
func (ExternalReferenceCategory) SPDXName ¶
func (c ExternalReferenceCategory) SPDXName() string
SPDXName returns the category's SPDX spelling, or "" when it has none -- which is the case for a CycloneDX-sourced reference. A caller emitting SPDX treats "" as "this reference has no SPDX projection".
func (ExternalReferenceCategory) String ¶
func (c ExternalReferenceCategory) String() string
String returns the canonical token.
type FailOnConstraint ¶
type FailOnConstraint struct {
Kind FailOnKind
Value string
}
FailOnConstraint is one parsed --fail-on value. Vulnerability constraints form an AND-set. Other finding types may define independent gates, such as a dependency source change in a diff.
func ParseFailOn ¶
func ParseFailOn(raw string) (FailOnConstraint, error)
ParseFailOn parses one raw --fail-on value into a typed constraint. Severity tokens (any|low|medium|high|critical) yield a SeverityConstraint. "reachable" yields a ReachabilityConstraint. "exploitable" yields an ExploitabilityConstraint. "source-change" yields a SourceChangeConstraint. Empty input returns the zero value with no error so callers can treat empty repeats as no-ops.
func ParseFailOnList ¶
func ParseFailOnList(raws []string) ([]FailOnConstraint, error)
ParseFailOnList parses every raw value, skipping empty entries. It returns an aggregate error if any value is invalid; valid constraints are still returned alongside the error so callers can surface partial diagnostics.
func (FailOnConstraint) String ¶
func (c FailOnConstraint) String() string
String returns a stable string form for the constraint, suitable for debug logs and error messages.
type FailOnKind ¶
type FailOnKind string
FailOnKind classifies one --fail-on constraint.
const ( // SeverityConstraint matches when a finding's severity is at or above // the constraint Value (any|low|medium|high|critical). SeverityConstraint FailOnKind = "severity" // ReachabilityConstraint matches when a vulnerability's reachability // status equals the constraint Value (currently only "reachable"). ReachabilityConstraint FailOnKind = "reachability" // ExploitabilityConstraint matches when a vulnerability has known // exploitation metadata. ExploitabilityConstraint FailOnKind = "exploitability" // SourceChangeConstraint matches package-auditor findings for dependency // source changes in a diff. SourceChangeConstraint FailOnKind = "source-change" )
type Finding ¶
type Finding struct {
ID string `json:"id"`
Kind FindingKind `json:"kind"`
Title string `json:"title,omitempty"`
Severity SeverityLevel `json:"severity,omitempty"`
PolicyStatus FindingPolicyStatus `json:"policy_status,omitempty"`
Reasons []string `json:"reasons,omitempty"`
Source string `json:"source,omitempty"`
Auditor string `json:"auditor,omitempty"`
// RuleID is the stable auditor rule that produced the finding. Unlike ID,
// it must not contain package versions or project-specific occurrence data.
RuleID string `json:"rule_id,omitempty"`
VexStatus VEXStatus `json:"vex_status,omitempty"`
VEXJustification string `json:"vex_justification,omitempty"`
// PackageRef is the PURL of the offending package in the registry.
PackageRef string `json:"package_ref,omitempty"`
// DependencyRefs are the dependency node IDs that introduced the package.
DependencyRefs []string `json:"dependency_refs,omitempty"`
// VulnerabilityID is the advisory id within the referenced package, set
// for vulnerability-kind findings.
VulnerabilityID string `json:"vulnerability_id,omitempty"`
// Decision records which resolver settled PolicyStatus and why, when one
// did. PolicyStatus is what a consumer enforces; Decision is what it can
// show. Gate and merge class: see FindingPolicyDecision. Optional;
// omitted by auditors that carry no resolver.
Decision *FindingPolicyDecision `json:"decision,omitempty"`
}
Finding describes a normalized audit result as a reference into the package registry rather than an inlined copy of vulnerability data. Consumers resolve the underlying enrichment via PackageRef (PURL) and, for vulnerability findings, VulnerabilityID (the OSV id inside the referenced package).
func (Finding) MarshalJSON ¶ added in v0.14.0
MarshalJSON writes the gated form, so a status set directly on a hand-built finding is held to the vocabulary too.
func (*Finding) UnmarshalJSON ¶
UnmarshalJSON accepts the current policy_status field and the protocol-v1 legacy field so existing external auditor plugins continue to interoperate.
type FindingKind ¶
type FindingKind string
FindingKind categorizes audit findings by the underlying concern the auditor is reporting on. Built-in auditors normally emit these kinds:
FindingKindVulnerability — advisory findings from the vulnerability auditor
FindingKindLicense — emitted by the license auditor
FindingKindPackage — package policy findings, including dependency
source changes
External plugins may introduce new kinds; consumers should treat the list as open.
const ( FindingKindVulnerability FindingKind = "vulnerability" FindingKindLicense FindingKind = "license" FindingKindPackage FindingKind = "package" )
type FindingPolicyDecision ¶
type FindingPolicyDecision struct {
Status FindingPolicyStatus `json:"status,omitempty"`
Source string `json:"source,omitempty"`
Reason string `json:"reason,omitempty"`
}
FindingPolicyDecision is a resolver's proposed policy status for one finding. Source and Reason provide diagnostic provenance: which resolver decided, and why. It is also a wire value, carried on Finding.Decision, so a verdict can be explained after the run that produced it has ended.
Gate: Normalized, applied in the JSON codec on both directions -- Status is a FindingPolicyStatus or cleared, since a status outside the vocabulary has no rank and a reader would otherwise have to decide what it meant; Source and Reason are free text, trimmed. Merge class: scalar, fill-gaps -- a decision already recorded is not overwritten by a later resolver's.
func (FindingPolicyDecision) MarshalJSON ¶ added in v0.14.0
func (d FindingPolicyDecision) MarshalJSON() ([]byte, error)
MarshalJSON writes the gated form.
func (FindingPolicyDecision) Normalized ¶ added in v0.14.0
func (d FindingPolicyDecision) Normalized() FindingPolicyDecision
Normalized returns the decision held to its gate: a status outside the vocabulary is cleared, the free text is trimmed.
func (*FindingPolicyDecision) UnmarshalJSON ¶ added in v0.14.0
func (d *FindingPolicyDecision) UnmarshalJSON(data []byte) error
UnmarshalJSON reads through the gate, so a managed auditor or a decoded record cannot put a status the vocabulary does not name on a finding.
type FindingPolicyResolver ¶
type FindingPolicyResolver interface {
ResolveFindingPolicy(context.Context, Finding, *PackageRegistry) (FindingPolicyDecision, bool)
}
FindingPolicyResolver may refine a finding's policy status during auditing. Resolvers must not remove findings or rewrite their evidence.
type FindingPolicyStatus ¶
type FindingPolicyStatus string
FindingPolicyStatus controls whether a finding fails evaluation, remains a warning, or is accepted by project policy.
const ( FindingPolicyStatusFail FindingPolicyStatus = "fail" FindingPolicyStatusWarn FindingPolicyStatus = "warn" // FindingPolicyStatusSuppressed keeps a finding visible while excluding it // from policy-failure evaluation. FindingPolicyStatusSuppressed FindingPolicyStatus = "suppressed" )
type FixAvailable ¶
type FixAvailable struct {
Version string `json:"version,omitempty"`
Date string `json:"date,omitempty"`
Kind FixAvailableKind `json:"kind,omitempty"`
}
FixAvailable captures one version/date/kind tuple for an available fix.
type FixAvailableKind ¶
type FixAvailableKind string
FixAvailableKind identifies why a fix version was selected.
const (
FixAvailableFirstObserved FixAvailableKind = "first-observed"
)
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph stores the typed graph nodes as a directed graph, keyed by NodeID. A node's ID is its identity (ADR-0041), so the ID index doubles as the identity index: two nodes are the same node exactly when their IDs match.
Example ¶
A graph is built from nodes whose identity is their canonical package URL, joined by edges; every iteration is ordered by ID.
package main
import (
"fmt"
"github.com/bomly-dev/bomly-sdk/model"
)
func mustNode(purl string) *model.DependencyNode {
node, err := model.NewDependencyNodeFromPURL(purl)
if err != nil {
panic(err)
}
return node
}
func main() {
g := model.New()
app := mustNode("pkg:npm/app@1.0.0")
react := mustNode("pkg:npm/react@18.2.0")
react.Scopes = []model.Scope{model.ScopeRuntime}
jest := mustNode("pkg:npm/jest@29.0.0")
jest.Scopes = []model.Scope{model.ScopeDevelopment}
for _, node := range []*model.DependencyNode{app, react, jest} {
if err := g.AddNode(node); err != nil {
panic(err)
}
}
_ = g.AddEdge(app.NodeID(), react.NodeID())
_ = g.AddEdge(app.NodeID(), jest.NodeID())
for _, dep := range g.DependencyNodes() {
children, _ := g.DirectDependencies(dep.NodeID())
fmt.Println(dep.NodeID(), len(children))
}
}
Output: pkg:npm/app@1.0.0 2 pkg:npm/jest@29.0.0 0 pkg:npm/react@18.2.0 0
func ConsolidateGraphContainerEntry ¶
func ConsolidateGraphContainerEntry(container *GraphContainer) (*Graph, error)
ConsolidateGraphContainerEntry ensures one entry is present.
func FilterGraphByScope ¶
FilterGraphByScope returns a graph view containing roots plus dependencies whose scope matches the requested filter, per MatchesScopeFilter.
It discards the report; a caller that wants to tell a user how much of a runtime view was kept on absence calls FilterGraphByScopeWithReport.
func NewWithCapacity ¶
NewWithCapacity creates an empty graph sized for the expected node count.
func (*Graph) AddEdge ¶
AddEdge adds a dependency relationship fromID -> toID, meaning fromID depends on toID.
The edge's kind is derived from the two nodes, so a caller that knows nothing about EdgeKind still produces correctly typed edges. Use AddTypedEdge to state a kind the structure does not imply.
func (*Graph) AddNode ¶
AddNode inserts a node, rejecting a duplicate identity. Use InsertNode for fold-by-identity insertion.
func (*Graph) AddTypedEdge ¶
AddTypedEdge adds a relationship and states what it asserts. An unknown kind is derived from the nodes, which is what AddEdge passes.
Adding an edge that already exists merges the kinds rather than ignoring the second call, so a stated kind is never lost to an earlier unstated one.
func (*Graph) CollectPathsTo ¶
CollectPathsTo returns deterministic root-to-target paths.
func (*Graph) DependencyNode ¶
func (g *Graph) DependencyNode(id string) (*DependencyNode, bool)
DependencyNode returns the dependency node with the given ID, or false when the ID is absent or names a different kind.
func (*Graph) DependencyNodes ¶
func (g *Graph) DependencyNodes() []*DependencyNode
DependencyNodes returns all dependency nodes sorted by ID — the iteration surface for matching, enrichment, and diffing, which are dependency-only.
func (*Graph) Dependents ¶
Dependents returns direct dependents for a node, sorted by ID.
func (*Graph) DirectDependencies ¶
DirectDependencies returns direct dependencies for a node, sorted by ID.
func (*Graph) EdgeKindOf ¶
EdgeKindOf returns the kind recorded for an edge, or EdgeKindUnknown when there is no such edge.
func (*Graph) InsertNode ¶
InsertNode is fold-by-identity insertion (ADR-0041): a node whose identity already exists in the graph unions into the existing record and the survivor is returned. Identity is the node ID, and IDs are disjoint across kinds, so a fold always joins records of one kind. Dependency folds union scopes and origins, merge the relationship, and union locations by usage record — ADR-0037's (module root, declaration site), see mergeNodeLocations — where a matched record merges its per-site scopes and relationship instead of keeping whichever witness came first. They also fold registry-match eligibility toward eligible (any-witness: when exactly one witness is eligible, its source survives — withholding enrichment from a package a registry release genuinely uses would hide vulnerabilities). Module folds union locations by the same usage rule; manifest folds are no-ops beyond the identity match.
func (*Graph) ManifestNodes ¶
func (g *Graph) ManifestNodes() []*ManifestNode
ManifestNodes returns all manifest nodes sorted by ID.
func (*Graph) MarshalJSON ¶
MarshalJSON encodes a graph as a stable transport-friendly adjacency list.
Stable means byte-stable: nodes are written in ascending node-ID order and edges in ascending (fromId, toId) order, so two graphs with the same content encode to the same bytes whatever order their nodes were added in, and whether a node was removed and added back. The slot order the graph keeps internally reuses freed slots and the adjacency maps iterate in Go's randomized order, so walking either would put the insertion history into the payload -- which is what a digest over these bytes must not see.
func (*Graph) ModuleNodes ¶
func (g *Graph) ModuleNodes() []*ModuleNode
ModuleNodes returns all module nodes sorted by ID.
func (*Graph) PrettyString ¶
PrettyString returns a stable, human-readable adjacency list.
func (*Graph) PrettyTree ¶
PrettyTree returns an ASCII tree view of dependencies from graph roots.
func (*Graph) RemoveEdge ¶
RemoveEdge removes a dependency relationship and reports whether it existed.
func (*Graph) RemoveNode ¶
RemoveNode removes a node and all incident relationships.
func (*Graph) TopologicalSort ¶
TopologicalSort returns a topological ordering for the acyclic portion of the graph. If cycles remain, the returned slice contains the ordered prefix and ErrCycleDetected.
func (*Graph) UnmarshalJSON ¶
UnmarshalJSON decodes a graph from the plugin transport adjacency list. Nodes are reconstructed through the constructor gates (strict: an invalid dependency identity fails the decode) and inserted with fold-by-identity semantics, so a legacy payload whose distinct wire IDs mint one canonical identity folds instead of erroring. Edges follow the wire-ID → identity mapping; an edge that becomes a self-edge after folding is dropped — the fold made it meaningless.
func (*Graph) WalkDependencyNodes ¶
func (g *Graph) WalkDependencyNodes(fn func(*DependencyNode) bool)
WalkDependencyNodes iterates all live dependency nodes. Returning false from fn stops iteration.
func (*Graph) WalkEdges ¶
WalkEdges iterates all dependency relationships (from -> to). Returning false stops iteration.
func (*Graph) WalkNodes ¶
WalkNodes iterates all live nodes. Returning false from fn stops iteration.
func (*Graph) WalkTypedEdges ¶
WalkTypedEdges iterates every relationship with the kind it asserts. Returning false stops iteration.
Reconstruction sites must use this, or CopyEdgesInto which is built on it, rather than WalkEdges: rebuilding a graph from (from, to) pairs alone drops every kind, and TestGraphReconstructionPreservesEdgeKind fails when it does.
type GraphContainer ¶
type GraphContainer struct {
Entries []GraphEntry `json:"entries,omitempty"`
}
GraphContainer groups one or more manifest-scoped dependency graphs.
func SingleGraphContainer ¶
func SingleGraphContainer(g *Graph, manifest ManifestMetadata) *GraphContainer
SingleGraphContainer wraps a single graph entry.
func (*GraphContainer) ConsolidatedGraph ¶
func (c *GraphContainer) ConsolidatedGraph() (*Graph, error)
ConsolidatedGraph materializes a single graph view for the container.
func (*GraphContainer) Len ¶
func (c *GraphContainer) Len() int
Len returns the number of graph entries.
type GraphEntry ¶
type GraphEntry struct {
Graph *Graph `json:"graph,omitempty"`
Manifest ManifestMetadata `json:"manifest"`
Packages []*Package `json:"packages,omitempty"`
// Document carries the claims the source SBOM made about itself, when
// this entry came from one. It lives here rather than on the scan because
// an entry is what a document maps to: a scan that read three SBOMs read
// three sets of these, and collapsing them loses which claim came from
// where -- which is what a merged export links back to.
Document *DocumentAssertions `json:"document,omitempty"`
}
GraphEntry describes one manifest-scoped dependency graph. Detection-time package facts discovered alongside the graph (licenses, digests, copyright pulled from lockfiles) are carried in Packages for folding into the global package registry during consolidation.
type GraphNode ¶
type GraphNode interface {
// NodeID returns the node's published graph ID: its identity.
NodeID() string
// Kind returns which member of the union this node is.
Kind() NodeKind
// NodeLocations returns the file locations that witnessed this node.
NodeLocations() []PackageLocation
// NodeWarnings returns the constructor-recorded recoverable conditions.
NodeWarnings() []NodeWarning
// CloneNode returns a deep copy of the node.
CloneNode() GraphNode
// contains filtered or unexported methods
}
GraphNode is the sealed union of the three graph-node kinds. Only this package's ManifestNode, ModuleNode, and DependencyNode implement it: the unexported method seals the union, so a type switch over the three kinds is exhaustive. A node's published graph ID is its identity itself — canonical package URL for dependency nodes, kind-qualified canonical paths for module and manifest nodes — which makes IDs disjoint across kinds and identity comparison a string comparison on IDs.
type ImpactAnalysisJustification ¶ added in v0.14.0
type ImpactAnalysisJustification string
ImpactAnalysisJustification is the rationale of why the impact analysis state was asserted (CycloneDX `impactAnalysisJustification`).
func ParseImpactAnalysisJustification ¶ added in v0.14.0
func ParseImpactAnalysisJustification(value string) (ImpactAnalysisJustification, error)
ParseImpactAnalysisJustification returns the justification a value names, or an error when it is not one CycloneDX defines.
type ImpactAnalysisResponse ¶ added in v0.14.0
type ImpactAnalysisResponse string
ImpactAnalysisResponse is a response to the vulnerability by the manufacturer, supplier, or project responsible for the affected component or service (CycloneDX `impactAnalysisResponse`). More than one is allowed.
func ParseImpactAnalysisResponse ¶ added in v0.14.0
func ParseImpactAnalysisResponse(value string) (ImpactAnalysisResponse, error)
ParseImpactAnalysisResponse returns the response a value names, or an error when it is not one CycloneDX defines.
type ImpactAnalysisState ¶ added in v0.14.0
type ImpactAnalysisState string
ImpactAnalysisState declares the current state of an occurrence of a vulnerability, after automated or manual analysis (CycloneDX `impactAnalysisState`).
func ParseImpactAnalysisState ¶ added in v0.14.0
func ParseImpactAnalysisState(value string) (ImpactAnalysisState, error)
ParseImpactAnalysisState returns the state a value names, or an error when it is not one CycloneDX defines. Spelling is exact: the specification's values are lowercase tokens and a producer that wrote another word did not write this vocabulary.
type KnownExploited ¶
type KnownExploited struct {
CVE string `json:"cve,omitempty"`
VendorProject string `json:"vendor_project,omitempty"`
Product string `json:"product,omitempty"`
DateAdded string `json:"date_added,omitempty"`
RequiredAction string `json:"required_action,omitempty"`
DueDate string `json:"due_date,omitempty"`
KnownRansomwareCampaignUse string `json:"known_ransomware_campaign_use,omitempty"`
Notes string `json:"notes,omitempty"`
URLs []string `json:"urls,omitempty"`
CWEs []string `json:"cwes,omitempty"`
}
KnownExploited captures CISA KEV-style known exploitation metadata.
type Language ¶
type Language string
Language identifies the programming language used by a package or analyzed by a code analyzer. Languages are coarse-grained and ecosystem-agnostic; one PackageManager can carry multiple languages (e.g. Maven covers Java, Kotlin, Scala, and Groovy).
const ( LanguageUnknown Language = "" LanguageGo Language = "go" LanguageJavaScript Language = "javascript" LanguageTypeScript Language = "typescript" LanguagePython Language = "python" LanguageJava Language = "java" LanguageKotlin Language = "kotlin" LanguageScala Language = "scala" LanguageGroovy Language = "groovy" LanguageRuby Language = "ruby" LanguagePHP Language = "php" LanguageRust Language = "rust" LanguageCSharp Language = "csharp" LanguageFSharp Language = "fsharp" LanguageVB Language = "vb" LanguageSwift Language = "swift" LanguageObjC Language = "objective-c" LanguageDart Language = "dart" LanguageElixir Language = "elixir" LanguageErlang Language = "erlang" LanguageHaskell Language = "haskell" LanguageOCaml Language = "ocaml" LanguageLua Language = "lua" LanguageR Language = "r" LanguageC Language = "c" LanguageCPP Language = "cpp" )
func LanguageFromPackage ¶
LanguageFromPackage returns the most specific language for a package. It prefers the package's own Language field, then falls back to the primary language declared by the package's PackageManager (if recognizable), and finally returns LanguageUnknown.
func ParseLanguage ¶
ParseLanguage normalizes a string into a Language. Returns LanguageUnknown for unrecognized values; callers that need strict validation should compare the result against LanguageUnknown for non-empty input.
type LicenseType ¶
type LicenseType string
LicenseType identifies license provenance: who is making the claim. Both SBOM formats draw the same distinction -- SPDX as licenseDeclared versus licenseConcluded, CycloneDX 1.6 as the acknowledgement field -- and it matters to a reader, because a declared license is what the package says about itself while a concluded one is what an analysis decided after looking. Collapsing them, as a single-valued vocabulary does, publishes an opinion as if the package had stated it.
const ( // LicenseTypeDeclared is the license the package declares about itself: // a manifest field, a registry record, a lockfile entry. LicenseTypeDeclared LicenseType = "declared" // LicenseTypeConcluded is the license an analysis concluded, having // looked at more than the declaration -- a license file's text, a scan // result, a human review. It may contradict the declaration, which is a // fact worth publishing rather than a conflict to resolve. LicenseTypeConcluded LicenseType = "concluded" )
func ParseLicenseType ¶
func ParseLicenseType(value string) (LicenseType, error)
ParseLicenseType normalizes a license provenance value. An empty value is unknown provenance, which is legal; anything else unrecognized is an error, since a misspelled provenance would silently publish a conclusion as a declaration.
type LocatorKind ¶
type LocatorKind string
LocatorKind says what shape an external reference's locator has, and so which grammar validates it.
It exists because a locator is not always a URL. Both formats carry non-URL locators: Bomly itself emits package URLs and CPE values as SPDX external references, SPDX's package-manager references carry bare coordinates such as "org.apache.tomcat:tomcat:9.0.0.M4", and a persistent identifier is a Software Heritage or gitoid string. Validating every locator as a URL would discard most of them.
const ( // LocatorKindURL is a web location, held to URLFormReference. LocatorKindURL LocatorKind = "url" // LocatorKindPURL is a package URL, held to purlkit. LocatorKindPURL LocatorKind = "purl" // LocatorKindCPE22 is a CPE 2.2 URI ("cpe:/a:vendor:product"). LocatorKindCPE22 LocatorKind = "cpe22" // LocatorKindCPE23 is a CPE 2.3 formatted string // ("cpe:2.3:a:vendor:product:..."). // // The two bindings are separate kinds because the reference type names // one of them. Collapsing them into a single "cpe" kind let a cpe23Type // reference carry a 2.2 URI and vice versa, so an exporter would publish // a reference whose declared type contradicts its own locator. LocatorKindCPE23 LocatorKind = "cpe23" // LocatorKindIRI is CycloneDX's externalReference url field, which its // schema types as an IRI reference rather than a web URL. A BOM-Link // ("urn:cdx:<serial>/<version>") is a valid locator there, and ADR-0037 // relies on exactly that to link a merged document back to its sources -- // so holding this field to the web-URL gate would drop the reference the // merged-export design depends on. LocatorKindIRI LocatorKind = "iri" // LocatorKindIdentifier is the bounded free-form fallback: a token with // no whitespace or control characters and no grammar of its own. LocatorKindIdentifier LocatorKind = "identifier" )
func LocatorKindFor ¶
func LocatorKindFor(category ExternalReferenceCategory, referenceType string) LocatorKind
LocatorKindFor derives the locator shape from a reference's category and type. The pair is the input, never the category alone: an SPDX-only axis cannot decide the shape of a reference that arrived without one.
A reference with no category came from CycloneDX, whose schema types the field as an IRI reference, so its locator is a URL. A known category with an unrecognized type -- SPDX's OTHER, and any type the specification adds after this table was written -- takes the bounded identifier form, which accepts the most and asserts the least.
type ManifestKind ¶
type ManifestKind string
ManifestKind identifies the manifest family represented by one graph entry.
const ( // ManifestKindPackageLockJSON identifies npm package-lock.json manifests. ManifestKindPackageLockJSON ManifestKind = "package-lock.json" // ManifestKindNPMLockfile identifies generic npm lockfile manifests. ManifestKindNPMLockfile ManifestKind = "npm-lockfile" // ManifestKindPackageJSON identifies npm package.json manifests. ManifestKindPackageJSON ManifestKind = "package.json" // ManifestKindBunLock identifies Bun text lockfiles. ManifestKindBunLock ManifestKind = "bun.lock" // ManifestKindGoMod identifies Go module manifests. ManifestKindGoMod ManifestKind = "go.mod" // ManifestKindGoModule identifies normalized Go module manifests. ManifestKindGoModule ManifestKind = "go-module" // ManifestKindPomXML identifies Maven POM manifests. ManifestKindPomXML ManifestKind = "pom.xml" // ManifestKindRequirementsTXT identifies Python requirements manifests. ManifestKindRequirementsTXT ManifestKind = "requirements.txt" // ManifestKindSPDX identifies SPDX SBOM manifests. ManifestKindSPDX ManifestKind = "spdx" // ManifestKindSBOM identifies generic SBOM manifests. ManifestKindSBOM ManifestKind = "sbom" // ManifestKindGitHubSPDX identifies GitHub-produced SPDX SBOM manifests. ManifestKindGitHubSPDX ManifestKind = "github.spdx" // ManifestKindBomlySPDX identifies Bomly-produced SPDX SBOM manifests. ManifestKindBomlySPDX ManifestKind = "bomly.spdx" // ManifestKindGitHubActions identifies GitHub Actions manifests. ManifestKindGitHubActions ManifestKind = "github-actions" // ManifestKindGitHubActionsWorkflow identifies GitHub Actions workflow files. ManifestKindGitHubActionsWorkflow ManifestKind = "github-actions-workflow" // ManifestKindGitHubActionsAction identifies GitHub Actions action metadata files. ManifestKindGitHubActionsAction ManifestKind = "github-actions-action" )
type ManifestMetadata ¶
type ManifestMetadata struct {
Path string `json:"path,omitempty"`
Kind ManifestKind `json:"kind,omitempty"`
Resolution *ResolutionMetadata `json:"resolution,omitempty"`
}
ManifestMetadata describes the manifest or evidence file associated with one graph.
type ManifestNode ¶
type ManifestNode struct {
// Path is the canonical repository-relative path (identity).
Path string
// FileKind classifies the manifest file, reusing the ManifestMetadata
// vocabulary.
FileKind ManifestKind
// Metadata is the free-form escape hatch shared by all node kinds.
Metadata map[string]any
// contains filtered or unexported fields
}
ManifestNode is the structural file record of the union: a manifest, lockfile, or build script. Its identity is its canonical repository-relative path, its published ID is "manifest:" + path, and it is never matched or enriched. The per-entry ManifestMetadata on GraphEntry remains the authoritative manifest record; a manifest node is the graph's projection of it (detectorkit.ManifestNodeForEntry derives one), with the public constructor covering nested workspace manifests.
func NewManifestNode ¶
func NewManifestNode(manifestPath string, kind ManifestKind) (*ManifestNode, error)
NewManifestNode constructs a manifest node from a repository-relative path. The path passes CanonicalRepoPath; there is no other gate.
func (*ManifestNode) Clone ¶
func (n *ManifestNode) Clone() *ManifestNode
Clone returns a deep copy.
func (*ManifestNode) CloneNode ¶
func (n *ManifestNode) CloneNode() GraphNode
CloneNode implements GraphNode.
func (*ManifestNode) NodeID ¶
func (n *ManifestNode) NodeID() string
NodeID returns "manifest:" + the canonical path.
func (*ManifestNode) NodeLocations ¶
func (n *ManifestNode) NodeLocations() []PackageLocation
NodeLocations returns the manifest's own path as its single location.
func (*ManifestNode) NodeWarnings ¶
func (n *ManifestNode) NodeWarnings() []NodeWarning
NodeWarnings returns nil: manifest construction records no recoverable conditions.
type ModuleNode ¶
type ModuleNode struct {
Coordinates
// DeclaringManifestPath is the canonical repository-relative path of
// the manifest that declares this module — always part of the identity.
DeclaringManifestPath string
// Locations are the file locations that witnessed the module.
Locations []PackageLocation
// Metadata is the free-form escape hatch shared by all node kinds.
Metadata map[string]any
// contains filtered or unexported fields
}
ModuleNode is one of the scanned project's own artifacts: the root project and every workspace or reactor module. Ownership is the kind — it cannot be dropped by a fold or asserted by an imported document — and module nodes are never matched or enriched. Identity is the declaring manifest path beside the canonical package URL when one is derivable, or beside the module name otherwise: a recursive scan can discover two unrelated projects with identical coordinates, and the path keeps those roots apart.
func AsModuleNode ¶
func AsModuleNode(node GraphNode) (*ModuleNode, bool)
AsModuleNode narrows a node to a module node, reporting whether it is one.
func NewModuleNode ¶
func NewModuleNode(declaringManifestPath string, coords Coordinates) (*ModuleNode, error)
NewModuleNode constructs a module node. The declaring manifest path passes CanonicalRepoPath and always participates in identity. The coordinates are normalized, and a canonical package URL is derived when they allow one — under the same missing-version warning policy as dependency nodes — otherwise the module is identified by path and name, and the name is then required.
func (*ModuleNode) CloneNode ¶
func (n *ModuleNode) CloneNode() GraphNode
CloneNode implements GraphNode.
func (*ModuleNode) NodeID ¶
func (n *ModuleNode) NodeID() string
NodeID returns "module:" + path + "#" + (canonical PURL | name).
func (*ModuleNode) NodeLocations ¶
func (n *ModuleNode) NodeLocations() []PackageLocation
NodeLocations returns the module's witnessed locations.
func (*ModuleNode) NodeWarnings ¶
func (n *ModuleNode) NodeWarnings() []NodeWarning
NodeWarnings returns the constructor-recorded recoverable conditions.
func (*ModuleNode) PURL ¶
func (n *ModuleNode) PURL() string
PURL returns the module's canonical package URL, or "" when none was derivable.
type NPMPackageMetadata ¶
type NPMPackageMetadata struct {
Bundled bool `json:"bundled,omitempty"`
Extraneous bool `json:"extraneous,omitempty"`
HasInstallScript bool `json:"hasInstallScript,omitempty"`
PeerDependencies map[string]string `json:"peerDependencies,omitempty"`
OptionalPeerDependencies []string `json:"optionalPeerDependencies,omitempty"`
Engines map[string]string `json:"engines,omitempty"`
}
NPMPackageMetadata holds npm-specific package data extracted from npm/pnpm/yarn lockfiles that does not fit into the cross-ecosystem fields.
type NodeKind ¶
type NodeKind string
NodeKind discriminates the sealed graph-node union (ADR-0041 in bomly-cli's dev-docs/adr). Exactly three kinds exist in protocol v1; a future kind means a v2 negotiation, so ParseNodeKind rejects anything else rather than guessing.
const ( // NodeKindManifest is a structural file record: a package.json, a // lockfile, a build script. Identified by its path, never matched or // enriched. NodeKindManifest NodeKind = "manifest" // NodeKindModule is one of the scanned project's own artifacts: the // root project itself and every workspace or reactor module. // First-party ownership is the kind, not a flag. NodeKindModule NodeKind = "module" // NodeKindDependency is one resolved third-party package — the unit of // matching and enrichment. Its identity is its canonical package URL. NodeKindDependency NodeKind = "dependency" )
func ParseNodeKind ¶
ParseNodeKind validates a wire-supplied kind value. An unrecognized kind is an error, never a guess: a v1 payload can only carry v1 kinds.
type NodeWarning ¶
type NodeWarning struct {
Code NodeWarningCode
Message string
}
NodeWarning is a recoverable, constructor-recorded observation about a node. Warnings are in-process state: they are re-derived wherever the node is reconstructed (the wire decoder runs the same constructor gates), so they never need to travel.
type NodeWarningCode ¶
type NodeWarningCode string
NodeWarningCode identifies a recoverable condition a node constructor recorded instead of failing.
const ( // NodeWarningMissingVersion marks a node whose package URL carries no // version. The purl specification leaves version optional, so absence is // visible rather than fatal. NodeWarningMissingVersion NodeWarningCode = "missing-version" // NodeWarningDroppedEvidenceQualifier marks a URL-valued evidence // qualifier whose value did not survive the origin gates and was // discarded entirely — a signed or tokenized link is never sanitized // into something publishable. NodeWarningDroppedEvidenceQualifier NodeWarningCode = "dropped-evidence-qualifier" // NodeWarningGenericIdentity marks a node whose ecosystem's own package // URL type could not express its coordinates, so its identity was minted // as pkg:generic instead. // // The alternative was refusing the node, which is worse: the package was // installed, it is in the artifact, and an inventory that omits it is // wrong in a way a loosely typed identity is not. The warning is how a // consumer can tell the difference -- the ecosystem stays on the // coordinates either way, so nothing but the identity's type degrades. NodeWarningGenericIdentity NodeWarningCode = "generic-identity" )
type Package ¶
type Package struct {
Coordinates
// Assertions are the component-level claims sources made about the
// package, seeded from the dependency node that matched it and enriched
// by matchers. See Assertions for the gates and merge classes.
Assertions
// ID is the package registry identifier. It may be a database ID, PURL, or
// another stable key chosen by the package registry.
ID string `json:"id,omitempty"`
// ResolvedURL is detection-time evidence carried onto the registry package
// for matchers (repository resolution reads it). It is raw and never
// published; the dependency's validated Origin stays on the graph node.
ResolvedURL string `json:"resolved_url,omitempty"`
// DetectedOrigins carries the graph node's vetted ADR-0033 origins onto
// the seeded registry package, so matchers that resolved repositories
// from the (now identity-stripped) URL-valued purl qualifiers receive
// the relocated signal. Additive and optional; every element passes the
// origin codecs' validation. Merge class: union by normalized value.
DetectedOrigins []DependencyOrigin `json:"detected_origins,omitempty"`
Vulnerabilities []Vulnerability `json:"vulnerabilities,omitempty"`
Attestations []PackageAttestation `json:"attestations,omitempty"`
Scorecard *PackageScorecard `json:"scorecard,omitempty"`
EOL *PackageEOL `json:"eol,omitempty"`
Remediation *PackageRemediation `json:"remediation,omitempty"`
// Matched indicates that this package was successfully matched by one or
// more external enrichment sources.
Matched bool `json:"matched,omitempty"`
// Metadata holds per-ecosystem extensible data.
Metadata map[string]any `json:"metadata,omitempty"`
}
Package describes one matching artifact: the PURL-keyed, deduplicated record produced by the matching stage. Many Dependency nodes (across manifests and subprojects) reference a single Package by PURL. A Package holds only matching-stage enrichment; detection-time identity and relationships live on Dependency.
func PackageFromDependencyNode ¶
func PackageFromDependencyNode(dep *DependencyNode) *Package
PackageFromDependencyNode seeds a registry package from a dependency node's identity. The node's ID is its canonical package URL, so the package is keyed on it directly. The returned package carries no enrichment; matchers fill it in. DetectedOrigins projects the node's vetted origins onto the package, so matchers that used to read the URL-valued purl qualifiers (Scorecard's repository resolution) receive the relocated signal.
func (*Package) DisplayName ¶
DisplayName returns the most human-friendly identifier available, using the ecosystem-native name form (e.g. "@org/name" for npm).
func (*Package) IdentityKey ¶
IdentityKey returns a stable package identity without version information.
func (*Package) LicenseValues ¶
LicenseValues returns normalized package license labels in stable order.
func (Package) MarshalJSON ¶
MarshalJSON re-gates on the way out. The receiver is a value, so normalization applies to this copy and never rewrites the record its holder still owns.
func (*Package) MergeFrom ¶
MergeFrom folds enrichment from src into p in place. Used by the package registry to deduplicate multiple records for the same PURL. Existing typed data on p wins; src contributes anything p is missing, and vulnerability lists are unioned by (Source, ID).
func (*Package) NormalizeAssertions ¶
func (p *Package) NormalizeAssertions()
NormalizeAssertions re-runs the publication gate on every field of p that carries untrusted input, in place. Values that cannot be published are cleared rather than corrected, following the codecs on DependencyOrigin and Contact.
Package has no JSON codec of its own -- it is a large struct decoded by the standard rules, and matcher package updates cross the plugin wire as plain values -- so there is no unmarshal hook to hang these rules on. This method is that hook, and PackageRegistry.Add calls it, which is the one door every package goes through on its way into the registry.
func (*Package) QualifiedName ¶
QualifiedName returns the package name prefixed with its organization when present.
func (*Package) UnmarshalJSON ¶
UnmarshalJSON applies the package rule as a value arrives, and MarshalJSON applies it again on the way out.
The codec lives on the type because the registry is not the only path a package takes. A matcher or analyzer returns PackageUpdates on its result, which the plugin transport serializes directly -- never through PackageRegistry -- so a gate that lived only at the registry let a credential-bearing homepage cross the wire, and let contacts and digests the model had already rejected encode as empty "{}" objects.
type PackageAttestation ¶
type PackageAttestation struct {
// PredicateType identifies what the statement asserts, using the in-toto
// predicate vocabulary (for example "https://slsa.dev/provenance/v1").
PredicateType string `json:"predicate_type,omitempty"`
// Source names the component or service that attached the statement, in
// the same style as PackageScorecard.Source.
Source string `json:"source,omitempty"`
// URL is where the statement can be fetched.
URL string `json:"url,omitempty"`
// Digest identifies the statement itself, so two fetches of one URL can be
// told apart.
Digest *Digest `json:"digest,omitempty"`
// Issuer is the identity that signed the statement -- an OIDC identity, a
// key id, or a registry account -- as reported by whatever verified it.
Issuer string `json:"issuer,omitempty"`
// Verified records that the component attaching this statement checked its
// signature. False means the statement was found but not verified, which is
// weaker evidence rather than evidence of tampering; consumers must not
// present an unverified statement as proof of provenance.
Verified bool `json:"verified,omitempty"`
}
PackageAttestation records a signed statement about how a package was built or published: an in-toto statement such as SLSA provenance, or a publish-time signature.
Bomly does not fetch or verify attestations today. The type exists so a matcher that does can attach what it found without a model change, and so consumers can tell a verified statement from one that was merely present -- a distinction that matters more than the statement itself, and that is easily lost when provenance data is carried in untyped metadata.
func (PackageAttestation) Clone ¶
func (a PackageAttestation) Clone() PackageAttestation
Clone returns a deep copy.
type PackageEOL ¶
type PackageEOL struct {
Source string `json:"source,omitempty"`
Cycle string `json:"cycle,omitempty"`
EOL bool `json:"eol,omitempty"`
EOLDate string `json:"eol_date,omitempty"`
LatestVersion string `json:"latest_version,omitempty"`
ReleaseDate string `json:"release_date,omitempty"`
Supported bool `json:"supported,omitempty"`
}
PackageEOL captures end-of-life enrichment attached by the EOL matcher.
func (*PackageEOL) Clone ¶
func (e *PackageEOL) Clone() *PackageEOL
Clone returns a deep copy of the EOL payload.
type PackageLicense ¶
type PackageLicense struct {
// Value is the license as the source stated it, unmodified.
Value string `json:"value,omitempty"`
// SPDXExpression is the validated SPDX expression form, when the value
// has one. For a license that is not on the SPDX list, this is a minted
// LicenseRef-* identifier whose text is carried in ExtractedText.
SPDXExpression string `json:"spdx_expression,omitempty"`
// Type is what kind of claim this is: declared by the package, or
// concluded by an analysis. See LicenseType.
Type LicenseType `json:"type,omitempty"`
// Source names the component that supplied the claim -- a matcher name
// such as "external-depsdev". It answers "who says so", which Type does
// not: Type is a closed two-member vocabulary about the kind of claim,
// and the two questions are independent. A deps.dev license is declared
// *and* sourced from deps.dev.
//
// They were briefly the same field, which is how this one came to exist.
// matcherkit.NormalizeLicenseSet wrote its matcher name into Type, so
// once Type became a closed vocabulary the gate dropped the value --
// silently emptying the "licenses[].source" field the CLI documents and
// publishes. Two independent facts sharing one field is what made that
// possible.
//
// Gate: PackageLicense.Normalized -- held to the component-name rule,
// not a token rule. A component descriptor requires only a non-blank
// name, so "My Matcher" and a name over 64 bytes are both valid
// components; gating this as a single short token would silently erase
// the source of a legitimately named matcher. What is enforced is what
// publication actually needs: valid UTF-8, no control characters, and a
// bound.
// Merge class: scalar, fill-gaps *within* a claim. Source is deliberately
// not part of the merge identity -- two matchers reporting one license
// stay one claim -- so the witness that carries a source supplies it to
// the one that does not, whichever arrived first.
Source string `json:"source,omitempty"`
// Name is the human-readable license name for a LicenseRef-* identifier.
// SPDX's hasExtractedLicensingInfos carries one, and a reader given only
// "LicenseRef-bomly-3f2a..." has nothing to go on.
//
// Gate: PackageLicense.Normalized (trimmed; cleared with the expression
// when a reference cannot be published). Merge class: scalar, fill-gaps
// *within* a claim -- Name is deliberately not part of the merge
// identity, so two records naming one license stay one claim and the
// witness that carries a name supplies it to the one that does not.
Name string `json:"name,omitempty"`
// ExtractedText is the original license text a LicenseRef-* identifier
// names. Both formats require the text to accompany the reference -- an
// SPDX document whose expression cites a LicenseRef without a matching
// hasExtractedLicensingInfos entry is invalid -- so the pair travels
// together on one record rather than in a side table that a merge or a
// projection could separate it from (bomly-cli issue #410).
//
// The text is authoritative and the reference is derived from it, per
// spdxkit.MintLicenseRef. Normalized re-mints rather than trusting a
// reference that disagrees with its text.
//
// Gate: PackageLicense.Normalized -- bounded, and blank text is cleared
// (it would otherwise mint the reference empty text mints, so every
// package with a blank license file would share one citation).
//
// Merge class: set member, and part of the merge identity -- by what the
// text mints rather than by its bytes, since whitespace-only differences
// name one license. Two claims whose texts genuinely differ are both
// kept, and if they arrived under one reference the later is re-minted so
// the set never leaves one identifier naming two licenses.
ExtractedText string `json:"extracted_text,omitempty"`
}
PackageLicense captures normalized license details for a package.
func DetectionLicenses ¶
func DetectionLicenses(dep *DependencyNode) []PackageLicense
DetectionLicenses returns the license facts recorded on dep at detection time: the typed field unioned with anything a producer left under the deprecated MetadataKeyDetectionLicenses stash.
Both are read because the stash outlives this release. A node decoded from an older producer's payload, or built by a component still pinned to an earlier SDK, carries its licenses only in metadata, and a consumer that looked at the typed field alone would silently see a package with no licenses at all.
func MergeLicenses ¶
func MergeLicenses(existing, additions []PackageLicense) []PackageLicense
MergeLicenses unions license claims, keeping the first record of each distinct claim. Licenses are a set: a package whose declaration and whose concluded analysis disagree carries both, and two sources that saw the same declaration contribute one entry.
func (PackageLicense) MarshalJSON ¶
func (l PackageLicense) MarshalJSON() ([]byte, error)
MarshalJSON applies the same rule on the way out.
func (PackageLicense) Normalized ¶
func (l PackageLicense) Normalized() (PackageLicense, bool)
Normalized returns the license with its claim re-checked, or false when the record says nothing publishable. It is the gate for a license that arrived from a plugin, an ingested document, or a hand-built value.
Three rules are enforced. An unrecognized provenance is dropped to unknown rather than published as a claim nobody made. A LicenseRef-* expression is re-minted from its text, since spdxkit makes the text authoritative: a reference that disagrees with the text it names would produce a document whose citation resolves to the wrong license. And every other expression is put to spdxkit -- the single home for SPDX expression semantics (ADR-0038) -- rather than trusted because it merely lacks a reference prefix.
The expression that survives is the canonical one. spdxkit rewrites deprecated identifiers, so "GPL-2.0" is stored as "GPL-2.0-only": Value keeps what the source said, while SPDXExpression is the form Bomly is willing to publish. Anything the parser rejects is dropped rather than exported into a document that would then fail its own validator.
func (*PackageLicense) UnmarshalJSON ¶
func (l *PackageLicense) UnmarshalJSON(data []byte) error
UnmarshalJSON applies the license rule as a value arrives, so a claim that would be rejected on read cannot be stored, forwarded, or written back out. A record that says nothing publishable decodes to the zero value, following DependencyOrigin.
type PackageLocation ¶
type PackageLocation struct {
RealPath string `json:"real_path,omitempty"`
AccessPath string `json:"access_path,omitempty"`
// Position optionally points at the exact line / column in RealPath where
// the package is declared. nil when unknown.
Position *SourcePosition `json:"position,omitempty"`
// ModuleRoot is the module whose resolution produced this site: a
// workspace member's directory, a Go main module, a Maven reactor
// project. Empty when the producer did not attribute it.
//
// It is what makes the fields below answerable. "Is this package a direct
// runtime dependency?" has no single answer for a workspace -- it can be
// direct-in-development in one module and transitive-at-runtime in
// another -- and a question with two answers can only be asked per module
// root.
ModuleRoot string `json:"module_root,omitempty"`
// Scopes are the scopes this particular site was reached under, as
// opposed to the union across every site, which is what the node carries.
Scopes []Scope `json:"scopes,omitempty"`
// Relationship is whether this site was declared directly by its module
// root or reached through another dependency. Same reasoning as Scopes:
// the node-level value is a union and cannot distinguish the sites.
Relationship DependencyRelationship `json:"relationship,omitempty"`
}
PackageLocation captures where a package was discovered.
func CanonicalLocations ¶ added in v0.14.0
func CanonicalLocations(locations []PackageLocation) []PackageLocation
CanonicalLocations returns a dependency's locations in their canonical form: folded by usage record the way a graph folds a second witness's (mergeNodeLocations), each record's scopes held to the same fold rule, and the records sorted by what names a usage -- real path, access path, module root, position. Two graphs that visited the same sites in a different order then publish the same list, which is what a byte-stable encoding of a node needs. The input is not modified; nil for none.
type PackageManager ¶
type PackageManager string
PackageManager identifies the concrete package manager or manifest family for a target. The type is string-backed so plugins can pass custom values while Bomly grows first-class constants; use PackageManagerOther when no specific manager value is appropriate.
const ( PackageManagerUnknown PackageManager = "" PackageManagerNPM PackageManager = "npm" PackageManagerPNPM PackageManager = "pnpm" PackageManagerYarn PackageManager = "yarn" PackageManagerBun PackageManager = "bun" PackageManagerGradle PackageManager = "gradle" PackageManagerMaven PackageManager = "maven" PackageManagerGoMod PackageManager = "gomod" PackageManagerPip PackageManager = "pip" PackageManagerPipenv PackageManager = "pipenv" PackageManagerPoetry PackageManager = "poetry" PackageManagerUV PackageManager = "uv" PackageManagerALPM PackageManager = "alpm" PackageManagerAPK PackageManager = "apk" PackageManagerConan PackageManager = "conan" PackageManagerConda PackageManager = "conda" PackageManagerPub PackageManager = "pub" PackageManagerDPKG PackageManager = "dpkg" PackageManagerMix PackageManager = "mix" PackageManagerRebar PackageManager = "rebar" PackageManagerOTP PackageManager = "otp" PackageManagerGitHubActions PackageManager = "github-actions" PackageManagerCabal PackageManager = "cabal" PackageManagerStack PackageManager = "stack" PackageManagerHomebrew PackageManager = "homebrew" PackageManagerLuaRocks PackageManager = "luarocks" PackageManagerNuGet PackageManager = "nuget" PackageManagerNix PackageManager = "nix" PackageManagerOpam PackageManager = "opam" PackageManagerComposer PackageManager = "composer" PackageManagerPear PackageManager = "pear" PackageManagerPDM PackageManager = "pdm" PackageManagerPortage PackageManager = "portage" PackageManagerSWIPLPack PackageManager = "swipl-pack" PackageManagerRPackage PackageManager = "r-package" PackageManagerRPM PackageManager = "rpm" PackageManagerBundler PackageManager = "bundler" PackageManagerGemspec PackageManager = "gemspec" PackageManagerCargo PackageManager = "cargo" PackageManagerSBOM PackageManager = "sbom" PackageManagerSnap PackageManager = "snap" PackageManagerCocoaPods PackageManager = "cocoapods" PackageManagerSwiftPM PackageManager = "swiftpm" PackageManagerTerraform PackageManager = "terraform" PackageManagerWordPress PackageManager = "wordpress" PackageManagerSetupPy PackageManager = "setuppy" PackageManagerOther PackageManager = "other" PackageManagerSBT PackageManager = "sbt" PackageManagerMultiple PackageManager = "multiple" )
func AllPackageManagers ¶
func AllPackageManagers() []PackageManager
AllPackageManagers returns the canonical package-manager list in SDK order.
func ParsePackageManager ¶
func ParsePackageManager(value string) (PackageManager, error)
ParsePackageManager normalizes a package-manager value.
func (PackageManager) Ecosystem ¶
func (p PackageManager) Ecosystem() Ecosystem
Ecosystem returns the higher-level grouping for a package manager.
func (PackageManager) Languages ¶
func (p PackageManager) Languages() []Language
Languages returns the programming languages typically built with this package manager. The first entry is the most common / canonical language; callers that need a single value should take Languages()[0]. Returns nil for OS-level managers and any manager that does not have a meaningful language association.
func (PackageManager) MarshalJSON ¶
func (p PackageManager) MarshalJSON() ([]byte, error)
MarshalJSON encodes a package manager by its canonical name.
func (PackageManager) Name ¶
func (p PackageManager) Name() string
Name returns the canonical package-manager name.
func (PackageManager) String ¶
func (p PackageManager) String() string
String returns the canonical package-manager name.
func (*PackageManager) UnmarshalJSON ¶
func (p *PackageManager) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a package manager from its canonical name.
type PackageNodeIndex ¶
type PackageNodeIndex map[string][]*DependencyNode
PackageNodeIndex maps a package reference to the dependency nodes that resolved to it.
It is derived, never stored. The stored truth stays DependencyNode's PackageRef -- one pointer per node to the package it matched -- and the registry stays position-free, holding packages keyed by PURL and nothing about where they were found. Storing the reverse direction as well would give the same fact two homes that can disagree, and the one that goes stale is always the derived-looking one.
Build it when a question needs it and discard it: it is a view over a graph that is being mutated, not a record.
func IndexNodesByPackage ¶
func IndexNodesByPackage(g *Graph) PackageNodeIndex
IndexNodesByPackage builds the reverse index for a graph. Nodes with no package reference are omitted, and each entry is ordered by node ID so a caller iterating it gets a stable answer.
func (PackageNodeIndex) Nodes ¶
func (i PackageNodeIndex) Nodes(packageRef string) []*DependencyNode
Nodes returns the dependency nodes that resolved to a package reference, or nil when none did.
func (PackageNodeIndex) Usages ¶
func (i PackageNodeIndex) Usages(packageRef string, evidence []ReachabilityEvidence, filter UsageFilter) []Usage
Usages returns every usage of a package across the graph the index was built from, joined to reachability evidence and filtered.
This is the reverse index earning its place: a vulnerability names a package, and the question "is it reachable at runtime anywhere" is about the nodes that package resolved to. Without the index a caller walks the whole graph per vulnerability.
type PackageRegistry ¶
type PackageRegistry struct {
// contains filtered or unexported fields
}
PackageRegistry is the PURL-keyed, deduplicated set of matching artifacts produced by the matching stage. Detection produces Dependency nodes that reference packages here by PURL; matchers enrich the packages once per PURL regardless of how many dependency instances point at them.
func ApplyPackageUpdates ¶
func ApplyPackageUpdates(registry *PackageRegistry, updates []*Package) *PackageRegistry
ApplyPackageUpdates merges package-update deltas returned by a matcher or analyzer (MatchResult.PackageUpdates / AnalyzeResult.PackageUpdates) into the registry. Each update is merged into any existing record with the same PURL via the registry's standard merge semantics; updates without a PURL are ignored. It returns the registry for convenience.
func NewPackageRegistry ¶
func NewPackageRegistry() *PackageRegistry
NewPackageRegistry creates an empty registry.
func (*PackageRegistry) Add ¶
func (r *PackageRegistry) Add(pkg *Package) *Package
Add inserts pkg, merging into any existing record with the same PURL, and returns the canonical stored package. Packages without a PURL are ignored.
func (*PackageRegistry) AddEntryPackages ¶ added in v0.14.0
func (r *PackageRegistry) AddEntryPackages(entries []GraphEntry)
AddEntryPackages folds the detection-time package facts carried on each graph entry -- licenses, digests and copyright read from a lockfile, the advisories and end-of-life records an ingested document asserted -- into the registry, through Add, so they take the same gates and merge classes as every other package. This is the one fold; a host that seeds its registry from graph nodes calls it afterwards so an entry's facts land on the packages those nodes seeded.
func (*PackageRegistry) All ¶
func (r *PackageRegistry) All() []*Package
All returns every package sorted by PURL.
func (*PackageRegistry) Ensure ¶
func (r *PackageRegistry) Ensure(purl string) *Package
Ensure returns the registry package for purl, creating an empty one when absent. Returns nil for an empty purl.
func (*PackageRegistry) Get ¶
func (r *PackageRegistry) Get(purl string) (*Package, bool)
Get returns the package for purl, if present.
func (*PackageRegistry) Len ¶
func (r *PackageRegistry) Len() int
Len returns the number of packages in the registry.
func (*PackageRegistry) MarshalJSON ¶
func (r *PackageRegistry) MarshalJSON() ([]byte, error)
MarshalJSON encodes a package registry as a stable PURL-keyed object for plugin transport.
func (*PackageRegistry) Merge ¶
func (r *PackageRegistry) Merge(other *PackageRegistry)
Merge folds every package from other into r.
func (*PackageRegistry) UnmarshalJSON ¶
func (r *PackageRegistry) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a PURL-keyed package registry from plugin transport.
type PackageRemediation ¶
type PackageRemediation struct {
Status PackageRemediationStatus `json:"status"`
RecommendedVersion string `json:"recommended_version,omitempty"`
Suggestions []PackageRemediationSuggestion `json:"suggestions,omitempty"`
}
PackageRemediation summarizes the fix evidence already present on a package's enriched vulnerabilities.
func (*PackageRemediation) Clone ¶
func (r *PackageRemediation) Clone() *PackageRemediation
Clone returns a copy of the package remediation summary.
type PackageRemediationStatus ¶
type PackageRemediationStatus string
PackageRemediationStatus describes how completely vulnerability enrichment identifies a safe package version.
const ( // PackageRemediationComplete means every vulnerability has usable fix // evidence and one recommended package version can address all of them. PackageRemediationComplete PackageRemediationStatus = "complete" // PackageRemediationPartial means fix evidence exists, but it cannot produce // one complete package recommendation. PackageRemediationPartial PackageRemediationStatus = "partial" // that no fix is available. PackageRemediationUnavailable PackageRemediationStatus = "unavailable" // PackageRemediationUnknown means fix evidence is missing or contradictory. PackageRemediationUnknown PackageRemediationStatus = "unknown" )
type PackageRemediationSuggestion ¶
type PackageRemediationSuggestion struct {
AffectedDependencyRefs []string `json:"affected_dependency_refs"`
SuggestedActionDependencyRef string `json:"suggested_action_dependency_ref,omitempty"`
ManifestPath string `json:"manifest_path,omitempty"`
Action RemediationAction `json:"action"`
OverrideAdvice string `json:"override_advice,omitempty"`
}
PackageRemediationSuggestion describes one occurrence-scoped action for the containing package. AffectedDependencyRefs identify occurrences of the vulnerable package. SuggestedActionDependencyRef identifies the direct dependency or manifest anchor the suggested action targets.
type PackageScorecard ¶
type PackageScorecard struct {
// Source identifies where the data came from (e.g. "api.scorecard.dev").
Source string `json:"source,omitempty"`
// Repository is the canonical repo identifier scored, e.g.
// "github.com/kubernetes/kubernetes".
Repository string `json:"repository,omitempty"`
// CommitSHA is the repo commit the run scored.
CommitSHA string `json:"commitSha,omitempty"`
// ScorecardVersion is the version of the Scorecard tool that produced
// the run.
ScorecardVersion string `json:"scorecardVersion,omitempty"`
// RunDate is when the run was performed.
RunDate time.Time `json:"runDate,omitempty"`
// AggregateScore is the overall Scorecard aggregate, 0.0–10.0.
// A negative value (typically -1) indicates "unscored".
AggregateScore float64 `json:"aggregateScore"`
// Checks holds per-check results in the order returned by Scorecard.
Checks []PackageScorecardCheck `json:"checks,omitempty"`
}
PackageScorecard holds the latest OpenSSF Scorecard run attached to a package by the scorecard matcher. A nil value means no run was attached (no resolvable source repo, the OSSF has not scored the project, or the matcher was not selected).
func (*PackageScorecard) Clone ¶
func (s *PackageScorecard) Clone() *PackageScorecard
Clone returns a deep copy of the scorecard payload, including its checks.
type PackageScorecardCheck ¶
type PackageScorecardCheck struct {
// Name is the Scorecard check name, e.g. "Branch-Protection".
Name string `json:"name"`
// Score is 0–10, or -1 when the check is inconclusive.
Score int `json:"score"`
// Reason is the short summary Scorecard emits for the check.
Reason string `json:"reason,omitempty"`
// Documentation links to the canonical documentation page for the check.
Documentation string `json:"documentation,omitempty"`
}
PackageScorecardCheck describes a single Scorecard check result.
type PackageType ¶
type PackageType string
PackageType describes the broad role or artifact kind of a package node.
const ( PackageTypeUnknown PackageType = "" PackageTypeApplication PackageType = "application" PackageTypePackage PackageType = "package" PackageTypeManifest PackageType = "manifest" PackageTypeWorkflow PackageType = "workflow" PackageTypeAction PackageType = "action" PackageTypeTransitive PackageType = "transitive" PackageTypeProject PackageType = "project" PackageTypeFile PackageType = "file" )
func ParsePackageType ¶
func ParsePackageType(value string) PackageType
ParsePackageType normalizes a package role string.
func (PackageType) String ¶
func (t PackageType) String() string
String returns the package type value.
type Path ¶
Path describes one path through the graph. Paths are heterogeneous: they traverse manifest and module nodes on their way to dependencies.
type RangeEvent ¶
type RangeEvent struct {
Introduced string `json:"introduced,omitempty"`
Fixed string `json:"fixed,omitempty"`
LastAffected string `json:"last_affected,omitempty"`
Limit string `json:"limit,omitempty"`
}
RangeEvent is one OSV range event marker.
type Reachability ¶
type Reachability struct {
Status ReachabilityStatus `json:"status"`
Tier ReachabilityTier `json:"tier,omitempty"`
Analyzer string `json:"analyzer,omitempty"`
Reason string `json:"reason,omitempty"`
Symbols []AffectedSymbol `json:"symbols,omitempty"`
CallPaths []CallPath `json:"call_paths,omitempty"`
Hops *int `json:"hops,omitempty"`
Confidence ReachabilityConfidence `json:"confidence,omitempty"`
DynamicImportsDetected bool `json:"dynamic_imports_detected,omitempty"`
AnalyzedAt string `json:"analyzed_at,omitempty"`
// Evidence is the per-module-root findings this annotation summarizes.
// Empty when the analyzer made a single whole-scan claim, which is what
// every analyzer emitted before the field existed -- so the annotation
// stays the record when there is no evidence, and becomes derived from it
// when there is. DeriveReachability builds the summary.
Evidence []ReachabilityEvidence `json:"evidence,omitempty"`
}
Reachability is the analyzer-supplied reachability annotation for one vulnerability. Stored on Vulnerability.
func DeriveReachability ¶
func DeriveReachability(evidence []ReachabilityEvidence) Reachability
DeriveReachability summarizes per-module-root evidence into the single annotation a vulnerability carries.
The rule is asymmetric on purpose, because the two answers are not equally safe to be wrong about. One module root reaching the symbol makes the finding reachable, whatever the others found: a real call path is not cancelled by an absence elsewhere. Unreachable requires every piece of evidence to say so, and at least one to exist -- anything less is unknown, not safe. This is the same caution the tier-3 caveat states in prose: "unreachable" is a claim about what was analyzed, not about the world.
The summary keeps the strongest reachable evidence's detail (tier, symbols, call paths, hops), since that is the finding a reader needs to act on.
func (*Reachability) Clone ¶
func (r *Reachability) Clone() *Reachability
Clone returns a deep copy of the reachability annotation.
type ReachabilityConfidence ¶
type ReachabilityConfidence string
ReachabilityConfidence is a coarse triage signal derived from Hops and DynamicImportsDetected.
const ( ConfidenceUnknown ReachabilityConfidence = "" ConfidenceHigh ReachabilityConfidence = "high" ConfidenceMedium ReachabilityConfidence = "medium" ConfidenceLow ReachabilityConfidence = "low" )
func DeriveConfidence ¶
func DeriveConfidence(hops *int, dynamicImports bool) ReachabilityConfidence
DeriveConfidence computes a confidence label from a hop count and a dynamic-imports flag. Returns ConfidenceUnknown when hops is nil.
type ReachabilityEvidence ¶
type ReachabilityEvidence struct {
// ModuleRoot is the module this finding is about. Empty means the
// analyzer did not attribute it, which is a whole-scan claim.
ModuleRoot string `json:"module_root,omitempty"`
// DependencyRefs optionally names the exact occurrence nodes the analyzer
// could attribute the finding to, by node ID. Empty means the analyzer
// could not narrow it below the module root, which is the common case --
// so a consumer must treat it as "not stated", never as "no occurrence".
DependencyRefs []string `json:"dependency_refs,omitempty"`
Status ReachabilityStatus `json:"status"`
Tier ReachabilityTier `json:"tier,omitempty"`
Analyzer string `json:"analyzer,omitempty"`
Reason string `json:"reason,omitempty"`
Symbols []AffectedSymbol `json:"symbols,omitempty"`
CallPaths []CallPath `json:"call_paths,omitempty"`
Hops *int `json:"hops,omitempty"`
Confidence ReachabilityConfidence `json:"confidence,omitempty"`
DynamicImportsDetected bool `json:"dynamic_imports_detected,omitempty"`
AnalyzedAt string `json:"analyzed_at,omitempty"`
}
ReachabilityEvidence is one analyzer's finding for one vulnerability within one module root.
Reachability is a per-module-root question for the same reason scope is: a vulnerable symbol can be called from one workspace member and unused by another, and one status for the whole scan cannot say so. Vulnerability's Reachability annotation becomes the derived summary over these.
func (ReachabilityEvidence) Clone ¶
func (e ReachabilityEvidence) Clone() ReachabilityEvidence
Clone returns a deep copy of the evidence.
type ReachabilityStatus ¶
type ReachabilityStatus string
ReachabilityStatus is the outcome of a reachability analysis for one vulnerability.
const ( ReachabilityUnknown ReachabilityStatus = "unknown" ReachabilityReachable ReachabilityStatus = "reachable" ReachabilityUnreachable ReachabilityStatus = "unreachable" )
type ReachabilityTier ¶
type ReachabilityTier string
ReachabilityTier communicates the precision of a reachability result.
const ( TierSymbol ReachabilityTier = "symbol" TierPackage ReachabilityTier = "package" TierNone ReachabilityTier = "none" )
type Reference ¶
type Reference struct {
URL string `json:"url,omitempty"`
Type ReferenceType `json:"type,omitempty"`
}
Reference is a URL and type pair.
type ReferenceType ¶
type ReferenceType string
ReferenceType identifies the role of a vulnerability reference URL.
const ( ReferenceTypeAdvisory ReferenceType = "advisory" ReferenceTypeDataSource ReferenceType = "data_source" )
type RemediationAction ¶
type RemediationAction string
RemediationAction identifies the user action suggested for one or more occurrences of an enriched vulnerable package.
const ( // RemediationActionDirectBump suggests updating a directly declared package. RemediationActionDirectBump RemediationAction = "direct-bump" // RemediationActionTransitiveOverride suggests using a package-manager // override for a transitive package. RemediationActionTransitiveOverride RemediationAction = "transitive-override" // RemediationActionLockfileRefresh suggests asking the package manager to // resolve a newer transitive package version. RemediationActionLockfileRefresh RemediationAction = "lockfile-refresh" // RemediationActionNoFixUpstream reports that every vulnerability explicitly // lacks an upstream fix. RemediationActionNoFixUpstream RemediationAction = "no-fix-upstream" // RemediationActionManualReview reports that available evidence cannot // support a safe, concrete automated suggestion. RemediationActionManualReview RemediationAction = "manual-review" )
type ResolutionFallback ¶
type ResolutionFallback struct {
From string `json:"from"`
Reason string `json:"reason,omitempty"`
}
ResolutionFallback identifies the primary detector that failed before a fallback detector produced the graph, and why it failed.
type ResolutionMetadata ¶
type ResolutionMetadata struct {
Method ResolutionMethod `json:"method,omitempty"`
InstallExecuted bool `json:"install_executed"`
InstallCommand []string `json:"install_command,omitempty"`
InstallWorkingDir string `json:"install_working_dir,omitempty"`
// Fallback records that a fallback detector produced this graph after the
// planned primary detector failed (not routine applicability hand-off).
Fallback *ResolutionFallback `json:"fallback,omitempty"`
}
ResolutionMetadata describes how a detector resolved a manifest graph.
type ResolutionMethod ¶
type ResolutionMethod string
ResolutionMethod identifies how a detector produced a manifest graph.
const ( // ResolutionMethodLockfile means the graph came from a deterministic lockfile parser. ResolutionMethodLockfile ResolutionMethod = "lockfile" // ResolutionMethodIsolatedInstall means Bomly installed dependencies into its own isolated environment. ResolutionMethodIsolatedInstall ResolutionMethod = "isolated-install" // ResolutionMethodProjectEnvironment means Bomly inspected an existing project-managed environment. ResolutionMethodProjectEnvironment ResolutionMethod = "project-environment" // ResolutionMethodManifestOnly means Bomly parsed a manifest without transitive install metadata. ResolutionMethodManifestOnly ResolutionMethod = "manifest-only" )
type RiskScore ¶
type RiskScore struct {
PackageRef string `json:"package_ref,omitempty"`
Score int `json:"score"`
Band RiskBand `json:"band,omitempty"`
Signals map[string]any `json:"signals,omitempty"`
}
RiskScore describes a normalized risk result for one package, referenced by its PURL in the package registry.
type RootAttribution ¶
type RootAttribution int
RootAttribution is how firmly a dependency node's declaration sites tie it to one module root.
Every reachability analyzer has to answer this before it emits evidence, because evidence is keyed by module root: a finding about a root the package is absent from is noise at best and, when it reads "unreachable", a claim about code that was never in that build -- one that survives into the summary, since DeriveReachability counts unreachable evidence.
The module root is the mandatory floor of an attribution and ReachabilityEvidence.DependencyRefs the optional ceiling. Naming whichever occurrence node an annotation loop happens to be visiting states a precision the analysis does not have: it pins an occurrence to a root nothing tied it to, which is a false claim rather than a vague one.
The rule reads SDK types (PackageLocation.ModuleRoot, PackageLocation.RealPath, DependencyNode.Locations) to produce inputs to another SDK type, so it lives here rather than once per analyzer. It arrived as four identical copies in the govulncheck, jsreach, pyreach and jvmreach analyzer repositories.
const ( // AttributedElsewhere: every site this node records names some other // module root. The node is not part of the root under analysis and // contributes no evidence to it. AttributedElsewhere RootAttribution = iota // AttributedToRootOnly: nothing ties the node to a particular root. The // analysis still covers it -- the analyzer ran over this root's build -- // so the evidence carries the module root, but no node reference, // because the occurrence was not established. AttributedToRootOnly // AttributedToSite: a site names this root, or lies under it. The // occurrence is established and the evidence may name the node. AttributedToSite )
func (RootAttribution) String ¶
func (a RootAttribution) String() string
String names the attribution, so a diagnostic reads as a claim rather than as an integer.
type RootAttributor ¶
type RootAttributor struct {
// contains filtered or unexported fields
}
RootAttributor answers the question above for one analysis pass over one set of module roots.
It is built per pass rather than per node because the honest answer depends on the whole run: a node whose sites declare module roots may only be judged "not in this root" when the producer's roots and the analyzer's roots are the same vocabulary. Detectors record the root they resolved from; an analyzer typically derives roots from the filesystem. When those two disagree -- a relative workspace path against an absolute module directory, say -- a non-match means the two are speaking past each other, not that the package is absent, and dropping the node's evidence on that basis would lose the finding entirely. So a non-match only means "not ours" once at least one declared root in the graph is a root this run analyzes.
The zero value knows no roots and trusts no declared one: it reports AttributedToSite for a node with a site under the root in hand and AttributedToRootOnly for everything else. That is the degraded answer, and it is the safe one -- it keeps evidence rather than dropping it.
func NewRootAttributor ¶
func NewRootAttributor(roots []string, graph *Graph) RootAttributor
NewRootAttributor calibrates attribution against the roots this run will analyze and the sites the graph actually records. A nil graph, or one whose sites declare no root this run analyzes, yields an attributor that will not read a declared-root mismatch as absence.
func (RootAttributor) Attribute ¶
func (a RootAttributor) Attribute(node *DependencyNode, root string) RootAttribution
Attribute reports how firmly node's sites tie it to root.
An empty root is the whole-scan claim -- ReachabilityEvidence with no module root applies to every location -- so no site can contradict it and it never answers AttributedElsewhere.
type Scope ¶
type Scope string
Scope describes the normalized dependency scope surfaced to users.
const ( // ScopeUnknown indicates that a detector could not determine dependency scope. ScopeUnknown Scope = "" // ScopeRuntime indicates a dependency required at runtime. ScopeRuntime Scope = "runtime" // ScopeDevelopment indicates a dependency used only for development workflows. ScopeDevelopment Scope = "development" )
func DecodeScopeSet ¶
DecodeScopeSet parses a carrier value written by EncodeScopeSet, strictly: an unrecognized token is an error, and nothing is returned beside it. It is the lenient reading with one more rule, for a caller that must know the value was written by a build that knows every token in it -- verifying a document Bomly itself wrote, for one. Ingest of a document from anywhere uses DecodeScopeSetLenient, because there the tokens an old build can read are still true and dropping them loses a scope the document stated.
The result is deduplicated and sorted, so decoding and re-encoding gives the same bytes.
func MergeScope ¶
MergeScope combines two normalized scopes, preferring runtime when a package is reachable from both runtime and development roots.
func ParseScope ¶
ParseScope normalizes a user-provided dependency scope value.
func ScopesFromCycloneDX ¶
ScopesFromCycloneDX derives a scope set from CycloneDX's scalar scope, for a document Bomly did not write. It returns nil for a value it cannot read: a scope spelled in a vocabulary that is not CycloneDX's is not a scope to guess at.
The mapping is the specification's reading of its own vocabulary, not a judgment call made here. CycloneDX states it normatively: "required" is "required for runtime"; an "optional" component is "not capable of being called due to [it] not being installed or otherwise accessible by any means", and one that is installed but merely prohibited from being called "must be scoped as 'required'"; "excluded" documents "test and other non-runtime purposes". So only "required" describes a component present in what runs, and both of the others describe one that is not -- which is what Bomly's development scope means to a filter.
This replaces an earlier reading in which "optional" landed on runtime because such a component "provides additional functionality" at runtime. That was the pre-1.6 gloss rather than what the specification says, and it was resolved against the specification in bomly-dev/bomly-sdk#63: a document Bomly did not write is read in the vocabulary of the format that defines it. The cost is real and was weighed -- a producer that spells an installed conditional dependency "optional" now has that component dropped by a runtime filter -- but a spelling that contradicts the specification is not evidence Bomly can act on, and acting on it would mean reading every conforming document wrongly to accommodate the ones that are not. Bomly's own documents never reach this mapping: CycloneDXScopeProperty carries their full scope set, and the scalar is read only when that carrier is absent.
An absent scope reads as runtime, for the same reason. The attribute is optional and most documents Bomly did not write omit it, and CycloneDX tells a consumer what to do with that: scope "SHOULD be assumed" to be "required" when it is not specified, which the schema restates as a "required" default. An absent attribute decodes to the empty string, so that -- and a value that is only space, which no conforming document writes -- is what "not specified" looks like here. Reading an unscoped component as unscoped instead dropped it from every runtime filter, which was a false negative on the majority of foreign documents rather than an edge case. The default lives in this mapping rather than at each ingest site for the reason the rest of it does: a second copy is how two readings come to disagree.
A value that is present but unreadable is not defaulted. "Not specified" and "spelled something this build cannot read" are different statements, and only the first is the one CycloneDX assigns a default to; the second has an unknown meaning, where answering "runtime" would put a claim in the graph that nothing in the document supports. Such a value still returns nil, and the caller decides what to do with a component whose scope it could not read.
func ScopesFromCycloneDXComponent ¶
ScopesFromCycloneDXComponent reads a component's scopes, preferring the carrier property over the scalar scope.
The precedence is the point of the pair. The carrier holds what Bomly recorded; the scalar holds a projection of it that cannot express a set. On a document Bomly wrote, both are present and only the carrier is exact. The carrier is read leniently: the scopes this build knows are kept even when a token beside them is not, since a newer Bomly's token is not a reason to discard the scopes an older one can still read. A carrier that is malformed outright, or names nothing this build knows, is treated as absent -- the scalar is still a true statement about the component, and dropping the scope entirely because the richer field was unreadable would lose more than it protects. A caller that wants to surface the unknown tokens reads the carrier with DecodeScopeSetLenient itself.
A component with neither -- no carrier and no scope attribute -- takes CycloneDX's default for an unspecified scope, which is runtime, since that is what falling through to the scalar reading means for an absent scalar.
type ScopeFilterReport ¶
type ScopeFilterReport struct {
// Unasserted are the IDs of the dependency nodes a runtime view kept
// because their scope set named nothing this build can read, sorted and
// deduplicated. Empty for every other view, and for a runtime view over
// a graph whose dependencies all stated a scope.
Unasserted []string
}
ScopeFilterReport says what a scope filter could not narrow. The SDK does not log, so the count reaches a user only if the caller reports it: a runtime view that kept most of the graph on absence has told the user far less than the flag implied, and silence there reads as a filtered result.
type ScopeSetDecoding ¶
type ScopeSetDecoding struct {
// Scopes are the recognized scopes, deduplicated and sorted, so
// re-encoding them gives stable bytes.
Scopes []Scope
// Unknown are the tokens this build does not recognize, lowercased the
// way ParseScope reads a token, in the order written, deduplicated.
// Empty when every token was read. Each has the shape of a scope token
// -- see isScopeTokenShaped -- because anything else is not a scope a
// newer build might have written; it is a malformed carrier, and that
// is an error rather than an entry here.
Unknown []string
}
ScopeSetDecoding is what a carrier value said, read leniently: the scopes it named that this build knows, and the tokens it named that it does not.
Unknown is the warning channel. The SDK does not log, and a token it cannot read is worth telling a user about -- it is most likely a scope a newer Bomly wrote -- so the caller gets the tokens and decides how to say so.
func DecodeScopeSetLenient ¶
func DecodeScopeSetLenient(value string) (ScopeSetDecoding, error)
DecodeScopeSetLenient reads a carrier value the way ADR-0037 states: the scopes it names that this build knows are kept, and the tokens it does not know are dropped and reported rather than failing the whole value.
The strict reading used to be the only one, and it was a forward compatibility trap: a newer Bomly writing one scope token an older one does not know made the older one lose the whole assertion, so a component the document scoped "runtime,future" became unscoped and a runtime filter dropped it. CycloneDX ingest could fall back to the scalar scope; SPDX has no scalar, so the loss there was total. The token an old build cannot read is still evidence -- it comes back in Unknown -- but the tokens it can read are still true, and those are kept.
What is still an error is a value that is not a carrier at all: over the byte bound, with an empty entry (a separator with nothing after it), or with an entry that is not shaped like a scope token at all -- a space, a control character, invalid UTF-8. A carrier is Bomly's own, and structure it would never write means the value did not come from where the caller thinks it did; treating such an entry as a future scope would let a malformed carrier override a valid scalar scope and surface garbage through the warning channel.
type Severity ¶
type Severity struct {
// Type is the OSV severity type, e.g. "CVSS_V3", "CVSS_V4".
Type SeverityType `json:"type,omitempty"`
// Score is the vector string or numeric score for Type.
Score string `json:"score,omitempty"`
}
Severity is one OSV-format severity entry (a CVSS type + vector/score).
type SeverityLevel ¶
type SeverityLevel string
SeverityLevel is Bomly's normalized severity band.
It carries two parallel vocabularies over one ordered scale, mirroring how GitHub presents code-scanning results:
- CVSS bands (critical/high/medium/low) are used for vulnerabilities, which also drive SARIF `security-severity`; GitHub renders them as Critical/High/Medium/Low.
- GitHub levels (error/warning/note) are used for findings that have no CVSS score (license, package); GitHub renders the SARIF `level` directly as Error/Warning/Note.
The two vocabularies share a single rank ladder (see SeverityRank): error ≡ high tier, warning ≡ medium tier, note ≡ low tier.
const ( // SeverityUnknown indicates that no severity could be determined. SeverityUnknown SeverityLevel = "unknown" // SeverityNA indicates that severity does not apply to the finding kind. // // Deprecated: kept for backward-compatible parsing only. New findings that // lack a CVSS score should use SeverityError/SeverityWarning/SeverityNote. SeverityNA SeverityLevel = "n/a" // SeverityLow indicates a low-severity issue. SeverityLow SeverityLevel = "low" // SeverityMedium indicates a medium-severity issue. SeverityMedium SeverityLevel = "medium" // SeverityHigh indicates a high-severity issue. SeverityHigh SeverityLevel = "high" // SeverityCritical indicates a critical-severity issue. SeverityCritical SeverityLevel = "critical" // SeverityAny is a policy threshold that matches every severity. SeverityAny SeverityLevel = "any" // SeverityNote is the GitHub-aligned level for low-impact findings without a // CVSS score. Ranks alongside SeverityLow. SeverityNote SeverityLevel = "note" // SeverityWarning is the GitHub-aligned level for findings without a CVSS // score that warrant attention. Ranks alongside SeverityMedium. SeverityWarning SeverityLevel = "warning" // SeverityError is the GitHub-aligned level for high-impact findings without // a CVSS score. Ranks alongside SeverityHigh. SeverityError SeverityLevel = "error" )
func ParseSeverityLevel ¶
func ParseSeverityLevel(value string) SeverityLevel
ParseSeverityLevel normalizes a severity string into a SeverityLevel.
type SeverityType ¶
type SeverityType string
SeverityType identifies the OSV severity vector family.
const ( SeverityTypeCVSSV2 SeverityType = "CVSS_V2" SeverityTypeCVSSV3 SeverityType = "CVSS_V3" SeverityTypeCVSSV31 SeverityType = "CVSS_V31" SeverityTypeCVSSV4 SeverityType = "CVSS_V4" )
type SourcePosition ¶
type SourcePosition struct {
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
EndLine int `json:"end_line,omitempty"`
}
SourcePosition is the canonical (file, line, column) tuple used wherever the SDK needs to point at a source location. Used by call frames, affected symbols, and (additively) by PackageLocation for declaration sites.
All fields are optional; consumers should treat zero/empty values as "unknown" rather than as positions at line 0 / column 0.
func (SourcePosition) IsZero ¶
func (p SourcePosition) IsZero() bool
IsZero reports whether the position carries no useful location data.
type SymbolKind ¶
type SymbolKind string
SymbolKind identifies a vulnerable or reachable code symbol kind.
const ( SymbolKindFunction SymbolKind = "function" SymbolKindMethod SymbolKind = "method" )
type URLForm ¶
type URLForm int
URLForm selects which published-URL rule a value is held to. Every form shares the same safety floor -- absolute http or https, a real host, no embedded credentials -- and differs only in what the location half of the URL is allowed to look like, because the three kinds of value answer different questions.
const ( // URLFormArtifact is the exact file a package was downloaded from. It // requires a non-empty path and rejects a query, which marks a signed or // tokenized link rather than a stable location. URLFormArtifact URLForm = iota // URLFormRepository is the source repository a package was resolved from. // It requires a non-empty path and drops the query, which carries the ref // that was requested rather than the one that was resolved. URLFormRepository // URLFormReference is a citation: a homepage, an advisory page, a // documentation link -- a URL published so a reader can follow it, never // one Bomly fetches to establish a fact. It keeps the query and the // fragment, and it permits a host root, because "https://example.com/" is // a legitimate homepage while it is never a package artifact. The safety // floor is unchanged: credentials, local paths, and non-http schemes are // rejected exactly as they are for the other two forms. URLFormReference )
type Usage ¶
type Usage struct {
// ModuleRoot is the module this usage belongs to.
ModuleRoot string
// Location is the site itself.
Location PackageLocation
// Evidence is the reachability finding for this module root, or nil when
// there is none.
Evidence *ReachabilityEvidence
}
Usage is one site of a package, with the reachability evidence that applies to it. It is what a conjunctive question is actually about.
func SelectUsages ¶
func SelectUsages(node *DependencyNode, evidence []ReachabilityEvidence, filter UsageFilter) []Usage
SelectUsages joins a node's locations to reachability evidence within each module root and returns the usages matching every condition in the filter.
This is the whole point of per-site attribution. Asking "reachable and runtime and direct" of a node's unions can answer yes when no single usage satisfies all three -- reachable in one module, runtime in another, direct in a third. Joining first and filtering after makes the answer a statement about a usage that exists.
Evidence with no module root applies to every location, since a whole-scan claim is a claim about all of them. A location with no module root is matched only by such evidence: an unattributed site cannot be joined to one module's finding without inventing the attribution the producer omitted.
type UsageFilter ¶
type UsageFilter struct {
// Scope, when set, requires the usage's site to match it under
// ScopeSetMatches -- so a runtime filter also keeps a site that asserted
// no scope, since absence is not a statement that the site is outside
// what ships. A site that has not migrated to per-site attribution
// carries no scopes at all, which is exactly that case.
Scope Scope
// Relationship, when set, requires the site to have it.
Relationship DependencyRelationship
// Reachable, when true, requires reachability evidence for the usage's
// module root that says reachable.
Reachable bool
}
UsageFilter is a conjunction of conditions about one usage of a package.
The zero value matches every usage. A condition left empty is not asked.
type VersionChange ¶
type VersionChange struct {
Before *DependencyNode
After *DependencyNode
}
VersionChange captures a dependency identity that changed versions.
type VersionRange ¶
type VersionRange struct {
// Type is the OSV range type: "SEMVER", "ECOSYSTEM", or "GIT".
Type VersionRangeType `json:"type,omitempty"`
Repo string `json:"repo,omitempty"`
Events []RangeEvent `json:"events,omitempty"`
}
VersionRange is one OSV affected version range.
type VersionRangeType ¶
type VersionRangeType string
VersionRangeType identifies the OSV affected range scheme.
const ( VersionRangeTypeSemver VersionRangeType = "SEMVER" VersionRangeTypeEcosystem VersionRangeType = "ECOSYSTEM" VersionRangeTypeGit VersionRangeType = "GIT" )
type Vulnerability ¶
type Vulnerability struct {
// --- OSV-aligned core ---
ID string `json:"id"`
Aliases []string `json:"aliases,omitempty"`
Related []string `json:"related,omitempty"`
Summary string `json:"summary,omitempty"`
Details string `json:"details,omitempty"`
Severity []Severity `json:"severity,omitempty"`
Affected []Affected `json:"affected,omitempty"`
References []Reference `json:"references,omitempty"`
Published string `json:"published,omitempty"`
Modified string `json:"modified,omitempty"`
Withdrawn string `json:"withdrawn,omitempty"`
DatabaseSpecific map[string]any `json:"database_specific,omitempty"`
// --- Bomly enrichment extensions ---
Source string `json:"source,omitempty"`
DataSource string `json:"data_source,omitempty"`
Namespace string `json:"namespace,omitempty"`
Title string `json:"title,omitempty"`
Reasons []string `json:"reasons,omitempty"`
ParsedSeverity SeverityLevel `json:"parsed_severity,omitempty"`
SeveritySource string `json:"severity_source,omitempty"`
CVSS []CVSSScore `json:"cvss,omitempty"`
EPSS []EPSSScore `json:"epss,omitempty"`
CWEs []CWE `json:"cwes,omitempty"`
KEVExploited bool `json:"kev_exploited,omitempty"`
KnownExploited []KnownExploited `json:"known_exploited,omitempty"`
RiskScore float64 `json:"risk_score,omitempty"`
FixState FixState `json:"fix_state,omitempty"`
FixedIn string `json:"fixed_in,omitempty"`
FixedVersions []string `json:"fixed_versions,omitempty"`
FixAvailable []FixAvailable `json:"fix_available,omitempty"`
AffectedVersionRange string `json:"affected_version_range,omitempty"`
CPEs []string `json:"cpes,omitempty"`
AffectedSymbols []AffectedSymbol `json:"affected_symbols,omitempty"`
Reachability *Reachability `json:"reachability,omitempty"`
// Analysis is the VEX impact analysis a source document attached to
// this advisory for this package: whether it is affected, why not, and
// what the responsible party intends to do. Preserved across ingest and
// re-export through CycloneDX; SPDX has no slot for it. Gate and merge
// class: see VulnerabilityAnalysis. Optional.
Analysis *VulnerabilityAnalysis `json:"analysis,omitempty"`
// Recommendation is the remediation guidance a source stated in its own
// words (CycloneDX `recommendation`), kept apart from the fixed versions
// an exporter can render advice from: a document that said "apply the
// vendor patch" named no version, and losing the sentence would lose
// the advice. Gate: NormalizeDescription, applied where a document is
// read and where a package merges. Merge class: scalar, fill-gaps.
Recommendation string `json:"recommendation,omitempty"`
}
Vulnerability describes a single advisory in an OSV-aligned shape, extended with Bomly-specific enrichment that the OSV schema does not model directly.
The leading block mirrors the OSV (Open Source Vulnerabilities) schema so the records can be exported as OSV with minimal translation. The trailing block carries Bomly enrichment (parsed severity, EPSS, KEV, CWE, risk, fix-state, reachability) attached by matchers and analyzers.
func (Vulnerability) Clone ¶
func (v Vulnerability) Clone() Vulnerability
Clone returns a deep copy of the vulnerability.
func (Vulnerability) IsExploitable ¶
func (v Vulnerability) IsExploitable() bool
IsExploitable reports whether advisory metadata says this vulnerability is known exploitable.
func (Vulnerability) MarshalJSON ¶ added in v0.14.5
func (v Vulnerability) MarshalJSON() ([]byte, error)
MarshalJSON writes the gated form. The receiver is a value and Normalized rebuilds every slice it touches, so encoding never edits the holder's vulnerability.
func (Vulnerability) MatchesConstraints ¶
func (v Vulnerability) MatchesConstraints(constraints []FailOnConstraint) bool
MatchesConstraints evaluates one vulnerability against the vulnerability constraints in an AND-set. Source-change constraints apply only to package findings and are ignored here. When constraints is empty, every vulnerability matches (the historical behavior of `--audit` without `--fail-on`). A list containing only non-vulnerability constraints also leaves vulnerability matching unchanged.
func (Vulnerability) Normalized ¶ added in v0.14.5
func (v Vulnerability) Normalized() Vulnerability
Normalized returns the vulnerability with its free text and reference URLs held to their gates. It is the gate the codec applies on both directions and Package.NormalizeAssertions applies at the registry's door, so a matcher's package update cannot carry an ungated value into a registry, a scan record, or a published document.
Gates: Summary, Title, Recommendation and each of Reasons take the description gate (trimmed, bounded, control characters other than line breaks and tabs dropped); Details takes the same rule under the longer advisory bound; a reference's URL passes NormalizeURL in its reference form -- net/url decides what a URL is -- and a reference whose URL cannot be published is dropped, since a reference is nothing but its URL. Values that fail are cleared rather than corrected. Slices are rebuilt, never edited in place, so the receiver's holder is unchanged.
func (*Vulnerability) UnmarshalJSON ¶ added in v0.14.5
func (v *Vulnerability) UnmarshalJSON(data []byte) error
UnmarshalJSON reads through the gate. The wire value starts from the receiver, as encoding/json's default decoding would, so a partial object applied to an existing vulnerability keeps the fields it does not name.
type VulnerabilityAnalysis ¶ added in v0.14.0
type VulnerabilityAnalysis struct {
State ImpactAnalysisState `json:"state,omitempty"`
Justification ImpactAnalysisJustification `json:"justification,omitempty"`
Response []ImpactAnalysisResponse `json:"response,omitempty"`
// Detail is the detailed description of the impact including methods
// used during assessment. If a vulnerability is not exploitable, this
// field should include specific details on why the component or service
// is not impacted by this vulnerability.
Detail string `json:"detail,omitempty"`
// FirstIssued is the date and time (timestamp) when the analysis was
// first issued, as the source stated it.
FirstIssued string `json:"first_issued,omitempty"`
// LastUpdated is the date and time (timestamp) when the analysis was
// last updated, as the source stated it.
LastUpdated string `json:"last_updated,omitempty"`
}
VulnerabilityAnalysis is an assessment of the impact and exploitability of a vulnerability for the package it is attached to: CycloneDX's `vulnerability.analysis`, the VEX block. It is what lets a document say that a listed advisory does not affect the package, and why.
Gate: Normalized, applied in the JSON codec on both directions the way DependencyOrigin's is, so a value a managed component or a decoded record supplies is held to it without a call site remembering to -- a state, justification or response that is not in the CycloneDX vocabulary is dropped rather than carried as a word the specification does not define; Detail takes the description gate; the two timestamps are kept verbatim when publishable, as a document's own timestamp is.
Merge class: the assessment -- State, Justification, Detail and the two timestamps -- is one claim and merges as one: a second witness fills its gaps only when it asserts the same state, and is set aside when it asserts another, so a merge never pairs one source's state with another's rationale. Response is a set, unioned. See MergeVulnerabilityAnalysis.
func MergeVulnerabilityAnalysis ¶ added in v0.14.0
func MergeVulnerabilityAnalysis(dst, src *VulnerabilityAnalysis) *VulnerabilityAnalysis
MergeVulnerabilityAnalysis folds src into dst under the declared merge classes. The assessment is one claim: when dst asserts no state, src's assessment stands whole; when both assert the same state, src fills the gaps dst left; when they assert different states, dst's assessment stands and src's is set aside, because a justification written for one state is not evidence for another. Responses are unioned regardless. Both sides are gated first, so a value that could not be published never blocks one that can. The result is a fresh value; nil when neither side carries anything publishable.
func (*VulnerabilityAnalysis) Clone ¶ added in v0.14.0
func (a *VulnerabilityAnalysis) Clone() *VulnerabilityAnalysis
Clone returns a deep copy; nil clones to nil.
func (VulnerabilityAnalysis) IsEmpty ¶ added in v0.14.0
func (a VulnerabilityAnalysis) IsEmpty() bool
IsEmpty reports whether the analysis carries nothing.
func (VulnerabilityAnalysis) MarshalJSON ¶ added in v0.14.0
func (a VulnerabilityAnalysis) MarshalJSON() ([]byte, error)
MarshalJSON writes the gated form, so an in-process value that never passed a codec is held to the same vocabulary as one that did.
func (VulnerabilityAnalysis) Normalized ¶ added in v0.14.0
func (a VulnerabilityAnalysis) Normalized() (VulnerabilityAnalysis, bool)
Normalized returns the analysis held to its gates, and reports whether anything publishable remains.
func (*VulnerabilityAnalysis) UnmarshalJSON ¶ added in v0.14.0
func (a *VulnerabilityAnalysis) UnmarshalJSON(data []byte) error
UnmarshalJSON reads through the gate: a value outside the vocabulary is dropped at the boundary rather than persisted until an export drops it.
Source Files
¶
- assertions.go
- attestation.go
- contact.go
- container.go
- coordinates.go
- dependency.go
- digest.go
- doc.go
- document.go
- ecosystem.go
- edge.go
- external_reference.go
- graph.go
- json.go
- language.go
- merge.go
- metadata.go
- node.go
- node_access.go
- normalization.go
- origin.go
- package.go
- package_manager.go
- policy.go
- purl.go
- registry.go
- relationship.go
- scope_cyclonedx.go
- scope_filter.go
- scorecard.go
- usage.go
- vulnerability.go
- vulnerability_analysis.go