Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions internal/service/rules/preview.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package rules

import (
"context"
"sort"
"time"

"github.com/google/uuid"
"gorm.io/gorm"
)

// Preview bounds: a preview (the rule dry run of docs/effectors/user-interface.md) evaluates
// at most MaxSubjects subjects and lists at most the other limits.
const (
DefaultPreviewMaxSubjects = 10000
DefaultPreviewMaxListed = 100
DefaultPreviewMaxErrors = 100
DefaultPreviewMaxTargets = 100
)

// previewPageSize is how many subjects a preview loads at a time.
const previewPageSize = 500

// PreviewOptions bound a preview; zero values take the defaults.
type PreviewOptions struct {
MaxSubjects, MaxListed, MaxErrors, MaxTargets int
}

func (o PreviewOptions) withDefaults() PreviewOptions {
if o.MaxSubjects <= 0 {
o.MaxSubjects = DefaultPreviewMaxSubjects
}
if o.MaxListed <= 0 {
o.MaxListed = DefaultPreviewMaxListed
}
if o.MaxErrors <= 0 {
o.MaxErrors = DefaultPreviewMaxErrors
}
if o.MaxTargets <= 0 {
o.MaxTargets = DefaultPreviewMaxTargets
}
return o
}

// PreviewResult is a rule evaluated against the source's subjects without saving anything.
type PreviewResult struct {
// Evaluated is how many subjects were evaluated; Matched how many match now.
Evaluated, Matched int
// Truncated: the source has more subjects than the preview evaluates.
Truncated bool
// Subjects are the first matching subjects, up to MaxListed.
Subjects []*EvidenceSubject
// Documents are every matching subject by ID, for building effect documents.
Documents map[string]*EvidenceSubject
// Actions are per action, in plan order.
Actions []PreviewAction
// Errors are evaluation errors, up to MaxErrors.
Errors []PreviewError
}

// PreviewAction is what one action resolves the matching subjects to.
type PreviewAction struct {
// Targets are by identity, sorted, up to MaxTargets.
Targets []PreviewTarget
// TargetsTruncated: more targets than listed.
TargetsTruncated bool
// NoTarget counts matching subjects the action resolved to nothing (and rejected nothing).
NoTarget int
}

// PreviewTarget is one identity and the matching subjects (IDs) that resolve to it.
type PreviewTarget struct {
Identity string
Subjects []string
// Reason is why the effector action rejects the identity; empty when it's allowed.
Reason string
}

// Allowed reports whether the effector action accepts the identity.
func (t PreviewTarget) Allowed() bool { return t.Reason == "" }

// PreviewError is one evaluation error.
type PreviewError struct {
SubjectID string
// ActionIndex is the action whose target failed; nil for when.
ActionIndex *int
Expression string
Error string
}

// Preview evaluates when and the actions' targets against the source's subjects, as
// rules.evaluate-subject would now, without writing anything. Errors are collected like
// EvaluateSubject's: a failing when is no match, a failing target no target.
func Preview(ctx context.Context, db *gorm.DB, when *Compiled, plans []ActionPlan, now time.Time, opts PreviewOptions) (*PreviewResult, error) {
opts = opts.withDefaults()
res := &PreviewResult{
Subjects: []*EvidenceSubject{},
Documents: map[string]*EvidenceSubject{},
Actions: make([]PreviewAction, len(plans)),
Errors: []PreviewError{},
}
byTarget := make([]map[string]*PreviewTarget, len(plans))
for i := range byTarget {
byTarget[i] = map[string]*PreviewTarget{}
}
addTarget := func(i int, identity, reason, subjectID string) {
t := byTarget[i][identity]
if t == nil {
t = &PreviewTarget{Identity: identity, Reason: reason}
byTarget[i][identity] = t
}
t.Subjects = append(t.Subjects, subjectID)
}
addError := func(subjectID string, actionIndex *int, expr string, err error) {
if len(res.Errors) < opts.MaxErrors {
res.Errors = append(res.Errors, PreviewError{SubjectID: subjectID, ActionIndex: actionIndex, Expression: expr, Error: err.Error()})
}
}

after := uuid.Nil
for !res.Truncated {
page, err := EvidenceStreamPage(ctx, db, after, previewPageSize)
if err != nil {
return nil, err
}
if len(page) == 0 {
break
}
after = page[len(page)-1]
docs, err := EvidenceSubjects(ctx, db, page)
if err != nil {
return nil, err
}
for _, id := range page {
doc := docs[id]
if doc == nil {
continue
}
if res.Evaluated >= opts.MaxSubjects {
res.Truncated = true
break
}
res.Evaluated++
sr := EvaluateSubject(when, plans, doc, now)
if sr.WhenErr != nil {
addError(doc.ID, nil, when.Expr, sr.WhenErr)
continue
}
if !sr.Matched {
continue
}
res.Matched++
res.Documents[doc.ID] = doc
if len(res.Subjects) < opts.MaxListed {
res.Subjects = append(res.Subjects, doc)
}
for i, ar := range sr.Actions {
if ar.Err != nil {
idx := i
addError(doc.ID, &idx, targetExpr(plans[i]), ar.Err)
}
if len(ar.Targets) == 0 && len(ar.Invalid) == 0 {
res.Actions[i].NoTarget++
}
for _, t := range ar.Targets {
addTarget(i, t, "", doc.ID)
}
for _, inv := range ar.Invalid {
addTarget(i, inv.Identity, inv.Reason, doc.ID)
}
}
}
if len(page) < previewPageSize {
break
}
}

for i := range plans {
identities := make([]string, 0, len(byTarget[i]))
for identity := range byTarget[i] {
identities = append(identities, identity)
}
sort.Strings(identities)
if len(identities) > opts.MaxTargets {
identities = identities[:opts.MaxTargets]
res.Actions[i].TargetsTruncated = true
}
res.Actions[i].Targets = make([]PreviewTarget, 0, len(identities))
for _, identity := range identities {
res.Actions[i].Targets = append(res.Actions[i].Targets, *byTarget[i][identity])
}
}
return res, nil
}

// targetExpr is the expression an action's targets come from: its CEL target, or its fixed
// identity.
func targetExpr(plan ActionPlan) string {
switch {
case plan.Target != nil:
return plan.Target.Expr
case plan.Action.TargetExpr != nil:
return *plan.Action.TargetExpr
case plan.Action.TargetIdentity != nil:
return *plan.Action.TargetIdentity
}
return ""
}
140 changes: 140 additions & 0 deletions internal/service/rules/preview_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//go:build integration

package rules_test

import (
"context"
"time"

"github.com/compliance-framework/api/internal/service/relational"
"github.com/compliance-framework/api/internal/service/relational/effectors"
"github.com/compliance-framework/api/internal/service/rules"
"github.com/compliance-framework/api/sdk/types"
oscalTypes_1_1_3 "github.com/defenseunicorns/go-oscal/src/types/oscal-1-1-3"
"github.com/google/uuid"
"gorm.io/datatypes"
)

func (s *RulesSuite) collect(owner, status string) uuid.UUID {
stream := uuid.New()
labels := []relational.Labels{}
if owner != "" {
labels = append(labels, relational.Labels{Name: "owner", Value: owner})
}
s.Require().NoError(s.DB.Create(&relational.Evidence{
UUID: stream, Title: "stream " + owner, Start: time.Now().Add(-time.Minute), End: time.Now(),
Status: datatypes.NewJSONType(oscalTypes_1_1_3.ObjectiveStatus{State: status}),
Labels: labels,
}).Error)
return stream
}

func (s *RulesSuite) compile(kind, expr string) *rules.Compiled {
env, err := rules.NewEvidenceEnv(0)
s.Require().NoError(err)
c, err := env.Compile(kind, expr)
s.Require().NoError(err)
return c
}

func (s *RulesSuite) TestPreview() {
alice1 := s.collect("UALICE", "not-satisfied")
alice2 := s.collect("UALICE", "not-satisfied")
bob := s.collect("bob", "not-satisfied") // rejected by the value pattern
noOwner := s.collect("", "not-satisfied") // the target fails
s.collect("UCAROL", "satisfied") // doesn't match
broken := s.collect("UDAVE", "error") // when fails on it

registered := &effectors.EffectorAction{
Name: "notify-owner",
Targets: datatypes.NewJSONType(types.EffectorActionTargets{Include: []string{"slack-user:*"}}),
TargetSchemes: datatypes.NewJSONSlice([]types.EffectorTargetScheme{{Name: "slack-user", ValuePattern: "U[A-Z0-9]+"}}),
}
fixed := "slack-channel:#platform"
plans := []rules.ActionPlan{
{Target: s.compile(rules.ExprTarget, `"slack-user:" + subject.labels["owner"]`), Registered: registered},
{Action: effectors.RuleAction{TargetIdentity: &fixed}},
}
when := s.compile(rules.ExprWhen, `subject.status == "error" ? subject.labels["missing"] == "x" : subject.status == "not-satisfied"`)

res, err := rules.Preview(context.Background(), s.DB, when, plans, time.Now(), rules.PreviewOptions{})
s.Require().NoError(err)
s.Equal(6, res.Evaluated)
s.Equal(4, res.Matched)
s.False(res.Truncated)
s.Len(res.Subjects, 4)
s.Len(res.Documents, 4)
s.Contains(res.Documents, alice1.String())

owner := res.Actions[0]
s.Require().Len(owner.Targets, 2)
s.Equal("slack-user:UALICE", owner.Targets[0].Identity)
s.True(owner.Targets[0].Allowed())
s.ElementsMatch([]string{alice1.String(), alice2.String()}, owner.Targets[0].Subjects)
s.Equal("slack-user:bob", owner.Targets[1].Identity)
s.False(owner.Targets[1].Allowed())
s.Contains(owner.Targets[1].Reason, "must match")
s.Equal([]string{bob.String()}, owner.Targets[1].Subjects)
s.Equal(1, owner.NoTarget, "the stream without an owner")

channel := res.Actions[1]
s.Require().Len(channel.Targets, 1)
s.Equal(fixed, channel.Targets[0].Identity)
s.Len(channel.Targets[0].Subjects, 4)
s.Zero(channel.NoTarget)

s.Require().Len(res.Errors, 2)
bySubject := map[string]rules.PreviewError{}
for _, e := range res.Errors {
bySubject[e.SubjectID] = e
}
whenErr := bySubject[broken.String()]
s.Nil(whenErr.ActionIndex)
s.Equal(when.Expr, whenErr.Expression)
s.Contains(whenErr.Error, "no such key")
targetErr := bySubject[noOwner.String()]
s.Require().NotNil(targetErr.ActionIndex)
s.Equal(0, *targetErr.ActionIndex)
s.Equal(plans[0].Target.Expr, targetErr.Expression)

// Nothing is written.
var matches, ruleErrors int64
s.Require().NoError(s.DB.Model(&effectors.RuleSubjectMatch{}).Count(&matches).Error)
s.Require().NoError(s.DB.Model(&effectors.RuleError{}).Count(&ruleErrors).Error)
s.Zero(matches)
s.Zero(ruleErrors)
}

func (s *RulesSuite) TestPreviewLimits() {
for range 5 {
s.collect("UALICE", "not-satisfied")
}
s.collect("UBOB", "not-satisfied")
plans := []rules.ActionPlan{{Target: s.compile(rules.ExprTarget, `["slack-user:" + subject.labels["owner"], "slack-user:" + subject.id.upperAscii().replace("-", "")]`)}}
when := s.compile(rules.ExprWhen, `subject.labels["nope"] == "x" || true`)

res, err := rules.Preview(context.Background(), s.DB, when, plans, time.Now(), rules.PreviewOptions{MaxSubjects: 4, MaxListed: 2, MaxErrors: 1, MaxTargets: 3})
s.Require().NoError(err)
s.Equal(4, res.Evaluated)
s.True(res.Truncated)
s.Len(res.Subjects, 2)
s.Len(res.Documents, 4, "every matching subject's document is kept")
s.Len(res.Actions[0].Targets, 3)
s.True(res.Actions[0].TargetsTruncated)
s.Empty(res.Errors)

// The error limit.
res, err = rules.Preview(context.Background(), s.DB, s.compile(rules.ExprWhen, `subject.labels["nope"] == "x"`), nil, time.Now(), rules.PreviewOptions{MaxErrors: 1})
s.Require().NoError(err)
s.Equal(6, res.Evaluated)
s.Zero(res.Matched)
s.Len(res.Errors, 1)

// No subjects at all.
s.Require().NoError(s.Migrator.Refresh())
res, err = rules.Preview(context.Background(), s.DB, when, plans, time.Now(), rules.PreviewOptions{})
s.Require().NoError(err)
s.Zero(res.Evaluated)
s.Empty(res.Actions[0].Targets)
s.NotNil(res.Actions[0].Targets)
}