ruleengine

package
v0.3.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 15 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 ruleengine is codefit's own matcher for a subset of the Semgrep rule format (PRD section 17). It is the TYPESCRIPT provider's detection mechanism, not the cross-language architecture: each language owns its detector, and what is shared across languages is the neutral model and the namematch vocabulary (ADR 0083). The pattern syntax itself is TypeScript-shaped — a metavariable is an ordinary TS identifier spelled "$X" — so patterns do not port to grammars where that is not a legal identifier. Deterministic detection rules are written as declarative YAML (the de-facto standard, with a large community corpus) and matched in pure Go over the provider's AST — the OCaml Semgrep/OpenGrep engine is NOT embedded, which would break the single, CGO-free binary.

Supported operators (the core subset): pattern, pattern-either, pattern-not, pattern-inside, metavariables ($VAR), metavariable-regex, plus two of codefit's own that Semgrep does not have: metavariable-name (match an identifier by name component against a closed vocabulary — see [metavarname] in matcher.go) and metavariable-value-veto (drop a match whose bound string literal proves, by its own shape, that it is something else — see [valueveto] in valueveto.go). Object patterns also accept one scoped ellipsis, spelled `...$REST` (see [objectsubset] in matcher.go). The YAML loader rejects any key it does not know, so a misspelled operator fails the load instead of being dropped. The `patterns` (AND) operator is DECLARED in the Rule shape but compiled by nothing — a rule using it alongside `pattern` loads and silently drops the conjunction. Listed here as absent rather than supported, so the doc stops promising it (found while gating unparsable patterns, PR #173). Deliberately NOT supported: taint mode and pattern-sources/sinks/sanitizers — their role is covered by the agent reasoning over mapped surface.

Status: BUILT (Fase 1). The rule shape (Rule), the YAML loader, and the matcher itself (Compile, Match, Matches) are implemented, and the TypeScript provider runs its deterministic security rules through them. Note the shape: the matcher is package-level FUNCTIONS over syntax.Node, not the Engine interface — Engine is a declared contract that nothing implements today, kept for the per-language adapter it was drawn for. Do not read it as the entry point.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Match

func Match(rules []CompiledRule, root syntax.Node, file string) []findings.Finding

Match runs the compiled rules over the tree rooted at root and returns the findings, located by file and line. file is the project-relative path.

func Matches

func Matches(pattern, code syntax.Node) (map[string]string, bool)

Matches reports whether the (already-parsed) pattern node matches the code node structurally, returning the metavariable bindings (name -> matched source text). It is the core of the matcher and is exported so each operator can be tested against real trees.

Matching is purely structural: a metavariable matches any node (and binds, consistently across repeats); otherwise node types must be equal, the node's own literal tokens must agree (its [skeleton], which is what makes an operator visible), and named children must match pairwise; leaves compare by text.

Semgrep's general ellipsis is deliberately NOT supported. Objects are the one scoped exception — see [objectsubset] — and it is opt-in per pattern, so a pattern that does not ask for it matches exactly as described above.

Types

type CompiledRule

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

CompiledRule is a Rule whose pattern strings have been parsed to syntax.Node (once, at load time) and whose metavariable regexes are compiled. The ruleengine never parses source itself — Compile receives a parse function from the active provider, so the engine stays parser-agnostic.

func Compile

func Compile(rules []Rule, parse func(src string) (syntax.Node, error)) ([]CompiledRule, error)

Compile parses each rule's pattern(s) via parse (a provider's parser, which emits syntax.Node) and compiles the metavariable regexes.

Compilation is strict and located, the same contract LoadFS enforces on the YAML: a pattern that does not parse fails the whole compile with an error naming the rule id, the operator, and the offending pattern text. It is not enough to trust parse's error — see [compilePattern] for why a nil error does not mean the pattern parsed.

type Engine

type Engine interface {
	// Match runs the rules against a parsed AST and returns the findings.
	Match(rules []Rule, ast any) ([]findings.Finding, error)
}

Engine matches rules against a parsed file and emits deterministic findings.

NOT IMPLEMENTED by anything today: the working matcher is the package-level Compile/Match pair over syntax.Node. This interface is kept for the per-language AST adapter it was drawn for, which is why its ast argument is still abstract (any).

type Rule

type Rule struct {
	ID         string             `yaml:"id"`
	Message    string             `yaml:"message"`
	Suggestion string             `yaml:"suggestion"`
	Severity   findings.Severity  `yaml:"severity"`
	Dimension  findings.Dimension `yaml:"dimension"`

	// Operators (core subset). Exactly the set codefit's matcher supports.
	Pattern           string            `yaml:"pattern,omitempty"`
	PatternEither     []string          `yaml:"pattern-either,omitempty"`
	Patterns          []string          `yaml:"patterns,omitempty"`
	PatternNot        string            `yaml:"pattern-not,omitempty"`
	PatternInside     string            `yaml:"pattern-inside,omitempty"`
	MetavariableRegex map[string]string `yaml:"metavariable-regex,omitempty"`
	// MetavariableName constrains a metavariable by NAME COMPONENT against a
	// named vocabulary (today: "credential"), which a regex cannot express —
	// RE2 has no lookbehind, so "token" cannot be anchored to a camelCase
	// boundary. See [metavarname] in matcher.go.
	MetavariableName map[string]string `yaml:"metavariable-name,omitempty"`
	// MetavariableValueVeto drops a match when the VALUE bound to a
	// metavariable proves, by its own shape, that it is something the rule is
	// not about (today: "not-a-credential", internal/core/valueshape). See
	// [valueveto] in valueveto.go.
	MetavariableValueVeto map[string]string `yaml:"metavariable-value-veto,omitempty"`
}

Rule is a deterministic detection rule in the supported Semgrep-format subset (PRD section 17). A rule carries its finding metadata plus one or more pattern operators; the operators are mutually composable (patterns = AND of its members, PatternEither = OR, etc.).

func LoadFS

func LoadFS(fsys fs.FS, dir string) ([]Rule, error)

LoadFS reads and validates every *.yaml rule file under dir in fsys and returns the rules in a stable, file-sorted order. fsys is supplied by the caller (the embedded rules/ FS in production, an in-memory FS in tests), so the engine never reaches the real filesystem itself.

Validation is strict and located: a malformed file or a structurally invalid rule fails with an error naming the file (and the rule id when known), so a broken rule can never enter the engine silently — a silent rule is a silent vulnerability.

Decoding is strict too: an unknown key is an error, not a key to skip. See [decodeRuleFile] for why.

Jump to

Keyboard shortcuts

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