Files

246 lines
7.1 KiB
Go

package audit
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
)
// The default lens ships inside the binary so `auditor check` works with no
// configuration. It is the same file an operator can point --rules at, and it is
// the single source of truth for both the engine and docs/RULES.md.
//
//go:embed lens.json
var defaultLens []byte
// Axis is the question a rule speaks to.
const (
AxisLegitimacy = "legitimacy" // trustworthy as produced: no deception, no unauthorised action, no payload
AxisValidity = "validity" // conforms to the declared contract
AxisRecord = "record" // the call record itself is intact and attributable
)
// Kind separates proof from suspicion. A violation is a proven defect present in
// the bundle; a signal is a heuristic that requires a human to judge. Only
// violations can produce a negative verdict on their own.
const (
KindViolation = "violation"
KindSignal = "signal"
)
// Severity is the impact of a hit, not the confidence in it.
const (
SevP0 = "P0"
SevP1 = "P1"
SevP2 = "P2"
)
// Rule is one entry in the lens.
type Rule struct {
ID string `json:"id"`
Title string `json:"title"`
Axis string `json:"axis"`
Severity string `json:"severity"`
Kind string `json:"kind"`
// Rationale is the mechanism: why a hit matters. Copied into findings.
Rationale string `json:"rationale"`
// Remediation is what to do about a hit.
Remediation string `json:"remediation"`
// Limits states what the rule does not cover, so the lens is not
// mistaken for a guarantee.
Limits string `json:"limits,omitempty"`
Check Check `json:"check"`
}
// Check binds a rule to a primitive and its parameters.
type Check struct {
Primitive string `json:"primitive"`
Params json.RawMessage `json:"params,omitempty"`
}
// Checker is a prepared primitive: parameters already decoded and compiled, so
// parameter errors surface at corpus-load time, not mid-audit.
type Checker interface {
run(*evalContext) Result
}
// constructor decodes and validates one primitive's parameters.
type constructor func(json.RawMessage) (Checker, error)
var registry = map[string]constructor{
"text_match": newTextMatch,
"hidden_text": newHiddenText,
"secret_like": newSecretLike,
"link_hygiene": newLinkHygiene,
"tool_calls": newToolCalls,
"tool_arguments": newToolArguments,
"schema_conformance": newSchemaConformance,
"contract_terms": newContractTerms,
"grounded_claims": newGroundedClaims,
"record_completeness": newRecordCompleteness,
"request_hash_mismatch": newRequestHash,
}
// Primitives lists the registered primitive names, for docs and error messages.
func Primitives() []string {
names := make([]string, 0, len(registry))
for name := range registry {
names = append(names, name)
}
sort.Strings(names)
return names
}
// DefaultRules parses the embedded lens.
func DefaultRules() ([]Rule, error) {
return ParseRules(defaultLens)
}
// LoadRules reads a lens from a path, or from stdin when path is "-".
func LoadRules(path string) ([]Rule, error) {
if path == "" {
return DefaultRules()
}
if path == "-" {
data, err := io.ReadAll(os.Stdin)
if err != nil {
return nil, fmt.Errorf("read rules from stdin: %w", err)
}
return ParseRules(data)
}
// The path comes from the operator running the auditor, not from the bundle.
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read rules %s: %w", path, err)
}
return ParseRules(data)
}
// ParseRules decodes and fully validates a lens, including preparing every
// primitive so that bad parameters and bad regexes fail here.
func ParseRules(data []byte) ([]Rule, error) {
dec := json.NewDecoder(strings.NewReader(string(data)))
dec.DisallowUnknownFields()
var rules []Rule
if err := dec.Decode(&rules); err != nil {
return nil, fmt.Errorf("decode rules: %w", err)
}
var extra any
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
return nil, errors.New("trailing data after rules")
}
if err := ValidateRules(rules); err != nil {
return nil, err
}
return rules, nil
}
// ValidateRules checks the lens itself. A lens that cannot be trusted produces
// false confidence, so this is a first-class operation, exposed as
// `auditor validate`.
func ValidateRules(rules []Rule) error {
if len(rules) == 0 {
return errors.New("lens is empty")
}
seen := make(map[string]bool, len(rules))
var errs []string
for i, r := range rules {
var problems []string
switch {
case r.ID == "":
problems = append(problems, "id is required")
case seen[r.ID]:
problems = append(problems, "duplicate id")
}
seen[r.ID] = true
if r.Title == "" {
problems = append(problems, "title is required")
}
if !oneOf(r.Axis, AxisLegitimacy, AxisValidity, AxisRecord) {
problems = append(problems, fmt.Sprintf("axis %q must be one of legitimacy, validity, record", r.Axis))
}
if !oneOf(r.Severity, SevP0, SevP1, SevP2) {
problems = append(problems, fmt.Sprintf("severity %q must be one of P0, P1, P2", r.Severity))
}
if !oneOf(r.Kind, KindViolation, KindSignal) {
problems = append(problems, fmt.Sprintf("kind %q must be one of violation, signal", r.Kind))
}
if r.Rationale == "" {
problems = append(problems, "rationale is required: a finding needs a mechanism")
}
if r.Remediation == "" {
problems = append(problems, "remediation is required")
}
build, ok := registry[r.Check.Primitive]
if !ok {
problems = append(problems, fmt.Sprintf("unknown primitive %q (have %s)", r.Check.Primitive, strings.Join(Primitives(), ", ")))
} else if _, err := build(r.Check.Params); err != nil {
problems = append(problems, fmt.Sprintf("primitive %q: %v", r.Check.Primitive, err))
}
if len(problems) > 0 {
id := r.ID
if id == "" {
id = fmt.Sprintf("#%d", i)
}
errs = append(errs, fmt.Sprintf("rule %s: %s", id, strings.Join(problems, "; ")))
}
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
}
// Prepare compiles each rule's primitive against the corpus.
func Prepare(rules []Rule) ([]preparedRule, error) {
out := make([]preparedRule, 0, len(rules))
for _, r := range rules {
build, ok := registry[r.Check.Primitive]
if !ok {
return nil, fmt.Errorf("rule %s: unknown primitive %q", r.ID, r.Check.Primitive)
}
c, err := build(r.Check.Params)
if err != nil {
return nil, fmt.Errorf("rule %s: %w", r.ID, err)
}
out = append(out, preparedRule{Rule: r, checker: c})
}
return out, nil
}
type preparedRule struct {
Rule
checker Checker
}
func oneOf(v string, allowed ...string) bool {
for _, a := range allowed {
if v == a {
return true
}
}
return false
}
// decodeParams decodes a rule's raw params into its parameter struct. It is
// strict: a misspelled parameter is an error, not a silently ignored no-op.
func decodeParams(raw json.RawMessage, dst any) error {
if len(raw) == 0 {
return nil
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return fmt.Errorf("params: %w", err)
}
return nil
}