policy

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: AGPL-3.0 Imports: 15 Imported by: ? 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.

README

policy

ci codecov

Policy plugin and expression language for the Pilot Protocol daemon. The repo ships two packages:

  • policy/ — a coreapi.Service adapter that loads per-network policy files and emits decisions on the event bus.
  • policy/policylang/ — the expr-lang/expr–backed evaluator. Used by the plugin and by cmd/pilotctl for policy linting.

Install

import (
    "github.com/pilot-protocol/policy"
    "github.com/pilot-protocol/policy/policylang"
)

Usage

p, err := policylang.Parse(jsonBytes)
if err != nil {
    return err
}
_ = p

rt.Register(policy.NewService(policy.Config{
    PolicyDir: "~/.pilot/policy",
}))

Layout

Root package (github.com/pilot-protocol/policy)
File What it does
runtime.go Loads/reloads policy files and watches the policy dir.
runner.go Per-network expression runner; binds events to the evaluator.
peer.go Per-peer rate/scope state used by directives.
aliases.go Re-exports policylang types for source compatibility.
service.go *Service — coreapi.Service adapter. Build tag !no_policy.
service_disabled.go Stub when build tag no_policy is set.
Subpackage policylang/
File What it does
policy.go Policy struct and JSON unmarshal.
engine.go Compile and cache compiled programs; evaluate against env.
env.go Event/peer-context binding for the expr-lang VM.

Build tags

Tag Effect
no_policy Compiles a stub whose Start is a no-op.

License

AGPL-3.0-or-later. See LICENSE.

Documentation

Index

Constants

View Source
const (
	EventConnect  = policylang.EventConnect
	EventDial     = policylang.EventDial
	EventDatagram = policylang.EventDatagram
	EventCycle    = policylang.EventCycle
	EventJoin     = policylang.EventJoin
	EventLeave    = policylang.EventLeave
)

EventType constants.

View Source
const (
	ActionAllow      = policylang.ActionAllow
	ActionDeny       = policylang.ActionDeny
	ActionTag        = policylang.ActionTag
	ActionEvict      = policylang.ActionEvict
	ActionEvictWhere = policylang.ActionEvictWhere
	ActionPrune      = policylang.ActionPrune
	ActionFill       = policylang.ActionFill
	ActionPruneTrust = policylang.ActionPruneTrust
	ActionFillTrust  = policylang.ActionFillTrust
	ActionWebhook    = policylang.ActionWebhook
	ActionLog        = policylang.ActionLog
)

ActionType constants.

View Source
const (
	DirectiveAllow      = policylang.DirectiveAllow
	DirectiveDeny       = policylang.DirectiveDeny
	DirectiveTag        = policylang.DirectiveTag
	DirectiveEvict      = policylang.DirectiveEvict
	DirectiveEvictWhere = policylang.DirectiveEvictWhere
	DirectivePrune      = policylang.DirectivePrune
	DirectiveFill       = policylang.DirectiveFill
	DirectivePruneTrust = policylang.DirectivePruneTrust
	DirectiveFillTrust  = policylang.DirectiveFillTrust
	DirectiveWebhook    = policylang.DirectiveWebhook
	DirectiveLog        = policylang.DirectiveLog
)

DirectiveType constants.

View Source
const Version = policylang.Version

Version is the policy schema version.

Variables

This section is empty.

Functions

func IsGateEvent

func IsGateEvent(e EventType) bool

func Validate

func Validate(doc *PolicyDocument) error

Types

type Action

type Action = policylang.Action

Document/version aliases.

type ActionType

type ActionType = policylang.ActionType

Document/version aliases.

type CompiledPolicy

type CompiledPolicy = policylang.CompiledPolicy

Document/version aliases.

func Compile

func Compile(doc *PolicyDocument) (*CompiledPolicy, error)

type Directive

type Directive = policylang.Directive

Document/version aliases.

type DirectiveType

type DirectiveType = policylang.DirectiveType

Document/version aliases.

type EventType

type EventType = policylang.EventType

Document/version aliases.

type PolicyDocument

type PolicyDocument = policylang.PolicyDocument

Document/version aliases.

func Parse

func Parse(data []byte) (*PolicyDocument, error)

Lang free-function re-exports. Functions can't be aliased — wrap.

type PolicyRunner

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

PolicyRunner manages a compiled policy for a single network. It holds per-peer state (scores, tags), runs cycle timers, and evaluates policy rules against protocol events.

func NewPolicyRunner

func NewPolicyRunner(netID uint16, cp *CompiledPolicy, d Runtime) *PolicyRunner

NewPolicyRunner creates a policy runner for a network with the given compiled policy.

func (*PolicyRunner) EvaluateActions

func (pr *PolicyRunner) EvaluateActions(eventType EventType, ctx map[string]interface{})

EvaluateActions evaluates an action event (cycle, join, leave).

func (*PolicyRunner) EvaluateGate

func (pr *PolicyRunner) EvaluateGate(eventType EventType, ctx map[string]interface{}) bool

EvaluateGate evaluates a gate event (connect, dial, datagram) and returns true if allowed, false if denied.

func (*PolicyRunner) EvaluatePortGate

func (pr *PolicyRunner) EvaluatePortGate(eventType EventType, port uint16, peerNodeID uint32, payloadSize int, direction string, localTags, nodeInfoTags []string) bool

EvaluatePortGate is the daemon-facing gate API for connect/dial/ datagram events. The plugin builds the full evaluation ctx internally (peer_age_s, peer_tags, members) using its own peer state and the daemon-supplied localTags + nodeInfoTags. Returns the allow/deny verdict; side effects (tag, log, webhook) execute on the runner.

func (*PolicyRunner) ForceCycle

func (pr *PolicyRunner) ForceCycle() map[string]interface{}

ForceCycle runs a cycle immediately.

func (*PolicyRunner) HasMember

func (pr *PolicyRunner) HasMember(peerNodeID uint32) bool

HasMember reports whether peerNodeID is in this runner's per-peer state. Used by daemon to decide which non-primary runners should also evaluate a packet event for cross-network deny semantics.

func (*PolicyRunner) NetworkID

func (pr *PolicyRunner) NetworkID() uint16

NetworkID returns the network ID this runner manages. Used by callers that hold the runner via the coreapi.PolicyRunner interface.

func (*PolicyRunner) PeerList

func (pr *PolicyRunner) PeerList() []map[string]interface{}

PeerList returns all managed peers as a list of maps, ordered by age (oldest first).

func (*PolicyRunner) Policy

func (pr *PolicyRunner) Policy() *CompiledPolicy

Policy returns the compiled policy.

func (*PolicyRunner) PolicyJSON

func (pr *PolicyRunner) PolicyJSON() ([]byte, error)

PolicyJSON marshals the underlying policy document. Returned bytes are the canonical PolicyDocument JSON the IPC layer hands back to admin tools.

func (*PolicyRunner) ReconcileNow

func (pr *PolicyRunner) ReconcileNow()

ReconcileNow triggers a membership reconcile synchronously — same code path as the periodic 5s reconciler, but on demand. Side-effect free aside from adding/removing peers, firing EventJoin/EventLeave, and updating tag metadata. No scoring / evict cycle runs.

func (*PolicyRunner) Start

func (pr *PolicyRunner) Start()

Start begins the cycle loop if the policy has cycle rules. Calling Start after Stop is a no-op (a stopped runner stays stopped).

func (*PolicyRunner) Status

func (pr *PolicyRunner) Status() map[string]interface{}

Status returns a summary of the policy runner state.

func (*PolicyRunner) Stop

func (pr *PolicyRunner) Stop()

Stop signals the cycle loop to exit and waits for it. Stop before Start is a safe no-op: cycleLoop never ran, so `done` would never be closed and waiting on it would deadlock.

type Rule

type Rule = policylang.Rule

Document/version aliases.

type Runtime

type Runtime interface {
	// NodeID returns the daemon's own node ID.
	NodeID() uint32

	// PublishEvent is the bus.Publish wrapper.
	PublishEvent(topic string, payload map[string]any)

	// AdminToken returns the token used for authenticated registry ops
	// (list_nodes, set_member_tags). Empty when not configured.
	AdminToken() string

	// ListNodes returns the registry-side membership for a network.
	// Caller must already hold any required signature/admin auth via
	// the runtime's regConn signer.
	ListNodes(netID uint16, adminToken string) (map[string]any, error)

	// SetMemberTags updates the local node's per-network tag list.
	SetMemberTags(netID uint16, tags []string)

	// TrustedPeers returns the current trust map.
	TrustedPeers() []TrustRecord

	// RevokeTrust removes a peer from the trust list.
	RevokeTrust(nodeID uint32) error

	// SendHandshakeRequest initiates a trust handshake to the peer.
	SendHandshakeRequest(nodeID uint32, reason string) error
}

Runtime is the per-daemon callback surface the policy runner needs to interact with daemon state (identity, trust subsystem, registry, event bus). The daemon (L7) implements this interface; the policy plugin (L11) calls into it via a stored reference. This inverts the previous *Daemon embedding so the runner code lives outside pkg/daemon without taking an L7-typed parameter.

type Service

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

Service is the L11 plugin adapter for the policy runtime. It owns the per-network registry of running PolicyRunner instances and satisfies coreapi.PolicyManager so the daemon can hold it via interface.

Constructed by cmd/daemon (L12) with a Runtime adapter that wraps the daemon's internals (NodeID, regConn, handshakes, bus).

func NewService

func NewService(runtime Runtime) *Service

func (*Service) LoadPersisted

func (s *Service) LoadPersisted() error

LoadPersisted scans the state directory for policy_<netID>.json snapshots and records which networks have persisted state. Called from daemon-Start after the registry connection is up.

The directory MUST be the same one NewPolicyRunner persists to — resolved via stateDir() so PILOT_HOME is honored consistently. (This previously called os.UserHomeDir directly, so when PILOT_HOME was set the scan looked in the wrong place and the persisted state was silently ignored.)

A snapshot holds per-peer scores/history, not the compiled policy, so a runner can only be rebuilt once its network rejoins (handled by handleNetworkJoined -> startInternal -> NewPolicyRunner, whose load() re-applies the matching snapshot from the same dir). Here we validate each discovered file by unmarshaling it into a policySnapshot and remember the set of persisted network IDs so callers can tell which networks carry restorable state.

func (*Service) Manager

func (s *Service) Manager() coreapi.PolicyManager

Manager returns the coreapi.PolicyManager view of this service. The daemon's RegisterPolicyManager(svc.Manager()) wires the gate hooks.

func (*Service) Name

func (s *Service) Name() string

func (*Service) Order

func (s *Service) Order() int

func (*Service) PersistedNetworks added in v0.2.3

func (s *Service) PersistedNetworks() []uint16

PersistedNetworks reports the set of network IDs that have on-disk state discovered by the last LoadPersisted call. Used by the daemon to know which networks carry restorable per-peer scores.

func (*Service) Start

func (s *Service) Start(_ context.Context, deps coreapi.Deps) error

Start wires the network.* bus subscriber. The handler reacts to network.joined / network.left events emitted by the daemon's reconcileMembership loop and calls the appropriate per-network lifecycle method (startInternal / stopInternal). Tests that don't supply Deps.Events skip the subscription wiring; lifecycle methods remain callable directly via the Manager view.

func (*Service) StartManager

func (s *Service) StartManager(netID uint16, policyJSON []byte) (coreapi.PolicyRunner, error)

func (*Service) Start_

func (s *Service) Start_(netID uint16, policyJSON []byte) (coreapi.PolicyRunner, error)

func (*Service) Stop

func (s *Service) Stop(_ context.Context) error

Stop tears down the network.* subscriber (so no further events fire against stopped runners) and stops every per-network runner.

func (*Service) StopAll

func (s *Service) StopAll()

StopAll stops every running runner. Safe to call multiple times.

type TrustRecord

type TrustRecord struct {
	NodeID     uint32
	PublicKey  string
	ApprovedAt time.Time
	Mutual     bool
	Network    uint16
}

TrustRecord is the runtime view of a single trusted peer. Mirrors pkg/daemon.TrustRecord (which the daemon-side Runtime adapter converts to). Defined here so the runner doesn't import pkg/daemon.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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