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
143 changes: 143 additions & 0 deletions internal/document.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package internal

import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
)

// Transitions of an effect (wire-interface.md, "The effect document").
const (
TransitionActivated = "activated"
TransitionUpdated = "updated"
TransitionRepeated = "repeated"
TransitionFinished = "finished"
TransitionRedelivered = "redelivered"
TransitionCleared = "cleared"
TransitionDisabled = "disabled"
TransitionRemoved = "removed"
TransitionOccurred = "occurred"
)

// States of an effect.
const (
StateActive = "active"
StateFinished = "finished"
StateInactive = "inactive"
)

// Effect is the part of the effect document (EffectRequest.effect_document) the plugin
// reads: the target, the transition, and the subjects that explain why it is active.
type Effect struct {
ID string `json:"id"`
Generation uint64 `json:"generation"`
Transition string `json:"transition"`
State string `json:"state"`
Rule Rule `json:"rule"`
Action Action `json:"action"`
Target Target `json:"target"`
Trigger Trigger `json:"trigger"`
Applied *Applied `json:"applied,omitempty"`
}

// Rule is the rule that produced the effect.
type Rule struct {
ID string `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
}

// Action is the rule action and the effector action it runs.
type Action struct {
RuleActionID string `json:"rule-action-id"`
EffectorAction string `json:"effector-action"`
Effect string `json:"effect"`
}

// Target is the effect's target identity, split into scheme and value.
type Target struct {
Identity string `json:"identity"`
Scheme string `json:"scheme"`
Value string `json:"value"`
}

// Trigger is what caused the effect.
type Trigger struct {
Source string `json:"source"`
Subjects []Subject `json:"subjects"`
}

// Subject is one subject (an evidence stream) in the effect.
type Subject struct {
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url,omitempty"`
}

// Applied is what the agent last reported for the effect.
type Applied struct {
Generation uint64 `json:"generation"`
Status string `json:"status"`
Refs map[string]any `json:"refs,omitempty"`
}

// ParseEffect decodes an effect document. It accepts the effect object itself and, for
// robustness, a whole webhook body ({"type": ..., "effect": {...}}).
func ParseEffect(raw []byte) (*Effect, error) {
if len(raw) == 0 {
return nil, errors.New("empty effect document")
}
var wrapper struct {
Effect json.RawMessage `json:"effect"`
}
if err := json.Unmarshal(raw, &wrapper); err == nil && len(wrapper.Effect) > 0 && wrapper.Effect[0] == '{' {
raw = wrapper.Effect
}
var eff Effect
if err := json.Unmarshal(raw, &eff); err != nil {
return nil, fmt.Errorf("decode effect document: %w", err)
}
if eff.ID == "" {
return nil, errors.New("effect document has no id")
}
return &eff, nil
}

// Target scheme of a repository.
const (
SchemeRepo = "github-repo"
repoValuePattern = `^github\.com/[A-Za-z0-9-]+/[A-Za-z0-9._-]+$`
repoExample = "github-repo:github.com/acme/repo-1"
repoSchemeSummary = "A GitHub repository, as github.com/<owner>/<repository>"
)

var repoValueRE = regexp.MustCompile(repoValuePattern)

// Repo is a repository named by a target.
type Repo struct {
Owner, Name string
}

// FullName is owner/name.
func (r Repo) FullName() string { return r.Owner + "/" + r.Name }

// ParseTarget returns the repository a github-repo target names.
func ParseTarget(t Target) (Repo, error) {
scheme, value := t.Scheme, t.Value
if scheme == "" || value == "" {
scheme, value, _ = strings.Cut(t.Identity, ":")
}
if scheme != SchemeRepo {
return Repo{}, fmt.Errorf("unsupported target scheme %q (only %s)", scheme, SchemeRepo)
}
if !repoValueRE.MatchString(value) {
return Repo{}, fmt.Errorf("target %s:%s doesn't match %s", scheme, value, repoValuePattern)
}
parts := strings.SplitN(value, "/", 3)
if parts[2] == "." || parts[2] == ".." {
return Repo{}, fmt.Errorf("target %s:%s isn't a repository name", scheme, value)
}
return Repo{Owner: parts[1], Name: parts[2]}, nil
}
74 changes: 74 additions & 0 deletions internal/document_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package internal

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const effectDoc = `{
"id": "eff_7f3c", "generation": 3, "transition": "repeated", "state": "active",
"rule": {"id": "rul_19a2", "name": "No direct collaborators", "kind": "state"},
"action": {"rule-action-id": "act_55d1", "effector-action": "fix-github-repo", "effect": "remediate-apply"},
"target": {"identity": "github-repo:github.com/acme/repo-1", "scheme": "github-repo", "value": "github.com/acme/repo-1"},
"trigger": {"source": "evidence", "subjects": [{"id": "sub_1", "title": "repository_team_access"}]},
"applied": {"generation": 2, "status": "applied", "refs": {"last_applied": "2026-12-01T10:00:00Z"}}
}`

func TestParseEffect(t *testing.T) {
for name, raw := range map[string]string{
"effect": effectDoc,
"webhook body": `{"type": "effect.repeated", "effect": ` + effectDoc + `}`,
} {
eff, err := ParseEffect([]byte(raw))
require.NoError(t, err, name)
assert.Equal(t, "eff_7f3c", eff.ID, name)
assert.Equal(t, uint64(3), eff.Generation, name)
assert.Equal(t, TransitionRepeated, eff.Transition, name)
assert.Equal(t, StateActive, eff.State, name)
assert.Equal(t, "fix-github-repo", eff.Action.EffectorAction, name)
assert.Equal(t, "github.com/acme/repo-1", eff.Target.Value, name)
require.Len(t, eff.Trigger.Subjects, 1, name)
require.NotNil(t, eff.Applied, name)
assert.Equal(t, "2026-12-01T10:00:00Z", eff.Applied.Refs["last_applied"], name)
}

for name, raw := range map[string]string{
"empty": ``,
"invalid": `{`,
"no id": `{"transition": "activated"}`,
} {
_, err := ParseEffect([]byte(raw))
assert.Error(t, err, name)
}
}

func TestParseTarget(t *testing.T) {
for name, tc := range map[string]struct {
target Target
want Repo
}{
"split": {Target{Scheme: SchemeRepo, Value: "github.com/acme/repo-1"}, Repo{"acme", "repo-1"}},
"identity only": {Target{Identity: "github-repo:github.com/Acme-2/my.repo_x"}, Repo{"Acme-2", "my.repo_x"}},
} {
got, err := ParseTarget(tc.target)
require.NoError(t, err, name)
assert.Equal(t, tc.want, got, name)
}
assert.Equal(t, "acme/repo-1", Repo{"acme", "repo-1"}.FullName())

for identity, want := range map[string]string{
"slack-channel:#alerts": `unsupported target scheme "slack-channel"`,
"github-repo:gitlab.com/acme/x": "doesn't match",
"github-repo:github.com/acme": "doesn't match",
"github-repo:github.com/a/b/c": "doesn't match",
"github-repo:github.com/acme/..": "isn't a repository name",
"github-repo:github.com/acme/.": "isn't a repository name",
"no-scheme": "unsupported target scheme",
} {
_, err := ParseTarget(Target{Identity: identity})
require.Error(t, err, identity)
assert.Contains(t, err.Error(), want, identity)
}
}
Loading
Loading