package judgement import ( "context" "encoding/json/jsontext" json "encoding/json/v2" "fmt" "strings" "github.com/google/uuid" ) // Events says where a run came from. The events module implements it, so the // guard never reads another module's tables. type Events interface { // Provenance reports whether a verified source started the run, and the // free text that source's event carried. A run no event started is not // verified. Provenance(ctx context.Context, runID uuid.UUID) (verified bool, untrusted []string, err error) } // Provenance holds a changing action when nobody verified who asked, or when // text a stranger wrote has found its way into the action's input. type Provenance struct { Events Events } // Name is the guard's name in verdicts. func (Provenance) Name() string { return "provenance" } // Advisory is false. func (Provenance) Advisory() bool { return false } // minOverlap is the shortest input text worth comparing with untrusted text. const minOverlap = 8 // Judge returns the provenance ceiling. Reading changes nothing a stranger // could steer, so it passes. func (p Provenance) Judge(ctx context.Context, a Action) (Verdict, error) { if a.Effect.ReadOnly { return Verdict{Ceiling: ActQuietly}, nil } verified, untrusted, err := p.Events.Provenance(ctx, runFrom(ctx).RunID) if err != nil { return Verdict{}, fmt.Errorf("read run provenance: %w", err) } var findings []Finding if !verified { findings = append(findings, Finding{Text: "no verified source started this run"}) } if text, ok := carriesUntrusted(a.Input, untrusted); ok { findings = append(findings, Finding{Text: "the action's input carries untrusted text from the event", Evidence: text}) } if len(findings) > 0 { return Verdict{Ceiling: ProposeAndWait, Findings: findings}, nil } return Verdict{Ceiling: ActQuietly}, nil } // carriesUntrusted reports whether a phrase in input (text with a space in it, // so not an identifier or a path) overlaps text the event carried, and returns // that phrase. func carriesUntrusted(input jsontext.Value, untrusted []string) (string, bool) { if len(untrusted) == 0 || len(input) == 0 { return "", false } var v any if err := json.Unmarshal(input, &v); err != nil { return string(input), true } var found string walkStrings(v, func(s string) { if found != "" || len(s) < minOverlap || !strings.ContainsAny(s, " \t\n") { return } for _, u := range untrusted { if strings.Contains(s, u) || strings.Contains(u, s) { found = s return } } }) return found, found != "" } func walkStrings(v any, fn func(string)) { switch x := v.(type) { case string: fn(x) case []any: for _, e := range x { walkStrings(e, fn) } case map[string]any: for _, e := range x { walkStrings(e, fn) } } }