enforcer

package
v0.16.7 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 25 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package enforcer provides opt-in, finite source-address blocks for one immutable network scope. Handler can be mounted by an existing HTTP server; this package never starts a listener. Backends are trusted executors, not authorization boundaries.

Index

Constants

View Source
const (
	HardMaxTTL    = 15 * time.Minute
	HardMaxLeases = 1000
)
View Source
const MCPMaxRequestBytes = 16 << 10

MCPMaxRequestBytes bounds each JSON-RPC envelope, including tool arguments.

Variables

View Source
var (
	ErrConflict = errors.New("lease ID or packet selector already in use")
	ErrLimit    = errors.New("lease limit reached")
)

Functions

func ActionApprovalDigest

func ActionApprovalDigest(id, source string, ttl time.Duration, expires time.Time, action Action) string

func CreateApprovalDigest

func CreateApprovalDigest(id, source string, ttl time.Duration, expires time.Time) string

func DeleteApprovalDigest

func DeleteApprovalDigest(l Lease) string

Types

type Action

type Action struct {
	Kind    ActionKind `json:"kind,omitempty"`
	Profile string     `json:"profile,omitempty"`
	Flow    Flow       `json:"flow,omitempty"`
}

func (Action) EffectiveKind

func (a Action) EffectiveKind() ActionKind

func (*Action) UnmarshalJSON

func (a *Action) UnmarshalJSON(raw []byte) error

type ActionKind

type ActionKind string
const (
	BlockSource    ActionKind = "block_source"
	Quarantine     ActionKind = "quarantine"
	DropFlow       ActionKind = "drop_flow"
	RejectFlow     ActionKind = "reject_flow"
	RateSource     ActionKind = "rate_source"
	RedirectSource ActionKind = "redirect_source"
)

type Backend

type Backend interface {
	Apply(context.Context, Lease) error
	Delete(context.Context, Lease) error
	List(context.Context) ([]Lease, error)
}

Backend operations must be idempotent. Apply must never extend ExpiresAt; Delete must remove only the exact lease. List returns only owned leases. Implementations must enforce expiry independently of Controller.Reconcile.

type Config

type Config struct {
	Approvals *firewallauth.Approvals
	Auth      *firewallauth.Authority
	AuthScope firewallauth.Scope
	Origin    string
	Token     string
	Table     string
	// Namespace is an existing named Linux netns under /run/netns. It is required
	// by NewNFTBackend; enforcer never creates a namespace or targets the default one.
	Namespace      string
	Scope          Scope
	ProtectedCIDRs []string
	MaxLeases      int
	MaxTTL         time.Duration
	DryRun         bool
	// StateFile is an optional private desired-state snapshot. Its parent must
	// exist. A sibling .lock prevents concurrent controllers using the same file.
	StateFile         string
	Profiles          map[string]Profile
	ProtectedServices []Service
}

type Controller

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

func New

func New(config Config, backend Backend) (*Controller, error)

New validates the scope and reconciles immediately. With nil backend it selects DryRunBackend or NewNFTBackend. No listener, goroutine or installation is started. Call Reconcile periodically to garbage-collect expired rules and state; the nft set timeout removes the actual block even if this process has stopped. After backend acceptance, New owns its lifetime: an io.Closer backend is closed on initialization failure or Controller.Close. Do not share an NFTBackend.

func (*Controller) Close

func (c *Controller) Close() error

Close closes an io.Closer backend (releasing the nft namespace/table singleton) and releases the state-file lock. Existing leases retain their kernel TTL; Close does not remove blocks or delete the owned table.

func (*Controller) Create

func (c *Controller) Create(ctx context.Context, id, source string, ttl time.Duration) (Lease, error)

func (*Controller) CreateAction

func (c *Controller) CreateAction(ctx context.Context, id, source string, ttl time.Duration, action Action) (Lease, error)

func (*Controller) CreateActionUntil

func (c *Controller) CreateActionUntil(ctx context.Context, id, source string, expiresAt time.Time, action Action) (Lease, error)

func (*Controller) CreateUntil

func (c *Controller) CreateUntil(ctx context.Context, id, source string, expiresAt time.Time) (Lease, error)

CreateUntil preserves the exact UTC deadline (RFC3339Nano on the wire). Remaining lifetime must be 1ms..MaxTTL on the enforcer's clock. nft truncates remaining time to milliseconds; TTLSeconds is metadata, never a renewal input. An active same-ID retry must have the same source and deadline.

func (*Controller) Delete

func (c *Controller) Delete(ctx context.Context, id string) error

func (*Controller) Handler

func (c *Controller) Handler() http.Handler

Handler serves /mcp (stateless Streamable HTTP), GET/POST /v1/leases and DELETE /v1/leases/{id}. REST POST accepts {"id":"incident-1","source":"192.0.2.1","ttl_seconds":60}. expires_at optionally specifies an authoritative RFC3339Nano deadline; it can replace ttl_seconds. When both are present, TTL is an additional upper bound. All routes require Authorization: Bearer <Token>. Mount behind TLS or on a trusted local socket; the embedding server owns transport timeouts. Bodies are bounded and duplicate/unknown JSON fields are rejected before action dispatch.

func (*Controller) List

func (c *Controller) List(ctx context.Context) ([]Lease, error)

func (*Controller) Reconcile

func (c *Controller) Reconcile(ctx context.Context) error

type DryRunBackend

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

DryRunBackend is an unprivileged in-memory simulator. It executes no commands.

func NewDryRunBackend

func NewDryRunBackend() *DryRunBackend

func (*DryRunBackend) Apply

func (b *DryRunBackend) Apply(ctx context.Context, l Lease) error

func (*DryRunBackend) Delete

func (b *DryRunBackend) Delete(ctx context.Context, l Lease) error

func (*DryRunBackend) List

func (b *DryRunBackend) List(ctx context.Context) ([]Lease, error)

type ExecutionError

type ExecutionError struct{ Err error }

ExecutionError identifies backend/persistence failures without exposing command output.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

func (*ExecutionError) Unwrap

func (e *ExecutionError) Unwrap() error

type Flow

type Flow struct {
	Destination     string `json:"destination" yaml:"destination"`
	Protocol        string `json:"protocol" yaml:"protocol"`
	SourcePort      uint16 `json:"source_port" yaml:"source_port"`
	DestinationPort uint16 `json:"destination_port" yaml:"destination_port"`
}

Flow is an ingress five-tuple; Source is the lease's independently attributed IP.

type Lease

type Lease struct {
	Action Action `json:"action,omitempty"`
	ID     string `json:"id"`
	Source string `json:"source"`
	Scope  Scope  `json:"scope"`
	// TTLSeconds is the ceiling of the admission-time lifetime in seconds.
	// ExpiresAt is authoritative; subsecond leases do not receive a fresh second.
	TTLSeconds int64     `json:"ttl_seconds"`
	ExpiresAt  time.Time `json:"expires_at"`
}

type NFTBackend

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

NFTBackend exclusively owns one inet table inside an explicitly named network namespace. It needs iproute2, nft and namespace administration privileges. Construction takes a root-owned /run/netcap-enforcer lock keyed by namespace device/inode and inet table, independent of Config.StateFile and scope. No commands run until the first List creates the table. Close releases the lock; process death also releases it. Never unlink the lock file. All cooperating processes must share the host's /run mount; private /run mounts cannot coordinate flock ownership and must not target the same network namespace.

func NewNFTBackend

func NewNFTBackend(config Config) (*NFTBackend, error)

func (*NFTBackend) Apply

func (b *NFTBackend) Apply(ctx context.Context, l Lease) error

func (*NFTBackend) Close

func (b *NFTBackend) Close() error

Close releases singleton ownership without changing kernel leases or the table.

func (*NFTBackend) Delete

func (b *NFTBackend) Delete(ctx context.Context, l Lease) error

func (*NFTBackend) List

func (b *NFTBackend) List(ctx context.Context) ([]Lease, error)

type Profile

type Profile struct {
	Kind        ActionKind `json:"kind"`
	Services    []Service  `json:"services"`
	Rate        uint32     `json:"rate,omitempty"`
	Burst       uint32     `json:"burst,omitempty"`
	Unit        string     `json:"unit,omitempty"` // packets or bytes, per second
	Destination string     `json:"destination,omitempty"`
	Port        uint16     `json:"port,omitempty"`
}

Profile is bootstrap authority. Requests can name it, never supply its contents.

type Scope

type Scope struct {
	Hook            string `json:"hook"`
	Interface       string `json:"interface"`
	DestinationCIDR string `json:"destination_cidr"`
	Protocol        string `json:"protocol"`
	Port            uint16 `json:"port"`
}

Scope applies only to packets entering Interface, destined for DestinationCIDR and Port using Protocol. Hook must explicitly be "input" or "forward". There is no output hook, interface wildcard, all-ports or all-protocols mode.

type Service

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

Jump to

Keyboard shortcuts

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