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
- Variables
- func ActionApprovalDigest(id, source string, ttl time.Duration, expires time.Time, action Action) string
- func CreateApprovalDigest(id, source string, ttl time.Duration, expires time.Time) string
- func DeleteApprovalDigest(l Lease) string
- type Action
- type ActionKind
- type Backend
- type Config
- type Controller
- func (c *Controller) Close() error
- func (c *Controller) Create(ctx context.Context, id, source string, ttl time.Duration) (Lease, error)
- func (c *Controller) CreateAction(ctx context.Context, id, source string, ttl time.Duration, action Action) (Lease, error)
- func (c *Controller) CreateActionUntil(ctx context.Context, id, source string, expiresAt time.Time, action Action) (Lease, error)
- func (c *Controller) CreateUntil(ctx context.Context, id, source string, expiresAt time.Time) (Lease, error)
- func (c *Controller) Delete(ctx context.Context, id string) error
- func (c *Controller) Handler() http.Handler
- func (c *Controller) List(ctx context.Context) ([]Lease, error)
- func (c *Controller) Reconcile(ctx context.Context) error
- type DryRunBackend
- type ExecutionError
- type Flow
- type Lease
- type NFTBackend
- type Profile
- type Scope
- type Service
Constants ¶
const ( HardMaxTTL = 15 * time.Minute HardMaxLeases = 1000 )
const MCPMaxRequestBytes = 16 << 10
MCPMaxRequestBytes bounds each JSON-RPC envelope, including tool arguments.
Variables ¶
var ( ErrConflict = errors.New("lease ID or packet selector already in use") ErrLimit = errors.New("lease limit reached") )
Functions ¶
func ActionApprovalDigest ¶
func CreateApprovalDigest ¶
func DeleteApprovalDigest ¶
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 ¶
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) CreateAction ¶
func (*Controller) CreateActionUntil ¶
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) 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.
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
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) Close ¶
func (b *NFTBackend) Close() error
Close releases singleton ownership without changing kernel leases or the table.
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.