rule

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBlockedByRule = errors.New("request blocked by rule")

ErrBlockedByRule indicates the request was blocked by a blocklist rule

View Source
var ErrRuleEvaluationFailed = errors.New("rule evaluation failed")

ErrRuleEvaluationFailed indicates rule evaluation failed (Fail-Closed for blocklist)

Functions

func ExtractAmount

func ExtractAmount(metering types.BudgetMetering, req *types.SignRequest, parsed *types.ParsedPayload) (*big.Int, error)

ExtractAmount extracts the spending amount from a request based on the metering method

Types

type BatchEvaluationResult

type BatchEvaluationResult struct {
	RuleID  types.RuleID
	Passed  bool
	Reason  string
	Err     error
	Skipped bool // true if rule was skipped (e.g., primaryType mismatch)
}

BatchEvaluationResult represents the result of evaluating a single rule in a batch

type BatchRuleEvaluator

type BatchRuleEvaluator interface {
	RuleEvaluator

	// EvaluateBatch evaluates multiple rules against the same request in a single execution
	// Returns results in the same order as the input rules
	// Rules that don't apply (e.g., primaryType mismatch) will have Skipped=true
	EvaluateBatch(ctx context.Context, rules []*types.Rule, req *types.SignRequest, parsed *types.ParsedPayload) ([]BatchEvaluationResult, error)

	// CanBatchEvaluate returns true if the given rules can be evaluated together
	// Rules might not be batchable if they use different validation modes
	CanBatchEvaluate(rules []*types.Rule) bool
}

BatchRuleEvaluator extends RuleEvaluator with batch evaluation capability This is optional - evaluators that don't support batch evaluation will fall back to sequential

type BlockedError

type BlockedError struct {
	RuleID   types.RuleID
	RuleName string
	Reason   string
}

BlockedError contains details about why a request was blocked

func (*BlockedError) Error

func (e *BlockedError) Error() string

func (*BlockedError) Unwrap

func (e *BlockedError) Unwrap() error

type BudgetChecker

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

BudgetChecker checks and deducts budget for rule instances

func NewBudgetChecker

func NewBudgetChecker(
	budgetRepo storage.BudgetRepository,
	templateRepo storage.TemplateRepository,
	logger *slog.Logger,
) *BudgetChecker

NewBudgetChecker creates a new budget checker

func (*BudgetChecker) CheckAndDeductBudget

func (bc *BudgetChecker) CheckAndDeductBudget(
	ctx context.Context,
	rule *types.Rule,
	req *types.SignRequest,
	parsed *types.ParsedPayload,
) (bool, error)

CheckAndDeductBudget checks if the rule has budget and deducts the spending amount. Returns:

  • (true, nil) if budget is available or no budget constraint
  • (false, nil) if budget is exceeded
  • (false, err) if an error occurred

type DefaultRuleGenerator

type DefaultRuleGenerator struct{}

DefaultRuleGenerator generates rules from approved transactions

func NewDefaultRuleGenerator

func NewDefaultRuleGenerator() (*DefaultRuleGenerator, error)

NewDefaultRuleGenerator creates a new default rule generator

func (*DefaultRuleGenerator) Generate

Generate creates a rule (caller saves it)

func (*DefaultRuleGenerator) Preview

Preview generates a rule preview without saving

func (*DefaultRuleGenerator) SupportedTypes

func (g *DefaultRuleGenerator) SupportedTypes() []types.RuleType

SupportedTypes returns the rule types this generator can create

type EvaluationResult

type EvaluationResult struct {
	// Blocked indicates the request was blocked by a blocklist rule
	Blocked bool

	// BlockedBy contains the rule that blocked the request (if Blocked is true)
	BlockedBy *types.Rule

	// BlockReason explains why the request was blocked
	BlockReason string

	// Allowed indicates the request was allowed by a whitelist rule
	Allowed bool

	// AllowedBy contains the rule that allowed the request (if Allowed is true)
	AllowedBy *types.Rule

	// AllowReason explains why the request was allowed
	AllowReason string
}

EvaluationResult represents the result of rule evaluation

type RuleEngine

type RuleEngine interface {
	// Evaluate performs two-tier rule evaluation:
	// 1. Check blocklist rules first - ANY violation = blocked (returns BlockedError)
	// 2. Check whitelist rules - ANY match = allowed
	// Returns:
	// - (*RuleID, reason, nil) if whitelisted
	// - (nil, "", nil) if no whitelist match (needs manual approval)
	// - (nil, "", BlockedError) if blocked by a blocklist rule
	Evaluate(ctx context.Context, req *types.SignRequest, parsed *types.ParsedPayload) (*types.RuleID, string, error)

	// EvaluateWithResult returns detailed evaluation result
	EvaluateWithResult(ctx context.Context, req *types.SignRequest, parsed *types.ParsedPayload) (*EvaluationResult, error)

	// RegisterEvaluator registers a chain-specific rule evaluator
	RegisterEvaluator(evaluator RuleEvaluator)
}

RuleEngine evaluates rules for sign requests

type RuleEngineOption

type RuleEngineOption func(*WhitelistRuleEngine)

RuleEngineOption is a functional option for WhitelistRuleEngine

func WithBudgetChecker

func WithBudgetChecker(checker *BudgetChecker) RuleEngineOption

WithBudgetChecker adds budget checking capability to the rule engine

type RuleEvaluationError

type RuleEvaluationError struct {
	RuleID   types.RuleID
	RuleName string
	RuleType types.RuleType
	Err      error
}

RuleEvaluationError contains details about a rule evaluation failure

func (*RuleEvaluationError) Error

func (e *RuleEvaluationError) Error() string

func (*RuleEvaluationError) Unwrap

func (e *RuleEvaluationError) Unwrap() error

type RuleEvaluator

type RuleEvaluator interface {
	// Type returns the rule type this evaluator handles
	Type() types.RuleType

	// Evaluate evaluates the rule against the request
	// For whitelist mode: returns (true, reason, nil) if request matches the whitelist
	// For blocklist mode: returns (true, reason, nil) if request VIOLATES the limit (should be blocked)
	Evaluate(ctx context.Context, rule *types.Rule, req *types.SignRequest, parsed *types.ParsedPayload) (bool, string, error)
}

RuleEvaluator evaluates a specific rule type

type RuleGenerateOptions

type RuleGenerateOptions struct {
	RuleType types.RuleType `json:"rule_type"` // Required: evm_address_list, evm_contract_method, evm_value_limit
	RuleMode types.RuleMode `json:"rule_mode"` // Required: whitelist or blocklist
	RuleName string         `json:"rule_name"` // Optional: custom name, auto-generated if empty

	// For evm_value_limit: explicit max_value (required for this type)
	MaxValue *string `json:"max_value,omitempty"`
}

RuleGenerateOptions specifies how to generate a rule from an approved request

func (*RuleGenerateOptions) Validate

func (o *RuleGenerateOptions) Validate() error

Validate validates the rule generation options

type RuleGenerator

type RuleGenerator interface {
	// Preview generates a rule preview without saving (for user confirmation)
	Preview(req *types.SignRequest, parsed *types.ParsedPayload, opts *RuleGenerateOptions) (*types.Rule, error)

	// Generate creates and returns a rule (caller is responsible for saving)
	Generate(req *types.SignRequest, parsed *types.ParsedPayload, opts *RuleGenerateOptions) (*types.Rule, error)

	// SupportedTypes returns the rule types this generator can create
	SupportedTypes() []types.RuleType
}

RuleGenerator generates rules from approved transactions

type SignTypeApplicable

type SignTypeApplicable interface {
	// AppliesToSignType returns false if the rule does not apply to the given sign type (e.g. sign_type_filter mismatch).
	AppliesToSignType(rule *types.Rule, signType string) bool
}

SignTypeApplicable is an optional interface for evaluators that restrict by sign_type. When implemented, the engine filters out rules that don't apply to the request's sign type before calling Evaluate, avoiding unnecessary evaluator calls and config parsing.

type WhitelistRuleEngine

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

WhitelistRuleEngine implements RuleEngine with two-tier evaluation: 1. Blocklist rules (mandatory): ANY violation = blocked immediately 2. Whitelist rules (permissive): ANY match = allowed

Security: Blocklist rules use mandatory Fail-Closed behavior - any blocklist evaluation error results in immediate request rejection. This prevents attackers from bypassing blocklist rules by causing evaluation failures.

Whitelist rules use Fail-Open behavior - if a whitelist rule evaluation fails, it's skipped and the next whitelist rule is evaluated. This ensures that one failing whitelist rule doesn't prevent other valid whitelist rules from matching.

func NewWhitelistRuleEngine

func NewWhitelistRuleEngine(repo storage.RuleRepository, logger *slog.Logger, opts ...RuleEngineOption) (*WhitelistRuleEngine, error)

NewWhitelistRuleEngine creates a new two-tier rule engine

func (*WhitelistRuleEngine) Evaluate

Evaluate performs two-tier rule evaluation

func (*WhitelistRuleEngine) EvaluateWithResult

func (e *WhitelistRuleEngine) EvaluateWithResult(ctx context.Context, req *types.SignRequest, parsed *types.ParsedPayload) (*EvaluationResult, error)

EvaluateWithResult returns detailed evaluation result

func (*WhitelistRuleEngine) RegisterEvaluator

func (e *WhitelistRuleEngine) RegisterEvaluator(evaluator RuleEvaluator)

RegisterEvaluator registers a rule evaluator for a specific rule type

Jump to

Keyboard shortcuts

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