diff --git a/internal/service/effector/registration_integration_test.go b/internal/service/effector/registration_integration_test.go new file mode 100644 index 00000000..215e667c --- /dev/null +++ b/internal/service/effector/registration_integration_test.go @@ -0,0 +1,263 @@ +//go:build integration + +package effector + +import ( + "context" + "encoding/json" + "sync" + "testing" + "time" + + "github.com/compliance-framework/api/internal/service/relational" + "github.com/compliance-framework/api/internal/service/relational/agentcfg" + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/compliance-framework/api/internal/tests" + "github.com/compliance-framework/api/sdk/types" + "github.com/google/uuid" + "github.com/stretchr/testify/suite" + "gorm.io/datatypes" +) + +func TestRegistrationIntegration(t *testing.T) { + suite.Run(t, new(RegistrationSuite)) +} + +// recordingJobs records the verifications registration enqueues. +type recordingJobs struct { + mu sync.Mutex + verify []uuid.UUID +} + +func (j *recordingJobs) EnqueueEffectorVerify(_ context.Context, agentID uuid.UUID) error { + j.mu.Lock() + defer j.mu.Unlock() + j.verify = append(j.verify, agentID) + return nil +} + +func (j *recordingJobs) count() int { + j.mu.Lock() + defer j.mu.Unlock() + return len(j.verify) +} + +type RegistrationSuite struct { + tests.IntegrationTestSuite + signer *Signer + jobs *recordingJobs + svc *Service + agent uuid.UUID + instance uuid.UUID +} + +func (s *RegistrationSuite) SetupTest() { + s.Require().NoError(s.Migrator.Refresh()) + s.signer = NewSigner(newKey(s.T()), nil) + s.jobs = &recordingJobs{} + s.svc = s.newService(agentcfg.Settings{}) + agent, err := s.CreateAgent("platform-notify") + s.Require().NoError(err) + s.agent = *agent.ID + s.instance = uuid.New() +} + +func (s *RegistrationSuite) newService(settings agentcfg.Settings) *Service { + return NewService(s.DB, s.Config, s.signer, s.jobs, agentcfg.NewService(s.DB, settings, nil), nil) +} + +func (s *RegistrationSuite) setBaseURL(url, status string) { + s.Require().NoError(s.DB.Save(&effectors.AgentEffector{AgentID: s.agent, BaseURL: url, Status: status}).Error) +} + +func (s *RegistrationSuite) register(reg types.EffectorRegistration) (*types.EffectorRegistrationResult, error) { + return s.svc.Register(context.Background(), s.agent, nil, s.instance, reg) +} + +func (s *RegistrationSuite) TestRegistration() { + reg := notifyRegistration("https://agent.example:443/") + + // No base URL set: a mismatch, but the actions are stored and the instance row exists. + _, err := s.register(reg) + s.ErrorIs(err, ErrBaseURLMismatch) + var actions []effectors.EffectorAction + s.Require().NoError(s.DB.Where("agent_id = ?", s.agent).Find(&actions).Error) + s.Require().Len(actions, 1) + s.Equal("notify-owner", actions[0].Name) + s.Equal([]string{"slack-user:*"}, actions[0].Targets.Data().Include) + var inst relational.AgentInstance + s.Require().NoError(s.DB.Where("agent_id = ? AND instance_id = ?", s.agent, s.instance).First(&inst).Error) + + // A different base URL: a mismatch. + s.setBaseURL("https://other.example", effectors.AgentEffectorPendingVerify) + _, err = s.register(reg) + s.ErrorIs(err, ErrBaseURLMismatch) + s.Zero(s.jobs.count()) + + // The matching URL (after normalisation): the revision and keys, verification enqueued. + s.setBaseURL("https://agent.example", effectors.AgentEffectorPendingVerify) + res, err := s.register(reg) + s.Require().NoError(err) + s.Equal(int64(1), res.Revision) + s.Equal(s.signer.DeliveryKeys(), res.DeliveryKeys) + s.Equal(1, s.jobs.count()) + + // Idempotent; a changed body bumps the revision. + res, err = s.register(reg) + s.Require().NoError(err) + s.Equal(int64(1), res.Revision) + reg.Actions[0].Description = "changed" + res, err = s.register(reg) + s.Require().NoError(err) + s.Equal(int64(2), res.Revision) + + // Verified with the current key: no more verification. + kid := s.signer.CurrentKid() + s.Require().NoError(s.DB.Model(&effectors.AgentEffector{}).Where("agent_id = ?", s.agent). + Updates(map[string]any{"status": effectors.AgentEffectorReady, "verified_kid": kid}).Error) + before := s.jobs.count() + _, err = s.register(reg) + s.Require().NoError(err) + s.Equal(before, s.jobs.count()) + // A key rotation (another current key): verified again. + s.svc.signer = NewSigner(newKey(s.T()), nil) + _, err = s.register(reg) + s.Require().NoError(err) + s.Equal(before+1, s.jobs.count()) + + // An invalid body stores nothing. + bad := notifyRegistration("https://agent.example") + bad.Actions[0].OnClear = "explode" + bad.Actions[0].Name = "other" + _, err = s.register(bad) + var verr *ValidationError + s.Require().ErrorAs(err, &verr) + s.Contains(verr.Fields, "actions[0].on-clear") + s.Require().NoError(s.DB.Where("agent_id = ?", s.agent).Find(&actions).Error) + s.Equal("notify-owner", actions[0].Name) + + // A base URL that isn't one. + _, err = s.register(notifyRegistration("ftp://agent.example")) + s.Require().ErrorAs(err, &verr) + s.Contains(verr.Fields, "base-url") +} + +// At the agent's instance cap (every counted instance fresh), a new instance can't register. +func (s *RegistrationSuite) TestInstanceCap() { + s.setBaseURL("https://agent.example", effectors.AgentEffectorReady) + s.svc = s.newService(agentcfg.Settings{MaxInstancesPerAgent: 1}) + _, err := s.register(notifyRegistration("https://agent.example")) + s.Require().NoError(err) + _, err = s.svc.Register(context.Background(), s.agent, nil, uuid.New(), notifyRegistration("https://agent.example")) + s.ErrorIs(err, agentcfg.ErrInstanceLimit) + // The registered instance can register again. + _, err = s.register(notifyRegistration("https://agent.example")) + s.NoError(err) +} + +func (s *RegistrationSuite) TestRegistrationParams() { + s.setBaseURL("https://agent.example", effectors.AgentEffectorReady) + reg := notifyRegistration("https://agent.example") + reg.Actions[0].Params = notifyParams() + _, err := s.register(reg) + s.Require().NoError(err) + var stored effectors.EffectorAction + s.Require().NoError(s.DB.Where("agent_id = ? AND name = ?", s.agent, "notify-owner").First(&stored).Error) + s.JSONEq(string(reg.Actions[0].Params.Schema), string(stored.Schema())) + locked, err := stored.Locked() + s.Require().NoError(err) + s.Equal([]string{"layout"}, locked) + defaults, err := effectors.DecodeParams(stored.ParamsDefaults) + s.Require().NoError(err) + s.Equal(map[string]any{"layout": "short"}, defaults) + + // Without params the columns stay null. + _, err = s.register(notifyRegistration("https://agent.example")) + s.Require().NoError(err) + var plain effectors.EffectorAction + s.Require().NoError(s.DB.Where("agent_id = ? AND name = ?", s.agent, "notify-owner").First(&plain).Error) + s.Nil(plain.Schema()) + locked, err = plain.Locked() + s.Require().NoError(err) + s.Empty(locked) + s.Nil(plain.ParamsDefaults) +} + +func (s *RegistrationSuite) ruleActionStatuses(ruleID uuid.UUID) []string { + var got []effectors.RuleAction + s.Require().NoError(s.DB.Where("rule_id = ?", ruleID).Order("target_identity").Find(&got).Error) + out := make([]string, 0, len(got)) + for _, a := range got { + out = append(out, a.Status) + } + return out +} + +// A rule action whose params stop matching the registered schema or locks turns degraded, +// and recovers once they match again. +func (s *RegistrationSuite) TestRegistrationDegradesMismatchedParams() { + s.setBaseURL("https://agent.example", effectors.AgentEffectorReady) + ua, ub := "slack-user:UA", "slack-user:UB" + rule := effectors.Rule{ + Name: "r", Source: effectors.SourceEvidence, Kind: effectors.RuleKindState, WhenExpr: "true", Enabled: true, + Actions: []effectors.RuleAction{ + {AgentID: s.agent, EffectorAction: "notify-owner", TargetIdentity: &ua, Status: effectors.RuleActionStatusOK, + Params: datatypes.JSON(`{"on":{"repeated":{"text":"again"}}}`)}, + {AgentID: s.agent, EffectorAction: "notify-owner", TargetIdentity: &ub, Status: effectors.RuleActionStatusOK}, + }, + } + s.Require().NoError(s.DB.Create(&rule).Error) + + reg := notifyRegistration("https://agent.example") + reg.Actions[0].Params = notifyParams() + _, err := s.register(reg) + s.Require().NoError(err) + s.Equal([]string{"ok", "ok"}, s.ruleActionStatuses(rule.ID)) + + // The schema drops on.repeated: the first action's params no longer match. + reg.Actions[0].Params.Schema = json.RawMessage(`{"type":"object","properties":{"layout":{"type":"string","enum":["short","detailed"]}}}`) + _, err = s.register(reg) + s.Require().NoError(err) + s.Equal([]string{"degraded", "ok"}, s.ruleActionStatuses(rule.ID)) + + // The schema comes back, but the operator locks everything the rule sets. + reg.Actions[0].Params = notifyParams() + reg.Actions[0].Params.Locked = []string{"*"} + _, err = s.register(reg) + s.Require().NoError(err) + s.Equal([]string{"degraded", "ok"}, s.ruleActionStatuses(rule.ID)) + + reg.Actions[0].Params = notifyParams() + _, err = s.register(reg) + s.Require().NoError(err) + s.Equal([]string{"ok", "ok"}, s.ruleActionStatuses(rule.ID)) +} + +// Registration re-checks the agent's rule actions: ok when a fresh instance registers the +// action, degraded when none does. +func (s *RegistrationSuite) TestRegistrationRechecksRuleActions() { + ua := "slack-user:UA" + rule := effectors.Rule{ + Name: "r", Source: effectors.SourceEvidence, Kind: effectors.RuleKindState, WhenExpr: "true", Enabled: true, + Actions: []effectors.RuleAction{ + {AgentID: s.agent, EffectorAction: "notify-owner", TargetIdentity: &ua, Status: effectors.RuleActionStatusDegraded}, + {AgentID: s.agent, EffectorAction: "gone", TargetIdentity: &ua, Status: effectors.RuleActionStatusOK}, + }, + } + s.Require().NoError(s.DB.Create(&rule).Error) + s.setBaseURL("https://agent.example", effectors.AgentEffectorReady) + _, err := s.register(notifyRegistration("https://agent.example")) + s.Require().NoError(err) + var got []effectors.RuleAction + s.Require().NoError(s.DB.Where("rule_id = ?", rule.ID).Order("effector_action").Find(&got).Error) + s.Require().Len(got, 2) + s.Equal("gone", got[0].EffectorAction) + s.Equal(effectors.RuleActionStatusDegraded, got[0].Status) + s.Equal(effectors.RuleActionStatusOK, got[1].Status) + + // The only instance goes stale: the re-check degrades the action. + s.svc.WithClock(func() time.Time { return time.Now().Add(24 * time.Hour) }) + s.Require().NoError(s.svc.RecheckRuleActions(context.Background(), s.DB, s.agent)) + s.Require().NoError(s.DB.Where("rule_id = ?", rule.ID).Order("effector_action").Find(&got).Error) + s.Equal(effectors.RuleActionStatusDegraded, got[1].Status) +} diff --git a/internal/service/effector/service.go b/internal/service/effector/service.go new file mode 100644 index 00000000..73d338ec --- /dev/null +++ b/internal/service/effector/service.go @@ -0,0 +1,277 @@ +package effector + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/compliance-framework/api/internal/config" + "github.com/compliance-framework/api/internal/service/relational/agentcfg" + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/compliance-framework/api/internal/service/rules" + "github.com/compliance-framework/api/pkg/effector/params" + "github.com/compliance-framework/api/pkg/effector/targets" + "github.com/compliance-framework/api/sdk/types" + "github.com/google/uuid" + "go.uber.org/zap" + "gorm.io/datatypes" + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +// ErrBaseURLMismatch: a registration's base URL differs from the one the admin set, or none +// is set (409). +var ErrBaseURLMismatch = errors.New("base URL mismatch") + +// Service stores agents' effector registrations and keeps their rule actions' status in +// line with them. +type Service struct { + db *gorm.DB + signer *Signer + jobs Jobs + instances *agentcfg.Service + staleAfter time.Duration + logger *zap.SugaredLogger + now func() time.Time +} + +// NewService builds the service. signer may be nil (effectors off: no delivery keys); jobs +// may be nil (verification isn't enqueued). +func NewService(db *gorm.DB, cfg *config.Config, signer *Signer, jobs Jobs, instances *agentcfg.Service, logger *zap.SugaredLogger) *Service { + if logger == nil { + logger = zap.NewNop().Sugar() + } + s := &Service{db: db, signer: signer, jobs: jobs, instances: instances, logger: logger, now: time.Now} + s.staleAfter = config.DefaultAgentsConfig().InstanceStaleAfter + if cfg != nil { + if cfg.Agents != nil && cfg.Agents.InstanceStaleAfter > 0 { + s.staleAfter = cfg.Agents.InstanceStaleAfter + } + } + return s +} + +// WithClock sets the clock (tests). +func (s *Service) WithClock(now func() time.Time) *Service { + s.now = now + return s +} + +// DeliveryKeys are the public delivery keys (empty when effectors are off). +func (s *Service) DeliveryKeys() []types.DeliveryKey { + return s.signer.DeliveryKeys() +} + +func (s *Service) enqueueVerify(ctx context.Context, agentID uuid.UUID) { + if s.jobs == nil { + return + } + if err := s.jobs.EnqueueEffectorVerify(ctx, agentID); err != nil { + s.logger.Warnw("Failed to enqueue effector verification", "agent_id", agentID, "error", err) + } +} + +// needsVerify reports whether an agent effector should be (re)verified: it's pending, or +// was verified with another key than the current one. +func (s *Service) needsVerify(ae *effectors.AgentEffector) bool { + if ae == nil || ae.BaseURL == "" || s.signer == nil { + return false + } + if ae.Status == effectors.AgentEffectorPendingVerify { + return true + } + return ae.Status != effectors.AgentEffectorNotSet && (ae.VerifiedKid == nil || *ae.VerifiedKid != s.signer.CurrentKid()) +} + +func (s *Service) agentEffector(ctx context.Context, db *gorm.DB, agentID uuid.UUID) (*effectors.AgentEffector, error) { + var ae effectors.AgentEffector + err := db.WithContext(ctx).First(&ae, "agent_id = ?", agentID).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + return &ae, nil +} + +// bodyDigest is the registration body's digest: the same body gets the same revision. +func bodyDigest(reg types.EffectorRegistration) (string, error) { + raw, err := json.Marshal(reg) + if err != nil { + return "", err + } + sum := sha256.Sum256(raw) + return "sha256:" + hex.EncodeToString(sum[:]), nil +} + +// Register stores an instance's effector registration (wire-interface.md, "Registration"). It validates the body (a +// *ValidationError), upserts the agent instance (agentcfg.ErrInstanceLimit at the cap), stores +// the instance's actions, re-checks the agent's rule actions, and compares the base URL with +// the admin's: on a mismatch the actions stay stored and ErrBaseURLMismatch is returned. While +// the agent's effector is pending verification it enqueues effector.verify. +func (s *Service) Register(ctx context.Context, agentID uuid.UUID, credentialID *uuid.UUID, instanceID uuid.UUID, reg types.EffectorRegistration) (*types.EffectorRegistrationResult, error) { + if err := ValidateRegistration(reg); err != nil { + return nil, err + } + var normalized string + if reg.BaseURL != "" { + n, err := targets.NormalizeBaseURL(reg.BaseURL) + if err != nil { + return nil, &ValidationError{Fields: map[string]any{"base-url": err.Error()}} + } + normalized = n + } + digest, err := bodyDigest(reg) + if err != nil { + return nil, err + } + if s.instances != nil { + if err := s.instances.TouchFromEffectorRegistration(ctx, agentID, credentialID, instanceID); err != nil { + return nil, err + } + } + + now := s.now().UTC() + var revision int64 + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + var inst effectors.AgentEffectorInstance + err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&inst, "agent_id = ? AND instance_id = ?", agentID, instanceID).Error + switch { + case errors.Is(err, gorm.ErrRecordNotFound): + revision = 1 + inst = effectors.AgentEffectorInstance{AgentID: agentID, InstanceID: instanceID, Revision: 1, BodyDigest: digest, Version: reg.Version, RegisteredAt: now} + if err := tx.Create(&inst).Error; err != nil { + return err + } + case err != nil: + return err + default: + revision = inst.Revision + if inst.BodyDigest != digest { + revision++ + } + if err := tx.Model(&effectors.AgentEffectorInstance{}).Where("agent_id = ? AND instance_id = ?", agentID, instanceID). + Updates(map[string]any{"revision": revision, "body_digest": digest, "version": reg.Version, "registered_at": now}).Error; err != nil { + return err + } + } + if err := tx.Where("agent_id = ? AND instance_id = ?", agentID, instanceID).Delete(&effectors.EffectorAction{}).Error; err != nil { + return err + } + rows := make([]effectors.EffectorAction, 0, len(reg.Actions)) + for _, a := range reg.Actions { + schema, defaults, locked, err := encodeActionParams(a.Params) + if err != nil { + return err + } + rows = append(rows, effectors.EffectorAction{ + ParamsSchema: schema, ParamsDefaults: defaults, ParamsLocked: locked, + AgentID: agentID, InstanceID: instanceID, Name: a.Name, Plugin: a.Plugin, Effect: a.Effect, + RuleKinds: datatypes.NewJSONSlice(nonNilSlice(a.RuleKinds)), + Targets: datatypes.NewJSONType(types.EffectorActionTargets{Include: nonNilSlice(a.Targets.Include), Exclude: nonNilSlice(a.Targets.Exclude)}), + TargetSchemes: datatypes.NewJSONSlice(nonNilSlice(a.TargetSchemes)), + OnClear: a.OnClear, + Description: a.Description, + PublishTargets: a.PublishTargets, + SupportsExceptions: a.SupportsExceptions, + Observations: datatypes.NewJSONSlice(nonNilSlice(a.Observations)), + }) + } + if len(rows) > 0 { + if err := tx.Create(&rows).Error; err != nil { + return err + } + } + return s.RecheckRuleActions(ctx, tx, agentID) + }) + if err != nil { + return nil, err + } + + ae, err := s.agentEffector(ctx, s.db, agentID) + if err != nil { + return nil, err + } + switch { + case ae == nil || ae.BaseURL == "": + return nil, fmt.Errorf("%w: no base URL is set for this agent; an admin sets the agent's effector base URL first", ErrBaseURLMismatch) + case normalized != ae.BaseURL: + return nil, fmt.Errorf("%w: the instance's base URL %q differs from the agent's %q", ErrBaseURLMismatch, reg.BaseURL, ae.BaseURL) + } + if s.needsVerify(ae) { + s.enqueueVerify(ctx, agentID) + } + return &types.EffectorRegistrationResult{Revision: revision, DeliveryKeys: s.DeliveryKeys()}, nil +} + +// encodeActionParams encodes a registered action's params for its columns; each is null when +// not set. +func encodeActionParams(p *types.EffectorActionParams) (schema, defaults, locked datatypes.JSON, err error) { + if p == nil { + return nil, nil, nil, nil + } + if !params.IsEmpty(p.Schema) { + schema = datatypes.JSON(p.Schema) + } + if defaults, err = effectors.EncodeParams(p.Defaults); err != nil { + return nil, nil, nil, err + } + if len(p.Locked) > 0 { + raw, err := json.Marshal(p.Locked) + if err != nil { + return nil, nil, nil, err + } + locked = datatypes.JSON(raw) + } + return schema, defaults, locked, nil +} + +// RecheckRuleActions sets each of the agent's rule actions ok when a fresh instance registers +// its effector action and the rule action's params still match the registered schema and +// locks, degraded otherwise. +func (s *Service) RecheckRuleActions(ctx context.Context, tx *gorm.DB, agentID uuid.UUID) error { + var actions []effectors.RuleAction + if err := tx.WithContext(ctx).Where("agent_id = ?", agentID).Find(&actions).Error; err != nil { + return err + } + lookedUp := map[string]*rules.RegisteredAction{} + for _, a := range actions { + registered, seen := lookedUp[a.EffectorAction] + if !seen { + var err error + registered, err = rules.LookupEffectorAction(ctx, tx, agentID, a.EffectorAction, s.staleAfter, s.now()) + if err != nil { + return err + } + lookedUp[a.EffectorAction] = registered + } + ok := registered != nil && registered.Fresh && rules.ParamsMatch(®istered.Action, a.Params) + status := effectors.RuleActionStatusDegraded + if ok { + status = effectors.RuleActionStatusOK + } + if status != a.Status { + if err := tx.Model(&effectors.RuleAction{}).Where("id = ?", a.ID).Update("status", status).Error; err != nil { + return err + } + } + } + return nil +} + +func nonNilSlice[T any](s []T) []T { + if s == nil { + return []T{} + } + return s +} + +// Jobs enqueues the effector jobs registration needs. The worker service implements it. +type Jobs interface { + EnqueueEffectorVerify(ctx context.Context, agentID uuid.UUID) error +} diff --git a/internal/service/effector/signer.go b/internal/service/effector/signer.go index 0bfe0ddb..c6df120f 100644 --- a/internal/service/effector/signer.go +++ b/internal/service/effector/signer.go @@ -1,6 +1,6 @@ -// Package effector is the API side of effector agents (docs/effectors/wire-interface.md), -// starting with delivery signing: Standard Webhooks v1a (Ed25519) signatures and the -// delivery keys agents verify them with. +// Package effector is the API side of effector agents (docs/effectors/wire-interface.md): +// delivery signing (Standard Webhooks v1a, Ed25519) and the delivery keys agents verify +// signatures with, and agents' effector registrations. package effector import ( diff --git a/internal/service/effector/validate.go b/internal/service/effector/validate.go new file mode 100644 index 00000000..feadd5b8 --- /dev/null +++ b/internal/service/effector/validate.go @@ -0,0 +1,142 @@ +package effector + +import ( + "fmt" + "maps" + "slices" + "strings" + + "github.com/compliance-framework/api/pkg/agentconfig" + "github.com/compliance-framework/api/pkg/effector/params" + "github.com/compliance-framework/api/pkg/effector/targets" + "github.com/compliance-framework/api/sdk/types" +) + +// ValidationError is a 422 with errors by field path. +type ValidationError struct { + Fields map[string]any +} + +func (e *ValidationError) Error() string { + parts := make([]string, 0, len(e.Fields)) + for _, k := range slices.Sorted(maps.Keys(e.Fields)) { + parts = append(parts, fmt.Sprintf("%s: %v", k, e.Fields[k])) + } + return "invalid: " + strings.Join(parts, "; ") +} + +type fieldErrors map[string]any + +func (fe fieldErrors) add(field, format string, args ...any) { + if _, ok := fe[field]; !ok { + fe[field] = fmt.Sprintf(format, args...) + } +} + +func (fe fieldErrors) err() error { + if len(fe) == 0 { + return nil + } + return &ValidationError{Fields: fe} +} + +// ValidateRegistration checks a registration body (wire-interface.md, the 422 row): effect +// labels, rule kinds, on-clear, unique action names, target patterns and their schemes, and +// value patterns. The base URL is checked separately. +func ValidateRegistration(reg types.EffectorRegistration) error { + fe := fieldErrors{} + names := map[string]bool{} + for i, a := range reg.Actions { + p := fmt.Sprintf("actions[%d]", i) + switch { + case !agentconfig.ActionNamePattern.MatchString(a.Name): + fe.add(p+".name", "%q must match %s", a.Name, agentconfig.ActionNamePattern.String()) + case names[a.Name]: + fe.add(p+".name", "duplicate action name %q", a.Name) + } + names[a.Name] = true + if strings.TrimSpace(a.Plugin) == "" { + fe.add(p+".plugin", "required") + } + if !agentconfig.EffectPattern.MatchString(a.Effect) { + fe.add(p+".effect", "effect %q must be a lowercase slug matching %s", a.Effect, agentconfig.EffectPattern.String()) + } + if len(a.RuleKinds) == 0 { + fe.add(p+".rule-kinds", "at least one rule kind is required") + } + for _, k := range a.RuleKinds { + if !slices.Contains(agentconfig.RuleKinds, k) { + fe.add(p+".rule-kinds", "unknown rule kind %q (one of %s)", k, strings.Join(agentconfig.RuleKinds, ", ")) + } + } + if !slices.Contains(agentconfig.OnClearValues, a.OnClear) { + fe.add(p+".on-clear", "%q must be one of %s", a.OnClear, strings.Join(agentconfig.OnClearValues, ", ")) + } + schemes := map[string]bool{} + for j, ts := range a.TargetSchemes { + sp := fmt.Sprintf("%s.target-schemes[%d]", p, j) + if !targets.ValidScheme(ts.Name) { + fe.add(sp+".name", "invalid scheme %q", ts.Name) + } + schemes[ts.Name] = true + if ts.ValuePattern != "" { + if _, err := targets.CompileValuePattern(ts.ValuePattern); err != nil { + fe.add(sp+".value-pattern", "%s", err.Error()) + } + } + } + check := func(field string, patterns []string) { + for k, raw := range patterns { + pat, err := targets.ParsePattern(raw) + if err != nil { + fe.add(fmt.Sprintf("%s.%s[%d]", p, field, k), "%s", err.Error()) + continue + } + if !schemes[pat.Scheme] { + fe.add(fmt.Sprintf("%s.%s[%d]", p, field, k), "scheme %q is not in target-schemes", pat.Scheme) + } + } + } + check("targets.include", a.Targets.Include) + check("targets.exclude", a.Targets.Exclude) + validateParams(p+".params", a.Params, fe) + } + return fe.err() +} + +// validateParams checks an action's params: a schema inside the supported subset, defaults +// that match it, and locked paths it has ("*" always). Without a schema, defaults and locked +// paths other than "*" are rejected. +func validateParams(p string, ap *types.EffectorActionParams, fe fieldErrors) { + if ap == nil { + return + } + schema, err := params.Parse(ap.Schema) + if err != nil { + fe.add(p+".schema", "%s", err.Error()) + return + } + switch { + case schema == nil && len(ap.Defaults) > 0: + fe.add(p+".defaults", "defaults need a schema") + case schema != nil: + for _, e := range schema.Validate(ap.Defaults) { + fe.add(joinPath(p+".defaults", e.Path), "%s", e.Message) + } + } + for j, l := range ap.Locked { + if l == params.LockAll { + continue + } + if !schema.HasPath(l) { + fe.add(fmt.Sprintf("%s.locked[%d]", p, j), "%q is not a parameter in the schema", l) + } + } +} + +func joinPath(prefix, path string) string { + if path == "" { + return prefix + } + return prefix + "." + path +} diff --git a/internal/service/effector/validate_test.go b/internal/service/effector/validate_test.go new file mode 100644 index 00000000..1ae381ef --- /dev/null +++ b/internal/service/effector/validate_test.go @@ -0,0 +1,96 @@ +package effector + +import ( + "encoding/json" + "testing" + + "github.com/compliance-framework/api/sdk/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func notifyRegistration(baseURL string) types.EffectorRegistration { + return types.EffectorRegistration{ + Version: "1.9.0", + BaseURL: baseURL, + Plugins: []types.EffectorPlugin{{Name: "slack", Version: "1.0.0", Digest: "sha256:41ab"}}, + Actions: []types.EffectorAction{{ + Name: "notify-owner", Description: "DM the owner", Plugin: "slack", Effect: "notify", + RuleKinds: []string{"state"}, + Targets: types.EffectorActionTargets{Include: []string{"slack-user:*"}, Exclude: []string{}}, + TargetSchemes: []types.EffectorTargetScheme{{Name: "slack-user", ValuePattern: "U[A-Z0-9]+"}}, + OnClear: "resolve", + Observations: []types.EffectorObservationType{}, + }}, + } +} + +// notifyParams is a parameter schema with a layout enum and a per-transition template. +func notifyParams() *types.EffectorActionParams { + return &types.EffectorActionParams{ + Schema: json.RawMessage(`{"type":"object","properties":{ + "layout":{"type":"string","enum":["short","detailed"],"default":"detailed"}, + "on":{"type":"object","properties":{"repeated":{"type":"object","properties":{"text":{"type":"string","format":"template","maxLength":100}}}}}}}`), + Defaults: map[string]any{"layout": "short"}, + Locked: []string{"layout"}, + } +} + +func TestValidateRegistration(t *testing.T) { + require.NoError(t, ValidateRegistration(notifyRegistration("https://agent.example"))) + withParams := notifyRegistration("https://agent.example") + withParams.Actions[0].Params = notifyParams() + require.NoError(t, ValidateRegistration(withParams)) + allLocked := notifyRegistration("https://agent.example") + allLocked.Actions[0].Params = &types.EffectorActionParams{Locked: []string{"*"}} + require.NoError(t, ValidateRegistration(allLocked), `"*" needs no schema`) + + cases := []struct { + name string + mutate func(*types.EffectorRegistration) + field string + }{ + {"bad name", func(r *types.EffectorRegistration) { r.Actions[0].Name = "Not A Name" }, "actions[0].name"}, + {"duplicate name", func(r *types.EffectorRegistration) { r.Actions = append(r.Actions, r.Actions[0]) }, "actions[1].name"}, + {"no plugin", func(r *types.EffectorRegistration) { r.Actions[0].Plugin = " " }, "actions[0].plugin"}, + {"bad effect", func(r *types.EffectorRegistration) { r.Actions[0].Effect = "Not A Label" }, "actions[0].effect"}, + {"no rule kinds", func(r *types.EffectorRegistration) { r.Actions[0].RuleKinds = nil }, "actions[0].rule-kinds"}, + {"unknown rule kind", func(r *types.EffectorRegistration) { r.Actions[0].RuleKinds = []string{"nope"} }, "actions[0].rule-kinds"}, + {"bad on-clear", func(r *types.EffectorRegistration) { r.Actions[0].OnClear = "explode" }, "actions[0].on-clear"}, + {"bad scheme", func(r *types.EffectorRegistration) { r.Actions[0].TargetSchemes[0].Name = "Slack User" }, "actions[0].target-schemes[0].name"}, + {"bad value pattern", func(r *types.EffectorRegistration) { r.Actions[0].TargetSchemes[0].ValuePattern = "(" }, "actions[0].target-schemes[0].value-pattern"}, + {"undeclared scheme", func(r *types.EffectorRegistration) { r.Actions[0].Targets.Include = []string{"slack-channel:#x"} }, "actions[0].targets.include[0]"}, + {"bad exclude", func(r *types.EffectorRegistration) { r.Actions[0].Targets.Exclude = []string{"nocolon"} }, "actions[0].targets.exclude[0]"}, + {"schema outside the subset", func(r *types.EffectorRegistration) { + r.Actions[0].Params = notifyParams() + r.Actions[0].Params.Schema = json.RawMessage(`{"type":"object","properties":{"x":{"type":"string","pattern":"^a"}}}`) + }, "actions[0].params.schema"}, + {"defaults don't match", func(r *types.EffectorRegistration) { + r.Actions[0].Params = notifyParams() + r.Actions[0].Params.Defaults = map[string]any{"layout": "huge"} + }, "actions[0].params.defaults.layout"}, + {"unknown default", func(r *types.EffectorRegistration) { + r.Actions[0].Params = notifyParams() + r.Actions[0].Params.Defaults = map[string]any{"colour": "red"} + }, "actions[0].params.defaults.colour"}, + {"locked path missing", func(r *types.EffectorRegistration) { + r.Actions[0].Params = notifyParams() + r.Actions[0].Params.Locked = []string{"layout", "on.cleared.text"} + }, "actions[0].params.locked[1]"}, + {"defaults without schema", func(r *types.EffectorRegistration) { + r.Actions[0].Params = notifyParams() + r.Actions[0].Params.Schema = nil + }, "actions[0].params.defaults"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + reg := notifyRegistration("https://agent.example") + tc.mutate(®) + err := ValidateRegistration(reg) + var verr *ValidationError + require.ErrorAs(t, err, &verr) + assert.Contains(t, verr.Fields, tc.field, "%v", verr.Fields) + assert.Contains(t, verr.Error(), tc.field) + }) + } +} diff --git a/internal/service/relational/agentcfg/service.go b/internal/service/relational/agentcfg/service.go index c4b7189a..a9605851 100644 --- a/internal/service/relational/agentcfg/service.go +++ b/internal/service/relational/agentcfg/service.go @@ -391,6 +391,25 @@ func (s *Service) TouchFromHeartbeat(ctx context.Context, agentID uuid.UUID, cre return err } +// TouchFromEffectorRegistration records an effector registration against the instance +// registry: an effector needs an instance row whatever its remote config mode +// (wire-interface.md "PUT /api/agent/instances/{instanceId}/effector"). It upserts +// last_seen_at and credential_id; at the per-agent cap (every counted instance fresh) it fails +// with ErrInstanceLimit instead of skipping, as heartbeats do. +func (s *Service) TouchFromEffectorRegistration(ctx context.Context, agentID uuid.UUID, credentialID *uuid.UUID, instanceID uuid.UUID) error { + now := s.now() + row := &relational.AgentInstance{ + AgentID: agentID, + InstanceID: instanceID, + CredentialID: credentialID, + FirstSeenAt: now, + LastSeenAt: now, + CreatedAt: now, + UpdatedAt: now, + } + return s.upsert(ctx, row, []string{"last_seen_at", "credential_id", "updated_at"}, false) +} + // upsert updates the instance row when it exists, else inserts it after the cap check under // a lock on the agent row (so concurrent first reports cannot overshoot the cap). The update // writes exactly the given columns from row, zero values included; UpdateColumns (no hooks) diff --git a/internal/service/relational/agentcfg/service_integration_test.go b/internal/service/relational/agentcfg/service_integration_test.go index d0d52089..307b31e3 100644 --- a/internal/service/relational/agentcfg/service_integration_test.go +++ b/internal/service/relational/agentcfg/service_integration_test.go @@ -1089,3 +1089,23 @@ func (s *AgentCfgServiceIntegrationSuite) TestCurrentHead() { s.Equal(int64(2), head.Revision) s.True(second.CreatedAt.Equal(head.CreatedAt)) } + +// An effector registration always records its instance, whatever the mode, and fails at the +// cap instead of being skipped like a heartbeat. +func (s *AgentCfgServiceIntegrationSuite) TestTouchFromEffectorRegistration() { + svc := s.newService(agentcfg.Settings{MaxInstancesPerAgent: 1}) + agentID := s.newAgent("effector") + instance := uuid.New() + s.Require().NoError(svc.TouchFromEffectorRegistration(s.ctx, agentID, nil, instance)) + var row relational.AgentInstance + s.Require().NoError(s.DB.Where("agent_id = ? AND instance_id = ?", agentID, instance).First(&row).Error) + s.True(row.LastSeenAt.Equal(s.now)) + + s.now = s.now.Add(time.Minute) + s.Require().NoError(svc.TouchFromEffectorRegistration(s.ctx, agentID, nil, instance), "the same instance again") + s.Require().NoError(s.DB.Where("agent_id = ? AND instance_id = ?", agentID, instance).First(&row).Error) + s.True(row.LastSeenAt.Equal(s.now)) + + s.ErrorIs(svc.TouchFromEffectorRegistration(s.ctx, agentID, nil, uuid.New()), agentcfg.ErrInstanceLimit) + s.Equal(int64(1), s.countInstances(agentID)) +} diff --git a/internal/service/rules/params.go b/internal/service/rules/params.go new file mode 100644 index 00000000..08e517ee --- /dev/null +++ b/internal/service/rules/params.go @@ -0,0 +1,31 @@ +package rules + +import ( + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/compliance-framework/api/pkg/effector/params" +) + +// CheckParams checks a rule action's params against the effector action as registered: the +// plugin's parameter schema (an action without one takes no parameters) and the operator's +// locks. The agent does the same checks on delivery. A stored lock list that doesn't decode +// fails closed: every parameter is treated as locked. +func CheckParams(action *effectors.EffectorAction, p map[string]any) []params.FieldError { + if action == nil { + return nil + } + errs := params.Validate(action.Schema(), p) + locked, err := action.Locked() + if err != nil { + locked = []string{params.LockAll} + } + return append(errs, params.CheckLocked(locked, p)...) +} + +// ParamsMatch reports whether a rule action's stored params still pass CheckParams. +func ParamsMatch(action *effectors.EffectorAction, stored []byte) bool { + p, err := effectors.DecodeParams(stored) + if err != nil { + return false + } + return len(CheckParams(action, p)) == 0 +} diff --git a/internal/service/rules/params_test.go b/internal/service/rules/params_test.go new file mode 100644 index 00000000..6371414e --- /dev/null +++ b/internal/service/rules/params_test.go @@ -0,0 +1,41 @@ +package rules + +import ( + "testing" + + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/stretchr/testify/assert" + "gorm.io/datatypes" +) + +func TestCheckParams(t *testing.T) { + schema := datatypes.JSON(`{"type":"object","properties":{"layout":{"type":"string"},"mention":{"type":"boolean"}}}`) + action := &effectors.EffectorAction{ParamsSchema: schema, ParamsLocked: datatypes.JSON(`["layout"]`)} + + assert.Empty(t, CheckParams(nil, map[string]any{"anything": 1})) + assert.Empty(t, CheckParams(action, map[string]any{"mention": true})) + + errs := CheckParams(action, map[string]any{"layout": "long"}) + if assert.Len(t, errs, 1) { + assert.Equal(t, "layout", errs[0].Path) + } + assert.NotEmpty(t, CheckParams(action, map[string]any{"mention": "yes"})) + + assert.True(t, ParamsMatch(action, []byte(`{"mention":true}`))) + assert.False(t, ParamsMatch(action, []byte(`{"layout":"long"}`))) + assert.False(t, ParamsMatch(action, []byte(`not json`))) +} + +// A stored lock list that doesn't decode locks everything instead of nothing. +func TestCheckParamsUndecodableLocksFailClosed(t *testing.T) { + schema := datatypes.JSON(`{"type":"object","properties":{"layout":{"type":"string"}}}`) + action := &effectors.EffectorAction{ParamsSchema: schema, ParamsLocked: datatypes.JSON(`{"layout":true}`)} + + errs := CheckParams(action, map[string]any{"layout": "long"}) + if assert.Len(t, errs, 1) { + assert.Equal(t, "layout", errs[0].Path) + } + assert.Empty(t, CheckParams(action, nil)) + assert.False(t, ParamsMatch(action, []byte(`{"layout":"long"}`))) + assert.True(t, ParamsMatch(action, nil)) +}