kubernetes

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: 34 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 kubernetes is the Kubernetes source plugin and the shared Kubernetes observation layer that the Istio, agentgateway, and Cilium plugins build on.

Watches and collections

The plugin owns API discovery and one dynamic shared informer factory per cluster. It always watches a required core inventory (namespaces, nodes, pods, services, workloads, RBAC, admission, NetworkPolicy, Ingress, and related resources) and the optional gateway-api-v1 capability. Semantic plugins add GroupVersionResources through ResourceRequirementsProvider; the host merges them with ResourceRequirements before construction, so each GVR is watched once no matter how many plugins need it. Every watched GVR is published as its own kubernetes/resources/<group>/<version>/<resource> collection, and CollectionResourceCoverage reports per-capability API coverage. Consumers read these through ResourceClient rather than opening their own watches.

Secret observations carry metadata and a sorted key list only; values, type, and annotations never enter a collection or the native-event store.

Identity

Kubernetes objects use the kubernetes.io/v1 Object scheme with the configured cluster ID as authority and the lowercased apiVersion/kind/UID as the immutable key (see ClaimFor and ClaimForUID). Names, labels, and IP addresses are attributes. Every plugin asserting about a Kubernetes object reuses this scheme so its claims converge on the same graph resource. Service and Pod addresses materialize provider-neutral network destinations under the configured network ID, with exposes edges from their owners.

Graph output

The "inventory" contribution asserts resources plus contains, runs-on, instantiates, uses-identity, exposes, member-of, governed-by, and backed-by relationships and network-exposure, transport-posture, policy-targeting, and route-backends facets. Node-to-cloud-instance backed-by edges are emitted only when a configured IdentityReferenceResolver (for example the AWS plugin) resolves the Node's spec.providerID.

Failure behavior

An unavailable required API fails startup. An optional API that is not advertised is unsupported coverage; one that cannot be read is degraded and marks the contribution degraded. Neither proves the absence of unobserved objects. Each change replaces the complete contribution at the next generation; deletion is omission.

The package also implements the network-policy/v1 remediation action, which isolates a Pod's ingress with a NetworkPolicy and a controlled Pod label.

See https://agent-shield.dev/docs/plugins/kubernetes/ and, for the plugin contract, https://agent-shield.dev/docs/plugins/contract/.

Index

Constants

View Source
const CollectionResourceCoverage = "kubernetes/resource-coverage"

CollectionResourceCoverage reports which resource types this plugin can reliably observe.

View Source
const (
	// PluginID is the plugin and contribution owner ID, and the prefix of
	// Kubernetes observation event IDs.
	PluginID = "kubernetes"
)

Variables

This section is empty.

Functions

func ClaimFor

func ClaimFor(clusterID string, item *unstructured.Unstructured) graph.IdentityClaim

ClaimFor returns the cluster-qualified identity of item.

func ClaimForUID

func ClaimForUID(clusterID, apiVersion, kind, uid string) graph.IdentityClaim

ClaimForUID returns the cluster-qualified identity of an object known only by apiVersion, kind, and UID, for example from telemetry.

func DecodeProviderState

func DecodeProviderState(state remediation.ProviderState) (ActionObservation, ActionObservation, error)

DecodeProviderState reverses ProviderState.

func Descriptor

func Descriptor() agentshield.Descriptor

Descriptor declares Kubernetes as the owner of the shared object and coverage collections and of the cluster-qualified Kubernetes identity scheme.

func IdentitySchemeDefinition

func IdentitySchemeDefinition() graph.SchemeDefinition

IdentitySchemeDefinition makes Kubernetes object UIDs cluster-qualified so other plugins can assert against the same canonical resources.

func OwnedByRemediationTarget

func OwnedByRemediationTarget(object *unstructured.Unstructured, uid string) bool

OwnedByRemediationTarget reports whether object is managed by AgentShield for the remediation target with uid.

func Project

func Project(clusterID, sourceID string, objects []*unstructured.Unstructured) (graph.Input, error)

Project projects bare objects with the cluster ID as network ID. It exists for tests and offline evaluation.

func ProjectWithNetworkID

func ProjectWithNetworkID(clusterID, networkID, sourceID string, objects []*unstructured.Unstructured) (graph.Input, error)

ProjectWithNetworkID is Project with an explicit network ID.

func ProviderState

func ProviderState(key string, current, prepared ActionObservation) (remediation.ProviderState, error)

ProviderState encodes the current and prepared observations of one object in canonical JSON for a remediation preparation or result.

func RemediationTargetValue

func RemediationTargetValue(uid string) string

RemediationTargetValue is the value of a Pod action's target label for the Pod with uid.

func RollbackPodLabel

func RollbackPodLabel(ctx context.Context, transport WriteTransport, resource schema.GroupVersionResource, original, updated *unstructured.Unstructured, digest ControlledDigest, operation string) error

RollbackPodLabel restores original's controlled fields over updated using updated's resource version, so a concurrent change fails the rollback instead of being overwritten.

func UpdatePodLabel

func UpdatePodLabel(ctx context.Context, transport WriteTransport, resource schema.GroupVersionResource, desired *unstructured.Unstructured, nativeDryRun bool, digest ControlledDigest, operation string) (*unstructured.Unstructured, error)

UpdatePodLabel updates desired, optionally as a server-side dry run, and fails if admission changed any controlled field or the UID. operation prefixes the update error.

Types

type ActionObservation

type ActionObservation struct {
	Resource         string `json:"resource"`
	Namespace        string `json:"namespace,omitempty"`
	Name             string `json:"name"`
	Exists           bool   `json:"exists"`
	UID              string `json:"uid,omitempty"`
	ResourceVersion  string `json:"resourceVersion,omitempty"`
	ControlledSHA256 string `json:"controlledSha256,omitempty"`
}

ActionObservation records the provider state a remediation step observed for one object. ControlledSHA256 digests only the fields the action controls, so unrelated changes do not invalidate a plan.

type CLIConfig

type CLIConfig struct {
	Kubeconfig string
	ClusterID  string
	NetworkID  string
	SourceID   string
	Disabled   bool
}

CLIConfig contains the Kubernetes-owned runtime options. Its cluster authority is separate from each consumer plugin's authority configuration; matching values are required when their identities must join.

func (*CLIConfig) RegisterFlags

func (config *CLIConfig) RegisterFlags(flags *pflag.FlagSet) error

RegisterFlags registers Kubernetes flags in the kubernetes-* namespace.

type Config

type Config struct {
	ClusterID         string
	NetworkID         string
	SourceID          string
	Dynamic           dynamic.Interface
	Actions           WriteTransport
	Discovery         discovery.DiscoveryInterface
	Resync            time.Duration
	Resources         []ResourceRequirement
	IdentityResolvers []agentshield.IdentityReferenceResolver
}

Config configures one cluster source. NetworkID defaults to ClusterID, Actions to a transport over Dynamic, and Resync to 30 minutes. Resources are the merged semantic-plugin requirements from ResourceRequirements.

type ControlledDigest

type ControlledDigest func(*unstructured.Unstructured) (string, error)

ControlledDigest digests the fields of an object that an action controls.

type CoverageStatus

type CoverageStatus string

CoverageStatus is the observation state of one capability's API.

const (
	// CoverageCovered means the API is advertised and its informer synced.
	CoverageCovered CoverageStatus = "covered"
	// CoverageUnsupported means an optional API is not advertised.
	CoverageUnsupported CoverageStatus = "unsupported"
	// CoverageDegraded means an optional API is advertised but could not be
	// discovered or synced.
	CoverageDegraded CoverageStatus = "degraded"
	// CoverageFailed means a required API is unavailable or its informer is
	// not synced. During discovery it fails source startup.
	CoverageFailed CoverageStatus = "failed"
)

type DynamicTransport

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

DynamicTransport implements WriteTransport with a dynamic client.

func NewDynamicTransport

func NewDynamicTransport(client dynamic.Interface) (*DynamicTransport, error)

NewDynamicTransport wraps client.

func (*DynamicTransport) ReadResource

func (transport *DynamicTransport) ReadResource(resource schema.GroupVersionResource, namespace string) ResourceReader

ReadResource implements ReadTransport.

func (*DynamicTransport) WriteResource

func (transport *DynamicTransport) WriteResource(resource schema.GroupVersionResource, namespace string) ResourceWriter

WriteResource implements WriteTransport.

type Plugin

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

Plugin is the Kubernetes source, inventory projection, and remediation plugin.

func New

func New(config Config) (*Plugin, error)

New validates config and applies defaults.

func NewForConfig

func NewForConfig(config *rest.Config, clusterID, sourceID string, resources ...ResourceRequirement) (*Plugin, error)

NewForConfig builds clients from config and uses clusterID as network ID.

func NewForConfigWithNetworkID

func NewForConfigWithNetworkID(config *rest.Config, clusterID, networkID, sourceID string, resources ...ResourceRequirement) (*Plugin, error)

NewForConfigWithNetworkID builds clients from config.

func (*Plugin) Descriptor

func (p *Plugin) Descriptor() agentshield.Descriptor

Descriptor adds a collection for each configured semantic-plugin GVR to Descriptor.

func (*Plugin) Execute

Execute re-derives the plan, requires the provider state recorded by Prepare to be unchanged, and applies the action's NetworkPolicy. Pod actions also label the target and roll that label back if the policy write fails.

func (*Plugin) Plan

func (p *Plugin) Plan(ctx context.Context, proposal remediation.Proposal, actionID string) (remediation.Plan, error)

Plan resolves the proposal target and derives the desired NetworkPolicy, rejecting targets already selected by an overlapping ingress policy. It writes nothing.

func (*Plugin) Prepare

Prepare submits the desired Kubernetes writes as server-side dry runs so admission can reject them before any change, and records the admitted state.

func (*Plugin) RemediationDescriptor

func (p *Plugin) RemediationDescriptor() remediation.Descriptor

RemediationDescriptor advertises ingress isolation actions for Kubernetes Pods and Services.

func (*Plugin) Run

func (p *Plugin) Run(ctx context.Context, runtime agentshield.Runtime) error

Run discovers APIs, starts one informer per selected GVR, and publishes observations, coverage, and the inventory contribution. Each informer change triggers a full reconciliation at the next generation; bursts coalesce into one.

func (*Plugin) SourceID

func (p *Plugin) SourceID() string

SourceID returns the configured source ID.

func (*Plugin) Verify

Verify reports satisfied only while the live target and NetworkPolicy match the digests recorded at execution. It checks declared configuration, not CNI enforcement.

type PodPolicyAction

type PodPolicyAction struct {
	// Provider names the provider in error messages, such as "Istio".
	Provider   string
	ProviderID string
	SourceID   string
	ClusterID  string
	Intent     remediation.Intent
	Transport  WriteTransport
	// TargetLabel is the Pod label the policy selects.
	TargetLabel string
	// PolicyKind and PolicyResource name the managed policy type, and
	// PolicyStateKey keys its entry in provider state.
	PolicyKind     string
	PolicyResource schema.GroupVersionResource
	PolicyStateKey string
	PolicyName     func(uid string) string
	// BuildPolicy returns the desired policy selecting TargetLabel=targetValue.
	// It must carry the managed-by label and the target UID annotation.
	BuildPolicy  func(namespace, name, uid, targetValue string) (*unstructured.Unstructured, error)
	PolicyDigest ControlledDigest
	// RejectConflicts fails when a policy other than the managed one already
	// covers pod. It runs at planning and again after the label write.
	RejectConflicts func(ctx context.Context, pod *unstructured.Unstructured, managedName string) error
}

PodPolicyAction is the shared plan, prepare, execute, and verify skeleton of a remediation that labels one target Pod and writes one managed policy whose selector matches only that label. The Kubernetes, Istio, and Cilium Pod actions differ only in the policy object they build and in which existing policies conflict with it.

The policy is owned by the target when it carries the agentshield managed-by label and the target UID annotation. An existing policy with the deterministic name is reused only when it is owned and its controlled content matches.

func (*PodPolicyAction) DecodeStates

DecodeStates returns the current and prepared observations of the target Pod and the managed policy, in that order. It requires exactly one of each.

func (*PodPolicyAction) Execute

Execute re-derives the plan, requires the provider state recorded by Prepare to be unchanged, labels the Pod, rechecks for conflicting policy, and writes the policy. If a step after labeling fails, the label is rolled back on a context detached from ctx.

func (*PodPolicyAction) Plan

func (action *PodPolicyAction) Plan(ctx context.Context, proposal remediation.Proposal, actionID string) (remediation.Plan, error)

Plan resolves the proposal's target Pod and returns a plan over the digest of the desired label and policy. It writes nothing.

func (*PodPolicyAction) Prepare

Prepare submits the desired Pod label and policy as server-side dry runs so admission can reject them before any change, and records the admitted state.

func (*PodPolicyAction) Verify

Verify reports satisfied only while the live Pod label and policy still match the digests recorded at execution. It checks declared configuration, not enforcement.

func (*PodPolicyAction) WritePolicy

func (action *PodPolicyAction) WritePolicy(ctx context.Context, desired *unstructured.Unstructured, dryRun bool) (*unstructured.Unstructured, error)

WritePolicy creates desired, optionally as a server-side dry run, and fails if admission changed its controlled content. An existing policy is accepted unchanged only when it is owned by the same target, has the observed resource version, and has the same controlled content; remediation never updates a policy.

type ReadTransport

type ReadTransport interface {
	ReadResource(schema.GroupVersionResource, string) ResourceReader
}

ReadTransport opens readers for a GVR in a namespace, or cluster-scoped when namespace is empty.

type ResourceChange

type ResourceChange[T any] struct {
	discovery.Change
	Object T
}

ResourceChange is a collection change with its payload decoded. Object is the zero value for delete and sync changes.

type ResourceClient

type ResourceClient[T any] struct {
	// contains filtered or unexported fields
}

ResourceClient is a typed subscription to one shared Kubernetes resource collection. It never opens a Kubernetes connection.

func NewResourceClient

func NewResourceClient[T any](requirement ResourceRequirement, decode func([]byte) (T, error)) (*ResourceClient[T], error)

NewResourceClient returns a client that decodes upsert payloads with decode.

func NewUnstructuredResourceClient

func NewUnstructuredResourceClient(requirement ResourceRequirement) (*ResourceClient[*unstructured.Unstructured], error)

NewUnstructuredResourceClient returns a client that decodes payloads into unstructured objects.

func (*ResourceClient[T]) Collection

func (client *ResourceClient[T]) Collection() string

Collection returns the collection this client subscribes to.

func (*ResourceClient[T]) Requirement

func (client *ResourceClient[T]) Requirement() ResourceRequirement

Requirement returns the requirement this client was built for.

func (*ResourceClient[T]) Subscribe

func (client *ResourceClient[T]) Subscribe(ctx context.Context, runtime discovery.Runtime) (<-chan ResourceChange[T], <-chan error, error)

Subscribe replays and then follows the collection. The error channel receives at most one error: a decode failure or unexpected collection closure. Both channels close when delivery stops.

type ResourceCoverage

type ResourceCoverage struct {
	Capability string         `json:"capability"`
	GVR        string         `json:"gvr"`
	Required   bool           `json:"required"`
	Advertised bool           `json:"advertised"`
	Status     CoverageStatus `json:"status"`
	Message    string         `json:"message,omitempty"`
}

ResourceCoverage states whether one API resource falls inside this source's observation boundary; unsupported or degraded coverage does not prove nonexistence.

type ResourceReader

ResourceReader is the read subset of a dynamic resource client.

type ResourceRequirement

type ResourceRequirement struct {
	GVR        schema.GroupVersionResource
	Capability string
	Required   bool
}

ResourceRequirement asks the Kubernetes plugin to watch one GVR. Capability groups GVRs into one coverage boundary; a Required capability that is not available fails source startup.

func ResourceRequirements

func ResourceRequirements(plugins ...discovery.Plugin) []ResourceRequirement

ResourceRequirements merges the requirements of every plugin that implements ResourceRequirementsProvider, deduplicating by capability and GVR. A GVR is required if any plugin requires it. The result is sorted.

func (ResourceRequirement) Collection

func (requirement ResourceRequirement) Collection() string

Collection returns kubernetes/resources/<group>/<version>/<resource>, with "core" for the empty group. It names delivery, not identity.

type ResourceRequirementsProvider

type ResourceRequirementsProvider interface {
	KubernetesResources() []ResourceRequirement
}

ResourceRequirementsProvider is implemented by semantic plugins that consume Kubernetes collections. The host collects requirements before constructing the Kubernetes plugin.

type ResourceWriter

ResourceWriter adds the create and update calls remediation uses. Remediation never patches or deletes provider objects.

type WriteTransport

type WriteTransport interface {
	ReadTransport
	WriteResource(schema.GroupVersionResource, string) ResourceWriter
}

WriteTransport is shared by the Kubernetes, Istio, and Cilium remediation actions so all writes go through one client and can be faked in tests.

Directories

Path Synopsis
Package api decodes Kubernetes objects from their unstructured transport form into typed values for projection.
Package api decodes Kubernetes objects from their unstructured transport form into typed values for projection.

Jump to

Keyboard shortcuts

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