From e5672351931fe1a256a793e7862dab0fbccbb1bd Mon Sep 17 00:00:00 2001 From: "ccf-lisa[bot]" <286799724+ccf-lisa[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:26:36 -0300 Subject: [PATCH] feat(effects): effect document and signing internal/service/effects: the effect document (wire-interface.md) built from an effect, its rule and rule action (max_repeats, params as {} when unset), its entered subjects with the documents the rule saw, the current generation's entered and left subjects, the agent's last status report, subject links to the UI's evidence pages and the effect's UI link at /admin/rules/{rule}/effects/{effect}; its webhook envelope (effect.apply, or effect.clear for cleared, disabled and removed); LoadWebhook builds it from the database, also for a soft-deleted rule. internal/service/effector: the delivery signer: Ed25519 keys from CCF_EFFECTOR_SIGNING_KEY(_NEXT) (PKCS#8 PEM), kid, Standard Webhooks v1a signatures over {id}.{timestamp}.{body}, the signed headers, and the published delivery keys. Co-Authored-By: Claude Opus 5.5 --- internal/service/effector/signer.go | 176 ++++++++++++++++++ internal/service/effector/signer_test.go | 148 +++++++++++++++ internal/service/effects/document.go | 170 +++++++++++++++++ internal/service/effects/document_test.go | 78 ++++++++ internal/service/effects/load.go | 106 +++++++++++ .../service/effects/load_integration_test.go | 104 +++++++++++ 6 files changed, 782 insertions(+) create mode 100644 internal/service/effector/signer.go create mode 100644 internal/service/effector/signer_test.go create mode 100644 internal/service/effects/document.go create mode 100644 internal/service/effects/document_test.go create mode 100644 internal/service/effects/load.go create mode 100644 internal/service/effects/load_integration_test.go diff --git a/internal/service/effector/signer.go b/internal/service/effector/signer.go new file mode 100644 index 00000000..0bfe0ddb --- /dev/null +++ b/internal/service/effector/signer.go @@ -0,0 +1,176 @@ +// 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 + +import ( + "crypto/ed25519" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/pem" + "errors" + "fmt" + "net/http" + "os" + "strconv" + + "github.com/compliance-framework/api/internal/config" + "github.com/compliance-framework/api/sdk/types" +) + +// Standard Webhooks headers (https://www.standardwebhooks.com/). +const ( + HeaderWebhookID = "webhook-id" + HeaderWebhookTimestamp = "webhook-timestamp" + HeaderWebhookSignature = "webhook-signature" +) + +// SignatureVersion is the Standard Webhooks asymmetric (Ed25519) signature version. +const SignatureVersion = "v1a" + +// AlgEd25519 is the only delivery key algorithm. +const AlgEd25519 = "Ed25519" + +// ErrNoSigningKey is returned by LoadSigner when no key is configured. +var ErrNoSigningKey = errors.New("no effector signing key configured") + +// Key is one delivery key pair. +type Key struct { + Kid string + Public ed25519.PublicKey + private ed25519.PrivateKey +} + +// NewKey wraps a private key. +func NewKey(priv ed25519.PrivateKey) *Key { + pub := priv.Public().(ed25519.PublicKey) + return &Key{Kid: Kid(pub), Public: pub, private: priv} +} + +// Kid is the key ID: the first 16 hex characters of the SHA-256 of the raw public key. +func Kid(pub ed25519.PublicKey) string { + sum := sha256.Sum256(pub) + return hex.EncodeToString(sum[:])[:16] +} + +// Signer signs deliveries with the current key and publishes the current and next public +// keys. One key pair for the whole API. +type Signer struct { + current *Key + next *Key +} + +// NewSigner builds a signer from the current and (optional) next private keys. +func NewSigner(current, next ed25519.PrivateKey) *Signer { + s := &Signer{current: NewKey(current)} + if next != nil { + s.next = NewKey(next) + } + return s +} + +// LoadSigner reads CCF_EFFECTOR_SIGNING_KEY and, if set, CCF_EFFECTOR_SIGNING_KEY_NEXT +// (PKCS#8 PEM Ed25519 private keys, as `openssl genpkey -algorithm ed25519` writes them). +func LoadSigner(cfg *config.EffectorConfig) (*Signer, error) { + if cfg == nil || cfg.SigningKeyPath == "" { + return nil, ErrNoSigningKey + } + current, err := ReadPrivateKeyFile(cfg.SigningKeyPath) + if err != nil { + return nil, fmt.Errorf("effector signing key: %w", err) + } + var next ed25519.PrivateKey + if cfg.SigningKeyNextPath != "" { + if next, err = ReadPrivateKeyFile(cfg.SigningKeyNextPath); err != nil { + return nil, fmt.Errorf("next effector signing key: %w", err) + } + } + return NewSigner(current, next), nil +} + +// ReadPrivateKeyFile reads a PEM Ed25519 private key file. +func ReadPrivateKeyFile(path string) (ed25519.PrivateKey, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return ParsePrivateKeyPEM(raw) +} + +// ParsePrivateKeyPEM parses a PKCS#8 PEM Ed25519 private key. +func ParsePrivateKeyPEM(raw []byte) (ed25519.PrivateKey, error) { + block, _ := pem.Decode(raw) + if block == nil { + return nil, errors.New("no PEM block found") + } + key, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("parse PKCS#8 private key: %w", err) + } + priv, ok := key.(ed25519.PrivateKey) + if !ok { + return nil, fmt.Errorf("private key is %T, want Ed25519", key) + } + return priv, nil +} + +// MarshalPrivateKeyPEM encodes a private key as PKCS#8 PEM (tests and tooling). +func MarshalPrivateKeyPEM(priv ed25519.PrivateKey) ([]byte, error) { + der, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + return nil, err + } + return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), nil +} + +// CurrentKid is the kid deliveries are signed with. +func (s *Signer) CurrentKid() string { + return s.current.Kid +} + +// DeliveryKeys are the public keys agents verify deliveries with: the current key and, during +// a rotation, the next one. Public keys are base64 (standard encoding) of the raw 32 bytes. +func (s *Signer) DeliveryKeys() []types.DeliveryKey { + if s == nil { + return []types.DeliveryKey{} + } + out := []types.DeliveryKey{publish(s.current, types.DeliveryKeyCurrent)} + if s.next != nil { + out = append(out, publish(s.next, types.DeliveryKeyNext)) + } + return out +} + +func publish(k *Key, status string) types.DeliveryKey { + return types.DeliveryKey{Kid: k.Kid, Alg: AlgEd25519, PublicKey: base64.StdEncoding.EncodeToString(k.Public), Status: status} +} + +// SignedContent is what a v1a signature covers: "{webhook-id}.{webhook-timestamp}.{body}". +func SignedContent(id string, timestamp int64, body []byte) []byte { + ts := strconv.FormatInt(timestamp, 10) + out := make([]byte, 0, len(id)+len(ts)+len(body)+2) + out = append(out, id...) + out = append(out, '.') + out = append(out, ts...) + out = append(out, '.') + return append(out, body...) +} + +// Sign returns the webhook-signature header value: "v1a,". +func (s *Signer) Sign(id string, timestamp int64, body []byte) string { + sig := ed25519.Sign(s.current.private, SignedContent(id, timestamp, body)) + return SignatureVersion + "," + base64.StdEncoding.EncodeToString(sig) +} + +// Headers returns the signed delivery headers for body. +func (s *Signer) Headers(id string, timestamp int64, body []byte) http.Header { + h := http.Header{} + h.Set(HeaderWebhookID, id) + h.Set(HeaderWebhookTimestamp, strconv.FormatInt(timestamp, 10)) + h.Set(HeaderWebhookSignature, s.Sign(id, timestamp, body)) + h.Set(types.EffectorProtocolHeader, types.EffectorProtocolVersion) + h.Set("Content-Type", "application/json") + return h +} diff --git a/internal/service/effector/signer_test.go b/internal/service/effector/signer_test.go new file mode 100644 index 00000000..03ecdf0b --- /dev/null +++ b/internal/service/effector/signer_test.go @@ -0,0 +1,148 @@ +package effector + +import ( + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/pem" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/compliance-framework/api/internal/config" + "github.com/compliance-framework/api/sdk/types" + "github.com/stretchr/testify/require" +) + +func newKey(t *testing.T) ed25519.PrivateKey { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + return priv +} + +// agentVerify is the agent's verification (agent internal/effector/verifier.go), byte for +// byte: decode the published key (base64, std or raw, std or URL alphabet), then accept the +// first v1a signature among the space-separated header entries that verifies over +// "{id}.{trimmed timestamp}.{body}". +func agentVerify(keys []types.DeliveryKey, id, timestamp string, body []byte, header string) error { + var pubs []ed25519.PublicKey + for _, k := range keys { + if k.Alg != "" && !strings.EqualFold(k.Alg, "Ed25519") { + continue + } + for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding} { + if b, err := enc.DecodeString(strings.TrimSpace(k.PublicKey)); err == nil && len(b) == ed25519.PublicKeySize { + pubs = append(pubs, ed25519.PublicKey(b)) + break + } + } + } + msg := []byte(id + "." + strings.TrimSpace(timestamp) + "." + string(body)) + for _, part := range strings.Fields(header) { + version, sig, ok := strings.Cut(part, ",") + if !ok || version != "v1a" { + continue + } + raw, err := base64.StdEncoding.DecodeString(sig) + if err != nil { + continue + } + for _, k := range pubs { + if ed25519.Verify(k, msg, raw) { + return nil + } + } + } + return errors.New("signature does not verify") +} + +func TestSignerVerifiesWithTheAgentAlgorithm(t *testing.T) { + s := NewSigner(newKey(t), newKey(t)) + body := []byte(`{"type":"effect.apply","effect":{"id":"e1","generation":3}}`) + h := s.Headers("dlv_abc_3", 1764500000, body) + + require.Equal(t, "dlv_abc_3", h.Get(HeaderWebhookID)) + require.Equal(t, "1764500000", h.Get(HeaderWebhookTimestamp)) + require.Equal(t, "1", h.Get(types.EffectorProtocolHeader)) + require.True(t, strings.HasPrefix(h.Get(HeaderWebhookSignature), "v1a,")) + + keys := s.DeliveryKeys() + require.NoError(t, agentVerify(keys, h.Get(HeaderWebhookID), h.Get(HeaderWebhookTimestamp), body, h.Get(HeaderWebhookSignature))) + require.Error(t, agentVerify(keys, "dlv_abc_4", h.Get(HeaderWebhookTimestamp), body, h.Get(HeaderWebhookSignature)), "the id is signed") + require.Error(t, agentVerify(keys, h.Get(HeaderWebhookID), "1764500001", body, h.Get(HeaderWebhookSignature)), "the timestamp is signed") + require.Error(t, agentVerify(keys, h.Get(HeaderWebhookID), h.Get(HeaderWebhookTimestamp), append(body, ' '), h.Get(HeaderWebhookSignature)), "the body is signed") + // Only the next key: a delivery signed with the current one doesn't verify. + require.Error(t, agentVerify(keys[1:], h.Get(HeaderWebhookID), h.Get(HeaderWebhookTimestamp), body, h.Get(HeaderWebhookSignature))) +} + +func TestSignedContentAndKeys(t *testing.T) { + priv := newKey(t) + s := NewSigner(priv, nil) + require.Equal(t, "id.42.{}", string(SignedContent("id", 42, []byte("{}")))) + + pub := priv.Public().(ed25519.PublicKey) + sum := sha256.Sum256(pub) + keys := s.DeliveryKeys() + require.Len(t, keys, 1) + require.Equal(t, hex.EncodeToString(sum[:])[:16], keys[0].Kid) + require.Equal(t, s.CurrentKid(), keys[0].Kid) + require.Equal(t, "Ed25519", keys[0].Alg) + require.Equal(t, types.DeliveryKeyCurrent, keys[0].Status) + raw, err := base64.StdEncoding.DecodeString(keys[0].PublicKey) + require.NoError(t, err) + require.Equal(t, []byte(pub), raw) + + sig := s.Sign("id", 42, []byte("{}")) + decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sig, "v1a,")) + require.NoError(t, err) + require.True(t, ed25519.Verify(pub, []byte("id."+strconv.Itoa(42)+".{}"), decoded)) +} + +func TestLoadSigner(t *testing.T) { + dir := t.TempDir() + write := func(name string, priv ed25519.PrivateKey) string { + raw, err := MarshalPrivateKeyPEM(priv) + require.NoError(t, err) + path := filepath.Join(dir, name) + require.NoError(t, os.WriteFile(path, raw, 0o600)) + return path + } + current, next := newKey(t), newKey(t) + s, err := LoadSigner(&config.EffectorConfig{SigningKeyPath: write("current.pem", current), SigningKeyNextPath: write("next.pem", next)}) + require.NoError(t, err) + keys := s.DeliveryKeys() + require.Len(t, keys, 2) + require.Equal(t, Kid(current.Public().(ed25519.PublicKey)), keys[0].Kid) + require.Equal(t, Kid(next.Public().(ed25519.PublicKey)), keys[1].Kid) + require.Equal(t, types.DeliveryKeyNext, keys[1].Status) + + _, err = LoadSigner(&config.EffectorConfig{}) + require.ErrorIs(t, err, ErrNoSigningKey) + bad := filepath.Join(dir, "bad.pem") + require.NoError(t, os.WriteFile(bad, []byte("not a key"), 0o600)) + _, err = LoadSigner(&config.EffectorConfig{SigningKeyPath: bad}) + require.Error(t, err) + _, err = LoadSigner(&config.EffectorConfig{SigningKeyPath: write("ok.pem", current), SigningKeyNextPath: bad}) + require.ErrorContains(t, err, "next effector signing key") + + // A PKCS#8 key of another type is rejected. + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(ec) + require.NoError(t, err) + _, err = ParsePrivateKeyPEM(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})) + require.ErrorContains(t, err, "want Ed25519") + + var none *Signer + require.Empty(t, none.DeliveryKeys(), "effectors off: no delivery keys") + require.NotNil(t, none.DeliveryKeys()) +} diff --git a/internal/service/effects/document.go b/internal/service/effects/document.go new file mode 100644 index 00000000..5470358c --- /dev/null +++ b/internal/service/effects/document.go @@ -0,0 +1,170 @@ +// Package effects builds effect documents (docs/effectors/wire-interface.md, "The effect +// document"): what a webhook delivery and the agent's effect routes carry for an effect. +package effects + +import ( + "encoding/json" + "strings" + "time" + + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/compliance-framework/api/pkg/effector/targets" + "github.com/compliance-framework/api/sdk/types" +) + +// Transitions. Generation-bumping transitions are delivered; pending changes aren't. +const ( + TransitionActivated = types.EffectTransitionActivated + TransitionUpdated = types.EffectTransitionUpdated + TransitionRepeated = types.EffectTransitionRepeated + TransitionFinished = types.EffectTransitionFinished + TransitionRedelivered = types.EffectTransitionRedelivered + TransitionCleared = types.EffectTransitionCleared + TransitionDisabled = types.EffectTransitionDisabled + TransitionRemoved = types.EffectTransitionRemoved +) + +// IsClear reports whether a transition is delivered as effect.clear. +func IsClear(transition string) bool { + switch transition { + case TransitionCleared, TransitionDisabled, TransitionRemoved: + return true + } + return false +} + +// EventType is the webhook event type of a transition: effect.clear or effect.apply. +func EventType(transition string) string { + if IsClear(transition) { + return types.EffectEventClear + } + return types.EffectEventApply +} + +// SubjectEntry is one subject of an effect, with the document the rule saw. +type SubjectEntry struct { + ID string + Title string + MatchedSince *time.Time + EnteredAt *time.Time + Document json.RawMessage +} + +// DocumentInput is everything an effect document is built from. +type DocumentInput struct { + Effect effectors.Effect + Rule effectors.Rule + // EffectType is the effector action's effect (its registered `effect`), when known. + EffectType string + // MaxRepeats is the rule action's max_repeats (0: unlimited). + MaxRepeats int + // Params are the rule action's params (nil: none). + Params map[string]any + // Subjects that have entered the effect. + Subjects []SubjectEntry + // Entered and Left are the subject IDs that changed with the effect's generation. + Entered, Left []string + // WebBaseURL builds links to the UI; empty leaves them out. + WebBaseURL string +} + +// Document builds the effect document (the same document webhooks and the agent routes +// carry). It's built when sent, so `applied` is whatever the agent last reported. +func Document(in DocumentInput) types.Effect { + e := in.Effect + doc := types.Effect{ + ID: e.ID.String(), + Generation: e.Generation, + Transition: e.Transition, + State: e.State, + RepeatCount: e.RepeatCount, + Rule: types.EffectRule{ID: in.Rule.ID.String(), Name: in.Rule.Name, Kind: in.Rule.Kind}, + Action: types.EffectAction{ + RuleActionID: e.RuleActionID.String(), + EffectorAction: e.EffectorAction, + Effect: in.EffectType, + MaxRepeats: in.MaxRepeats, + Params: in.Params, + }, + Target: splitTarget(e.TargetIdentity), + Exceptions: []types.EffectException{}, + Trigger: types.EffectTrigger{ + Source: in.Rule.Source, + Subjects: []types.EffectSubject{}, + Changes: &types.EffectChanges{Entered: nonNil(in.Entered), Left: nonNil(in.Left)}, + }, + } + if doc.Action.Params == nil { + doc.Action.Params = map[string]any{} + } + if e.State == effectors.EffectStatePending { + doc.State = effectors.EffectStateInactive + } + if e.ActiveSince != nil && (e.State == effectors.EffectStateActive || e.State == effectors.EffectStateFinished) { + t := e.ActiveSince.UTC() + doc.ActiveSince = &t + } + base := strings.TrimRight(in.WebBaseURL, "/") + for _, s := range in.Subjects { + subject := types.EffectSubject{ + ID: s.ID, + Title: s.Title, + MatchedSince: utcPtr(s.MatchedSince), + EnteredAt: utcPtr(s.EnteredAt), + Document: s.Document, + } + if base != "" && in.Rule.Source == effectors.SourceEvidence { + subject.URL = base + "/evidence/" + s.ID + } + doc.Trigger.Subjects = append(doc.Trigger.Subjects, subject) + } + if e.AppliedGeneration != nil { + applied := &types.EffectApplied{Generation: *e.AppliedGeneration, At: utcPtr(e.AppliedAt)} + if e.AppliedStatus != nil { + applied.Status = *e.AppliedStatus + } + if e.AppliedMessage != nil { + applied.Message = *e.AppliedMessage + } + if len(e.AppliedLinks) > 0 { + _ = json.Unmarshal(e.AppliedLinks, &applied.Links) + } + if len(e.AppliedRefs) > 0 { + _ = json.Unmarshal(e.AppliedRefs, &applied.Refs) + } + doc.Applied = applied + } + if base != "" { + doc.Links = map[string]string{"ui": base + "/admin/rules/" + in.Rule.ID.String() + "/effects/" + e.ID.String()} + } + return doc +} + +// Webhook wraps the document in its webhook envelope (effect.apply or effect.clear). +func Webhook(in DocumentInput) types.EffectorWebhook { + doc := Document(in) + return types.EffectorWebhook{Type: EventType(doc.Transition), Effect: &doc} +} + +func splitTarget(identity string) types.EffectTarget { + t := types.EffectTarget{Identity: identity} + if id, err := targets.ParseIdentity(identity); err == nil { + t.Scheme, t.Value = id.Scheme, id.Value + } + return t +} + +func utcPtr(t *time.Time) *time.Time { + if t == nil { + return nil + } + u := t.UTC() + return &u +} + +func nonNil(s []string) []string { + if s == nil { + return []string{} + } + return s +} diff --git a/internal/service/effects/document_test.go b/internal/service/effects/document_test.go new file mode 100644 index 00000000..9a24899a --- /dev/null +++ b/internal/service/effects/document_test.go @@ -0,0 +1,78 @@ +package effects + +import ( + "encoding/json" + "testing" + "time" + + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/compliance-framework/api/sdk/types" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDocument(t *testing.T) { + now := time.Date(2026, 11, 30, 9, 12, 0, 0, time.UTC) + gen := int64(41) + status := "applied" + rule := effectors.Rule{ID: uuid.New(), Name: "Repos keep branch protection", Source: "evidence", Kind: "state"} + effect := effectors.Effect{ + ID: uuid.New(), RuleID: rule.ID, RuleActionID: uuid.New(), EffectorAction: "apply-branch-baseline", + TargetIdentity: "github-repo:github.com/acme/repo-1", State: effectors.EffectStateActive, + Generation: 42, Transition: TransitionActivated, ActiveSince: &now, RepeatCount: 0, + AppliedGeneration: &gen, AppliedStatus: &status, + AppliedLinks: []byte(`[{"rel":"settings","href":"https://github.com/acme/repo-1/settings"}]`), + AppliedRefs: []byte(`{"changed-fields":["required-reviews"]}`), + } + in := DocumentInput{ + Effect: effect, Rule: rule, EffectType: "remediate-apply", WebBaseURL: "https://ccf.acme/", + Subjects: []SubjectEntry{{ID: "4d1a", Title: "Branch protection", MatchedSince: &now, EnteredAt: &now, Document: json.RawMessage(`{"status":"not-satisfied"}`)}}, + Entered: []string{"4d1a"}, + } + hook := Webhook(in) + assert.Equal(t, types.EffectEventApply, hook.Type) + doc := hook.Effect + require.NotNil(t, doc) + assert.Equal(t, int64(42), doc.Generation) + assert.Equal(t, "github-repo", doc.Target.Scheme) + assert.Equal(t, "github.com/acme/repo-1", doc.Target.Value) + assert.Equal(t, "remediate-apply", doc.Action.Effect) + assert.Equal(t, "https://ccf.acme/evidence/4d1a", doc.Trigger.Subjects[0].URL) + assert.Equal(t, []string{"4d1a"}, doc.Trigger.Changes.Entered) + assert.Equal(t, []string{}, doc.Trigger.Changes.Left) + assert.Equal(t, "https://ccf.acme/admin/rules/"+rule.ID.String()+"/effects/"+effect.ID.String(), doc.Links["ui"]) + require.NotNil(t, doc.Applied) + assert.Equal(t, int64(41), doc.Applied.Generation) + assert.Equal(t, "settings", doc.Applied.Links[0].Rel) + assert.Equal(t, []any{"required-reviews"}, doc.Applied.Refs["changed-fields"]) + assert.Equal(t, []types.EffectException{}, doc.Exceptions) + + raw, err := json.Marshal(hook) + require.NoError(t, err) + assert.Contains(t, string(raw), `"active-since":"2026-11-30T09:12:00Z"`) + assert.Contains(t, string(raw), `"event":null`) + assert.Contains(t, string(raw), `"params":{}`, "action.params is {} when the rule set none") + + in.Params = map[string]any{"layout": "short", "on": map[string]any{"repeated": map[string]any{"text": "again"}}} + withParams := Document(in) + assert.Equal(t, in.Params, withParams.Action.Params) + in.Params = nil + + in.Effect.Transition, in.Effect.State = TransitionCleared, effectors.EffectStateInactive + in.Subjects, in.Entered, in.Left = nil, nil, []string{"4d1a"} + cleared := Webhook(in) + assert.Equal(t, types.EffectEventClear, cleared.Type) + assert.Nil(t, cleared.Effect.ActiveSince) + assert.Empty(t, cleared.Effect.Trigger.Subjects) + assert.Equal(t, []string{"4d1a"}, cleared.Effect.Trigger.Changes.Left) +} + +func TestEventType(t *testing.T) { + for _, tr := range []string{TransitionCleared, TransitionDisabled, TransitionRemoved} { + assert.Equal(t, types.EffectEventClear, EventType(tr)) + } + for _, tr := range []string{TransitionActivated, TransitionUpdated, TransitionRepeated, TransitionFinished, TransitionRedelivered} { + assert.Equal(t, types.EffectEventApply, EventType(tr)) + } +} diff --git a/internal/service/effects/load.go b/internal/service/effects/load.go new file mode 100644 index 00000000..4755b6c8 --- /dev/null +++ b/internal/service/effects/load.go @@ -0,0 +1,106 @@ +package effects + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/compliance-framework/api/internal/service/relational/effectors" + "github.com/compliance-framework/api/internal/service/rules" + "github.com/compliance-framework/api/sdk/types" + "github.com/google/uuid" + "gorm.io/datatypes" + "gorm.io/gorm" +) + +// ErrEffectNotFound is returned for an effect that doesn't exist. +var ErrEffectNotFound = errors.New("effect not found") + +// LoadWebhook builds an effect's current webhook (effect.apply or effect.clear) from the +// database: the document is built now, so `applied` is the agent's latest report. The +// delivery job and the agent's effects routes use it. +func LoadWebhook(ctx context.Context, db *gorm.DB, effectID uuid.UUID, webBaseURL string) (*types.EffectorWebhook, *effectors.Effect, error) { + in, effect, err := LoadDocumentInput(ctx, db, effectID, webBaseURL) + if err != nil { + return nil, nil, err + } + hook := Webhook(*in) + return &hook, effect, nil +} + +// LoadDocumentInput loads everything an effect document is built from. +func LoadDocumentInput(ctx context.Context, db *gorm.DB, effectID uuid.UUID, webBaseURL string) (*DocumentInput, *effectors.Effect, error) { + db = db.WithContext(ctx) + var effect effectors.Effect + if err := db.First(&effect, "id = ?", effectID).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, nil, ErrEffectNotFound + } + return nil, nil, fmt.Errorf("load effect: %w", err) + } + var rule effectors.Rule + if err := db.Unscoped().First(&rule, "id = ?", effect.RuleID).Error; err != nil { + return nil, nil, fmt.Errorf("load rule: %w", err) + } + in := &DocumentInput{Effect: effect, Rule: rule, WebBaseURL: webBaseURL} + var action effectors.RuleAction + if err := db.Unscoped().Select("id", "max_repeats", "params").First(&action, "id = ?", effect.RuleActionID).Error; err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return nil, nil, fmt.Errorf("load rule action: %w", err) + } + } else { + in.MaxRepeats = action.MaxRepeats + if in.Params, err = effectors.DecodeParams(action.Params); err != nil { + return nil, nil, fmt.Errorf("decode rule action params: %w", err) + } + } + + registered, err := rules.LookupEffectorAction(ctx, db, effect.AgentID, effect.EffectorAction, 0, time.Now()) + if err != nil { + return nil, nil, err + } + if registered != nil { + in.EffectType = registered.Action.Effect + } + + var subjects []struct { + SubjectID uuid.UUID + MatchedSince time.Time + EnteredAt *time.Time + Document datatypes.JSON + } + if err := db.Raw(` + SELECT es.subject_id, es.matched_since, es.entered_at, m.document + FROM ccf_effect_subjects es + LEFT JOIN ccf_rule_subject_matches m ON m.rule_id = ? AND m.subject_id = es.subject_id + WHERE es.effect_id = ? AND es.entered_at IS NOT NULL + ORDER BY es.entered_at, es.subject_id`, effect.RuleID, effect.ID).Scan(&subjects).Error; err != nil { + return nil, nil, fmt.Errorf("load effect subjects: %w", err) + } + for _, s := range subjects { + matched := s.MatchedSince + entry := SubjectEntry{ID: s.SubjectID.String(), MatchedSince: &matched, EnteredAt: s.EnteredAt} + if len(s.Document) > 0 { + entry.Document = json.RawMessage(s.Document) + var titled struct { + Title string `json:"title"` + } + if json.Unmarshal(s.Document, &titled) == nil { + entry.Title = titled.Title + } + } + in.Subjects = append(in.Subjects, entry) + } + + var history effectors.EffectHistory + err = db.Where("effect_id = ? AND generation = ?", effect.ID, effect.Generation).Order("id DESC").First(&history).Error + switch { + case err == nil: + in.Entered, in.Left = []string(history.Entered), []string(history.Left) + case !errors.Is(err, gorm.ErrRecordNotFound): + return nil, nil, fmt.Errorf("load effect history: %w", err) + } + return in, &effect, nil +} diff --git a/internal/service/effects/load_integration_test.go b/internal/service/effects/load_integration_test.go new file mode 100644 index 00000000..198c107e --- /dev/null +++ b/internal/service/effects/load_integration_test.go @@ -0,0 +1,104 @@ +//go:build integration + +package effects_test + +import ( + "context" + "testing" + "time" + + "github.com/compliance-framework/api/internal/service/effects" + "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 TestLoadWebhook(t *testing.T) { + suite.Run(t, new(LoadSuite)) +} + +type LoadSuite struct { + tests.IntegrationTestSuite +} + +func (s *LoadSuite) SetupTest() { + s.Require().NoError(s.Migrator.Refresh()) +} + +func (s *LoadSuite) TestBuildsTheDocumentFromTheDatabase() { + ctx := context.Background() + t0 := time.Date(2026, 11, 30, 9, 0, 0, 0, time.UTC) + agent, err := s.CreateAgent("platform-notify") + s.Require().NoError(err) + instance := uuid.New() + s.Require().NoError(s.DB.Create(&effectors.AgentEffectorInstance{AgentID: *agent.ID, InstanceID: instance, RegisteredAt: time.Now()}).Error) + s.Require().NoError(s.DB.Create(&effectors.EffectorAction{AgentID: *agent.ID, InstanceID: instance, Name: "notify-owner", Plugin: "slack", Effect: "notify"}).Error) + + target := "slack-user:UALICE" + rule := effectors.Rule{ + Name: "failing evidence", Source: effectors.SourceEvidence, Kind: effectors.RuleKindState, WhenExpr: "true", Enabled: true, + Actions: []effectors.RuleAction{{AgentID: *agent.ID, EffectorAction: "notify-owner", TargetIdentity: &target, MaxRepeats: 3, Params: datatypes.JSON(`{"layout":"short"}`)}}, + } + s.Require().NoError(s.DB.Create(&rule).Error) + action := rule.Actions[0] + effect := effectors.Effect{ + ID: uuid.New(), RuleID: rule.ID, RuleActionID: action.ID, AgentID: *agent.ID, EffectorAction: "notify-owner", + TargetIdentity: target, State: effectors.EffectStateActive, Generation: 2, Transition: effects.TransitionUpdated, ActiveSince: &t0, + } + s.Require().NoError(s.DB.Create(&effect).Error) + + // Two subjects entered (with the documents the rule last saw), one is still pending. + a, b, pending := uuid.New(), uuid.New(), uuid.New() + for i, subject := range []uuid.UUID{a, b} { + entered := t0.Add(time.Duration(i) * time.Minute) + s.Require().NoError(s.DB.Create(&effectors.EffectSubject{EffectID: effect.ID, SubjectID: subject, MatchedSince: t0, EnteredAt: &entered}).Error) + s.Require().NoError(s.DB.Create(&effectors.RuleSubjectMatch{RuleID: rule.ID, SubjectID: subject, MatchedSince: t0, Document: datatypes.JSON(`{"title":"stream ` + subject.String() + `","status":"not-satisfied"}`)}).Error) + } + s.Require().NoError(s.DB.Create(&effectors.EffectSubject{EffectID: effect.ID, SubjectID: pending, MatchedSince: t0}).Error) + s.Require().NoError(s.DB.Create(&effectors.EffectHistory{EffectID: effect.ID, Generation: 1, Transition: effects.TransitionActivated, State: effectors.EffectStateActive, Entered: datatypes.NewJSONSlice([]string{a.String()}), At: t0}).Error) + s.Require().NoError(s.DB.Create(&effectors.EffectHistory{EffectID: effect.ID, Generation: 2, Transition: effects.TransitionUpdated, State: effectors.EffectStateActive, Entered: datatypes.NewJSONSlice([]string{b.String()}), Left: datatypes.NewJSONSlice([]string{}), At: t0.Add(time.Minute)}).Error) + + hook, loaded, err := effects.LoadWebhook(ctx, s.DB, effect.ID, "https://ccf.example/") + s.Require().NoError(err) + s.Equal(effect.ID, loaded.ID) + s.Equal(types.EffectEventApply, hook.Type) + doc := hook.Effect + s.Equal(int64(2), doc.Generation) + s.Equal(effects.TransitionUpdated, doc.Transition) + s.Equal("notify", doc.Action.Effect, "the registered effect") + s.Equal(3, doc.Action.MaxRepeats) + s.Equal(map[string]any{"layout": "short"}, doc.Action.Params) + s.Equal("failing evidence", doc.Rule.Name) + s.Require().Len(doc.Trigger.Subjects, 2, "only subjects that entered") + s.Equal(a.String(), doc.Trigger.Subjects[0].ID, "ordered by entry") + s.Equal("stream "+a.String(), doc.Trigger.Subjects[0].Title) + s.JSONEq(`{"title":"stream `+a.String()+`","status":"not-satisfied"}`, string(doc.Trigger.Subjects[0].Document)) + s.Equal("https://ccf.example/evidence/"+b.String(), doc.Trigger.Subjects[1].URL) + s.Equal([]string{b.String()}, doc.Trigger.Changes.Entered, "the changes of the current generation") + s.Equal([]string{}, doc.Trigger.Changes.Left) + s.Equal("https://ccf.example/admin/rules/"+rule.ID.String()+"/effects/"+effect.ID.String(), doc.Links["ui"]) + s.Nil(doc.Applied) + + // The rule is deleted and the effect removed: the document still builds, as effect.clear. + s.Require().NoError(s.DB.Delete(&effectors.RuleAction{}, "id = ?", action.ID).Error) + s.Require().NoError(s.DB.Delete(&effectors.Rule{}, "id = ?", rule.ID).Error) + s.Require().NoError(s.DB.Model(&effectors.Effect{}).Where("id = ?", effect.ID).Updates(map[string]any{ + "state": effectors.EffectStateInactive, "transition": effects.TransitionRemoved, "generation": 3, + }).Error) + s.Require().NoError(s.DB.Where("effect_id = ?", effect.ID).Delete(&effectors.EffectSubject{}).Error) + s.Require().NoError(s.DB.Create(&effectors.EffectHistory{EffectID: effect.ID, Generation: 3, Transition: effects.TransitionRemoved, State: effectors.EffectStateInactive, Left: datatypes.NewJSONSlice([]string{a.String(), b.String()}), At: t0.Add(2 * time.Minute)}).Error) + hook, _, err = effects.LoadWebhook(ctx, s.DB, effect.ID, "") + s.Require().NoError(err) + s.Equal(types.EffectEventClear, hook.Type) + s.Equal("failing evidence", hook.Effect.Rule.Name) + s.Equal(map[string]any{"layout": "short"}, hook.Effect.Action.Params, "a soft-deleted action keeps its params") + s.Empty(hook.Effect.Trigger.Subjects) + s.Equal([]string{a.String(), b.String()}, hook.Effect.Trigger.Changes.Left) + s.Nil(hook.Effect.Links, "no UI base URL, no link") + + _, _, err = effects.LoadWebhook(ctx, s.DB, uuid.New(), "") + s.ErrorIs(err, effects.ErrEffectNotFound) +}