graph

package
v0.0.1-rc.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package graph defines AgentShield's provider-neutral graph model and the pure compiler that turns plugin assertions into a canonical snapshot.

Pipeline position

Discovery plugins and the telemetry rollup emit an Input: resource, facet, relationship, and bounded telemetry assertions. Package state persists those assertions per contribution and calls Compiler twice: once to validate a candidate contribution (Compiler.CompileContribution) and once to materialize the union of all active contributions (Compiler.Compile). The resulting Snapshot feeds current-state projections, the graph API, and reasoning. This package performs no I/O and holds no contribution or generation state; ownership and replacement live in package state.

Identity

Every graph node is named by an IdentityClaim: a scheme (group, version, kind), an authority ID, and an immutable key. A Registry maps each IdentityScheme to a normalizer, and the compiler derives a UUIDv5 resource ID from the normalized tuple. Claims must be authority-qualified (a cluster UID or cloud account, not a plugin ID) and provider-immutable (an object UID or immutable resource name, not a display name, label, or IP address), so independent plugins converge on the same node and a recreated object gets a new one. Mutable values belong in attributes. NetworkDestination and NetworkPeerClass are built-in provider-neutral schemes preloaded by NewRegistry; plugins register only the authority-specific schemes they introduce.

Assertions and provenance

Every assertion carries PluginID, SourceID, RuleID, and EvidenceIDs. The compiler rejects assertions without a plugin, source, or rule, sorts and deduplicates evidence IDs, groups equal claims onto one record while keeping every contributing assertion, deduplicates identical assertions, and sorts all output. Two inputs containing the same assertion set therefore compile to byte-identical Snapshot.CanonicalJSON, regardless of slice order or duplication.

Relationships use only predicates registered in this package (see IsRegisteredPredicate); adding a predicate is a central change that must also update persistence constraints. A relationship or facet whose endpoint resource is not present is kept with ResolutionUnresolved so contributions can reference identities owned by other plugins without publication ordering. Conflicting kinds for one identity become an AssertionConflict rather than an error.

Security semantics

SecuritySemantics is a closed, versioned, provider-neutral envelope stored in a facet attribute or relationship property under SecuritySemanticsAttribute. The compiler validates every envelope present and requires canonical encoding; it does not enforce that one is present.

See https://agent-shield.dev/docs/concepts/data-model/ for the full model.

Index

Constants

View Source
const (
	ResourceAuthoringContextAttribute   = "agentshield/resource-authoring-context"
	ResourceAuthoringContextMaxBytes    = 40 << 10
	ResourceAuthoringAttributesMaxItems = 128
)
View Source
const (
	NetworkRoleControlPlaneAPI = "control-plane-api"
	NetworkRoleService         = "service"
	NetworkRoleWorkload        = "workload"
)

Values of the provider-neutral network/role resource attribute.

View Source
const (
	// SecuritySemanticsAttribute is the facet attribute or relationship
	// property key that carries the canonical SecuritySemantics JSON.
	SecuritySemanticsAttribute = "agentshield.io/security-semantics"
	// SecuritySemanticsV1 is the only supported envelope version.
	SecuritySemanticsV1 = "v1"
)
View Source
const ProcessClassShell = "shell"

ProcessClassShell is an interactive shell process.

Variables

This section is empty.

Functions

func EncodeSecuritySemantics

func EncodeSecuritySemantics(semantics SecuritySemantics) (string, error)

EncodeSecuritySemantics validates semantics and returns its canonical JSON: protocols are trimmed, uppercased, sorted, and deduplicated, and ports are sorted and deduplicated. Producers must bound native input first; oversized protocol or port lists are rejected rather than truncated.

func IsNetworkDestinationClaim

func IsNetworkDestinationClaim(claim IdentityClaim) bool

IsNetworkDestinationClaim reports whether claim uses the NetworkDestination scheme.

func IsNetworkPeerClassClaim

func IsNetworkPeerClassClaim(claim IdentityClaim) bool

IsNetworkPeerClassClaim reports whether claim uses the NetworkPeerClass scheme.

func IsProcessClassClaim

func IsProcessClassClaim(claim IdentityClaim) bool

IsProcessClassClaim reports whether claim uses the ProcessClass scheme.

func IsRegisteredPredicate

func IsRegisteredPredicate(predicate Predicate) bool

IsRegisteredPredicate reports whether predicate is in the central vocabulary.

func ResourceNetworkRoles

func ResourceNetworkRoles(snapshot Snapshot) map[string]string

ResourceNetworkRoles maps resource IDs to network/role, including network destinations whose address appears in another resource's network/addresses.

func WithSecuritySemantics

func WithSecuritySemantics(attributes map[string]string, semantics SecuritySemantics) (map[string]string, error)

WithSecuritySemantics returns a copy of attributes with the canonical encoding of semantics added under SecuritySemanticsAttribute. The input map is not modified.

Types

type AssertionConflict

type AssertionConflict struct {
	ResourceID string              `json:"resourceId"`
	Kinds      []string            `json:"kinds"`
	Assertions []ResourceAssertion `json:"assertions"`
}

AssertionConflict records an identity asserted with more than one kind. The identity is withheld from Snapshot.Resources so traversal never picks a kind arbitrarily; edges to it remain unresolved.

type Compiler

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

Compiler is the pure, deterministic graph materializer. It holds no state besides its registry and is safe for concurrent use once registration is complete.

func NewCompiler

func NewCompiler(registry *Registry) *Compiler

NewCompiler returns a compiler that resolves identities through registry.

func (*Compiler) Compile

func (c *Compiler) Compile(input Input) (Snapshot, error)

Compile materializes the complete active graph. Telemetry whose subject or object resource is absent is dropped, because telemetry rollups only attach to materialized inventory; unresolved facets and relationships are kept.

func (*Compiler) CompileContribution

func (c *Compiler) CompileContribution(input Input) (Snapshot, error)

CompileContribution validates and resolves assertions before persistence; endpoint presence is enforced later when all active contributions are composed.

func (*Compiler) NormalizeIdentityClaim

func (c *Compiler) NormalizeIdentityClaim(claim IdentityClaim) (IdentityClaim, error)

type Facet

type Facet struct {
	ID               string           `json:"id"`
	ResourceID       string           `json:"resourceId"`
	Kind             string           `json:"kind"`
	Key              string           `json:"key"`
	ResolutionStatus ResolutionStatus `json:"resolutionStatus,omitempty"`
	Assertions       []FacetAssertion `json:"assertions"`
}

Facet is a compiled facet. ID is derived from resource ID, kind, and key.

type FacetAssertion

type FacetAssertion struct {
	Resource    IdentityClaim     `json:"resource"`
	Kind        string            `json:"kind"`
	Key         string            `json:"key"`
	Attributes  map[string]string `json:"attributes,omitempty"`
	PluginID    string            `json:"pluginId"`
	SourceID    string            `json:"sourceId"`
	RuleID      string            `json:"ruleId"`
	EvidenceIDs []string          `json:"evidenceIds"`
}

FacetAssertion attaches one independently computed aspect, identified by Kind and Key, to the resource named by Resource. Facets let several plugins enrich the same node without sharing ownership of it.

type IdentityClaim

type IdentityClaim struct {
	Scheme       IdentityScheme `json:"scheme"`
	AuthorityID  string         `json:"authorityId"`
	ImmutableKey string         `json:"immutableKey"`
}

IdentityClaim names a resource within an authority-owned scheme. The compiler normalizes this tuple and derives the stable resource ID shared by assertions.

func NetworkDestinationClaim

func NetworkDestinationClaim(authorityID, immutableKey string) (IdentityClaim, error)

NetworkDestinationClaim builds a claim through the scheme's normalizer, so it matches what the compiler stores; it fails for an empty authority or key.

func NetworkPeerClassClaim

func NetworkPeerClassClaim(authorityID, immutableKey string) (IdentityClaim, error)

NetworkPeerClassClaim builds a claim through the scheme's normalizer; it fails for a key outside the closed peer-class vocabulary.

func ProcessClassClaim

func ProcessClassClaim(authorityID, immutableKey string) (IdentityClaim, error)

ProcessClassClaim returns a normalized ProcessClass claim, or an error for a class outside the core vocabulary.

type IdentityScheme

type IdentityScheme struct {
	Group   string `json:"group"`
	Version string `json:"version"`
	Kind    string `json:"kind"`
}

IdentityScheme names an identity authority contract in Kubernetes-style group/version/kind form. The group identifies the semantic authority, not the plugin that emits claims under it.

type Input

type Input struct {
	Resources     []ResourceAssertion
	Facets        []FacetAssertion
	Relationships []RelationshipAssertion
	Telemetry     []TelemetryAssertion
}

Input is an assertion set submitted to the compiler. Contribution ownership and replacement are handled by the publication layer around this pure model.

func Reverse

func Reverse(input Input) Input

Reverse returns a copy of input with every assertion slice reversed. Tests use it to prove that compiled output does not depend on input order.

type NetworkRoleDescription

type NetworkRoleDescription struct {
	Role        string
	Description string
}

NetworkRoleDescription pairs a network/role value with its meaning.

func NetworkRoles

func NetworkRoles() []NetworkRoleDescription

NetworkRoles lists the values providers may publish in the network/role attribute.

type Predicate

type Predicate string

Predicate is a directed relationship type. Only predicates in the central registry are accepted by the compiler; see IsRegisteredPredicate.

const (
	PredicateContains     Predicate = "contains"
	PredicateInstantiates Predicate = "instantiates"
	PredicateMemberOf     Predicate = "member-of"
	PredicateUsesIdentity Predicate = "uses-identity"
	PredicateExposes      Predicate = "exposes"
	PredicateGovernedBy   Predicate = "governed-by"
	PredicateCommunicates Predicate = "communicates-with"
	PredicateRunsOn       Predicate = "runs-on"
	PredicateBackedBy     Predicate = "backed-by"
	PredicateExecutes     Predicate = "executes"
)

Registered predicates. Adding one is a central change that also needs a new state migration widening the relationship predicate CHECK constraints.

type PredicateDescription

type PredicateDescription struct {
	Predicate   Predicate
	Description string
}

PredicateDescription pairs a registered predicate with a human-readable meaning. It feeds generated detector-rule documentation.

func RegisteredPredicateDescriptions

func RegisteredPredicateDescriptions() []PredicateDescription

RegisteredPredicateDescriptions returns every registered predicate sorted by name. Predicates without a description have an empty Description.

type ProcessClassDescription

type ProcessClassDescription struct {
	Class       string
	Description string
}

ProcessClassDescription pairs a core process class with its meaning. It feeds generated detector-rule documentation.

func ProcessClasses

func ProcessClasses() []ProcessClassDescription

ProcessClasses lists the core process-class vocabulary.

type Registry

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

Registry maps identity schemes to their normalizers. It is populated at startup before the Compiler is built and is not safe for concurrent registration.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns a registry preloaded with the built-in NetworkDestination and NetworkPeerClass schemes.

func (*Registry) Register

func (r *Registry) Register(definition SchemeDefinition) error

Register adds a scheme definition. Registering the same scheme twice is an error, so two plugins cannot both claim authority over one scheme.

type Relationship

type Relationship struct {
	ID               string                  `json:"id"`
	SubjectID        string                  `json:"subjectId"`
	Predicate        Predicate               `json:"predicate"`
	ObjectID         string                  `json:"objectId"`
	Qualifier        string                  `json:"qualifier,omitempty"`
	ResolutionStatus ResolutionStatus        `json:"resolutionStatus,omitempty"`
	Assertions       []RelationshipAssertion `json:"assertions"`
}

Relationship is a compiled edge. ID is derived from subject, predicate, object, and qualifier, so equal edges from different plugins share one record and keep separate assertions.

type RelationshipAssertion

type RelationshipAssertion struct {
	Subject     IdentityClaim     `json:"subject"`
	Predicate   Predicate         `json:"predicate"`
	Object      IdentityClaim     `json:"object"`
	Qualifier   string            `json:"qualifier,omitempty"`
	Properties  map[string]string `json:"properties,omitempty"`
	PluginID    string            `json:"pluginId"`
	SourceID    string            `json:"sourceId"`
	RuleID      string            `json:"ruleId"`
	EvidenceIDs []string          `json:"evidenceIds"`
}

RelationshipAssertion claims a directed edge (Subject, Predicate, Object, Qualifier). Either endpoint may be owned by another contribution; the edge is kept as unresolved until both resources are present.

type ResolutionStatus

type ResolutionStatus string

ResolutionStatus records whether a facet or relationship's endpoint resources are present in the compiled snapshot.

const (
	ResolutionResolved   ResolutionStatus = ""
	ResolutionUnresolved ResolutionStatus = "unresolved"
)

Resolution statuses. Resolved is the zero value so it is omitted from JSON.

type Resource

type Resource struct {
	ID         string              `json:"id"`
	Kind       string              `json:"kind"`
	Identity   IdentityClaim       `json:"identity"`
	Assertions []ResourceAssertion `json:"assertions"`
}

Resource is a compiled graph node with every assertion that claimed it, in canonical order.

type ResourceAssertion

type ResourceAssertion struct {
	Claim       IdentityClaim     `json:"claim"`
	Kind        string            `json:"kind"`
	DisplayName string            `json:"displayName,omitempty"`
	Attributes  map[string]string `json:"attributes,omitempty"`
	PluginID    string            `json:"pluginId"`
	SourceID    string            `json:"sourceId"`
	RuleID      string            `json:"ruleId"`
	EvidenceIDs []string          `json:"evidenceIds"`
}

ResourceAssertion claims that a resource with Kind exists under Claim. More than one plugin may assert the same identity; differing kinds produce an AssertionConflict instead of a Resource.

type ResourceAuthoringContext

type ResourceAuthoringContext struct {
	SchemaVersion        string            `json:"schemaVersion"`
	SourceRevisionSHA256 string            `json:"sourceRevisionSha256,omitempty"`
	Context              json.RawMessage   `json:"context"`
	Attributes           map[string]string `json:"attributes,omitempty"`
}

func DecodeResourceAuthoringContext

func DecodeResourceAuthoringContext(encoded string) (ResourceAuthoringContext, error)

func NewResourceAuthoringContext

func NewResourceAuthoringContext(context any, attributes map[string]string) (ResourceAuthoringContext, error)

func (ResourceAuthoringContext) SHA256

func (authoringContext ResourceAuthoringContext) SHA256() (string, error)

func (ResourceAuthoringContext) Validate

func (authoringContext ResourceAuthoringContext) Validate() error

type SchemeDefinition

type SchemeDefinition struct {
	Scheme    IdentityScheme
	Normalize func(IdentityClaim) (IdentityClaim, error)
}

SchemeDefinition binds an authority contract to its identity normalizer. Plugins register only schemes whose identity authority they introduce.

func NetworkDestinationSchemeDefinition

func NetworkDestinationSchemeDefinition() SchemeDefinition

NetworkDestinationSchemeDefinition defines the built-in agentshield.io/v1 NetworkDestination scheme. Its authority is a network realm and its key is dns/<host> or ip/<address>, lowercased so configuration and telemetry converge on one node.

func NetworkPeerClassSchemeDefinition

func NetworkPeerClassSchemeDefinition() SchemeDefinition

NetworkPeerClassSchemeDefinition defines the built-in agentshield.io/v1 NetworkPeerClass scheme. Its key must be one value of a closed vocabulary, so unresolved telemetry peers collapse into a bounded set of nodes instead of one node per raw address.

func ProcessClassSchemeDefinition

func ProcessClassSchemeDefinition() SchemeDefinition

ProcessClassSchemeDefinition normalizes ProcessClass claims and accepts only the core process-class vocabulary.

func TrimmedIdentityScheme

func TrimmedIdentityScheme(name IdentityScheme) SchemeDefinition

TrimmedIdentityScheme returns a definition whose normalizer trims whitespace and requires a non-empty authority and key. It preserves key case; use a custom normalizer when the provider key is case-insensitive.

type SecurityClass

type SecurityClass string

SecurityClass separates what is reachable (exposure) from what constrains it (governance).

const (
	SecurityClassExposure   SecurityClass = "exposure"
	SecurityClassGovernance SecurityClass = "governance"
)

Security classes.

type SecurityDomain

type SecurityDomain string

SecurityDomain names the security mechanism a SecuritySemantics describes.

const (
	SecurityDomainNetworkAccess           SecurityDomain = "network-access"
	SecurityDomainAuthorization           SecurityDomain = "authorization"
	SecurityDomainTransportAuthentication SecurityDomain = "transport-authentication"
)

Security domains.

type SecurityPort

type SecurityPort struct {
	Protocol string `json:"protocol"`
	Port     uint16 `json:"port"`
}

SecurityPort is one protocol and port pair in a SecuritySemantics summary.

type SecuritySemantics

type SecuritySemantics struct {
	Version             string         `json:"version"`
	Class               SecurityClass  `json:"class"`
	Domain              SecurityDomain `json:"domain"`
	State               SecurityState  `json:"state"`
	Effect              string         `json:"effect"`
	Scope               string         `json:"scope"`
	Direction           string         `json:"direction"`
	Coverage            string         `json:"coverage"`
	Protocols           []string       `json:"protocols,omitempty"`
	Ports               []SecurityPort `json:"ports,omitempty"`
	ConfigurationDigest string         `json:"configurationDigest,omitempty"`
}

SecuritySemantics is the provider-neutral security meaning attached to a facet or relationship. Provider-native resources and attributes remain the provenance and drill-down surface.

func DecodeSecuritySemantics

func DecodeSecuritySemantics(attributes map[string]string) (*SecuritySemantics, error)

DecodeSecuritySemantics returns the envelope stored in attributes, or nil when none is present. It rejects unknown fields, trailing data, invalid vocabulary, and any payload that differs from its canonical encoding, so the stored bytes, and therefore assertion content addresses, are unambiguous.

type SecurityState

type SecurityState string

SecurityState records whether a security fact is declared or supported by provider/runtime observations. Declared configuration alone does not prove enforcement.

const (
	SecurityStateDeclared SecurityState = "declared"
	SecurityStateObserved SecurityState = "observed"
	SecurityStateUnknown  SecurityState = "unknown"
)

Security states.

type Snapshot

type Snapshot struct {
	Resources     []Resource          `json:"resources"`
	Facets        []Facet             `json:"facets"`
	Relationships []Relationship      `json:"relationships"`
	Telemetry     []TelemetryEvent    `json:"telemetry"`
	Conflicts     []AssertionConflict `json:"conflicts,omitempty"`
}

Snapshot is the canonical graph compiled by grouping assertions around their normalized identities while retaining each assertion's provenance.

func (Snapshot) CanonicalJSON

func (s Snapshot) CanonicalJSON() ([]byte, error)

CanonicalJSON encodes the snapshot. Because the compiler sorts every slice and encoding/json sorts map keys, equal snapshots encode to equal bytes.

func (Snapshot) MarshalIndent

func (s Snapshot) MarshalIndent() ([]byte, error)

MarshalIndent encodes the snapshot for human inspection.

type TelemetryAssertion

type TelemetryAssertion struct {
	EventID     string            `json:"eventId"`
	Kind        string            `json:"kind"`
	Subject     IdentityClaim     `json:"subject"`
	Object      IdentityClaim     `json:"object"`
	Operation   string            `json:"operation,omitempty"`
	Outcome     string            `json:"outcome,omitempty"`
	Coverage    string            `json:"coverage,omitempty"`
	Count       uint64            `json:"count"`
	Properties  map[string]string `json:"properties,omitempty"`
	PluginID    string            `json:"pluginId"`
	SourceID    string            `json:"sourceId"`
	RuleID      string            `json:"ruleId"`
	EvidenceIDs []string          `json:"evidenceIds"`
}

TelemetryAssertion is a bounded rollup of observed activity from Subject to Object. EventID must be stable for the rollup series; reusing it within one plugin and source with different content is a compile error. Raw events stay in the telemetry sink.

type TelemetryEvent

type TelemetryEvent struct {
	ID          string            `json:"id"`
	EventID     string            `json:"eventId"`
	Kind        string            `json:"kind"`
	SubjectID   string            `json:"subjectId"`
	ObjectID    string            `json:"objectId"`
	Operation   string            `json:"operation,omitempty"`
	Outcome     string            `json:"outcome,omitempty"`
	Coverage    string            `json:"coverage,omitempty"`
	Count       uint64            `json:"count"`
	Properties  map[string]string `json:"properties,omitempty"`
	PluginID    string            `json:"pluginId"`
	SourceID    string            `json:"sourceId"`
	RuleID      string            `json:"ruleId"`
	EvidenceIDs []string          `json:"evidenceIds"`
}

TelemetryEvent is a compiled telemetry rollup with endpoints resolved to resource IDs. ID is derived from plugin, source, and EventID.

Jump to

Keyboard shortcuts

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