From a8336000d40279cf36f8564d469043dbb449862d Mon Sep 17 00:00:00 2001 From: "ccf-lisa[bot]" <286799724+ccf-lisa[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:27:57 -0300 Subject: [PATCH 1/4] feat: github-settings effector: apply, clear, reconcile and README The plugin itself: Describe (one remediate-apply capability on github-repo targets with the params schema), Configure, ValidateAction, Apply (enforce; dry-run only reports), Clear (nothing to undo), and Reconcile (enforce again, report what changed, failed or drifted), served with the agent's effector.Serve. The README documents parameters, token permissions, behaviour and an agent config example, and warns that apply removes real people's access. Co-Authored-By: Claude Opus 5.5 --- README.md | 180 +++++++++++++++++- go.mod | 4 +- internal/grpc_test.go | 76 ++++++++ internal/plugin.go | 257 +++++++++++++++++++++++++ internal/plugin_test.go | 405 ++++++++++++++++++++++++++++++++++++++++ main.go | 10 + 6 files changed, 925 insertions(+), 7 deletions(-) create mode 100644 internal/grpc_test.go create mode 100644 internal/plugin.go create mode 100644 internal/plugin_test.go create mode 100644 main.go diff --git a/README.md b/README.md index 8ab5a92..81b5615 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,177 @@ # effector-github-settings -A Compliance Framework (CCF) effector plugin that makes a GitHub repository's settings match -what a rule asks for, through the GitHub REST API: it removes direct collaborators (except -the ones a rule keeps), cancels their pending invitations, and sets web commit signoff. It runs -under the CCF agent's effector runtime, defaults to a dry-run that only reports what it would -change, and is specified in the API's `docs/effectors/lld/effector-github-settings.md`. +A Compliance Framework (CCF) **effector plugin** that makes a GitHub repository's settings +match what a rule asks for, through the GitHub REST API. While an effect is active, the plugin +**enforces the desired state the rule's parameters describe** on the effect's target +repository: it removes direct collaborators (except those you keep), cancels their pending +invitations, and sets web commit signoff. Repeats re-check, so drift (someone re-adds a +collaborator) is fixed again. + +> [!WARNING] +> In `apply` mode this plugin **removes real people's access** to your repositories: every +> direct collaborator not listed in `keep` loses access, and their pending invitations are +> cancelled. Nothing is undone when the effect clears. Start in `dry-run` (the default), read +> the plan it reports on the effect, and only then let a rule switch to `apply`, ideally with +> the operator holding `mode` locked (see the [example](#example-agent-config)). + +It doesn't map policies to fixes: the rule's `when` picks which evidence triggers it (for +example the `repository_team_access` policy failing), and its parameters say what the +repository should look like. The subjects only explain why the effect is active; the effect +view in CCF lists them. + +It implements the agent's `effector` contract (`github.com/compliance-framework/agent/effector`) +as specified in the API's `docs/effectors/lld/effector-github-settings.md`, with rule +parameters per `docs/effectors/action-parameters.md`. + +## Build + +```sh +make build # dist/plugin +make test # unit tests against a fake GitHub (httptest); never calls the real API +make lint # go vet and golangci-lint +``` + +Releases are tags: `.github/workflows/release.yml` builds with goreleaser and publishes +`ghcr.io/compliance-framework/effector-github-settings:` (and `:latest` for tags that +aren't release candidates). + +Until the agent and API releases that carry the effector runtime exist, `go.mod` points both +modules at sibling checkouts (`../agent`, `../api`), so check those out next to this +repository at their effectors branches. CI can't resolve them and fails until then. + +## Manifest + +One capability: + +| Field | Value | +| --- | --- | +| `effect` | `remediate-apply` | +| `rule_kinds` | `state` | +| `default_on_clear` | `none`: a fix isn't undone when the evidence passes | +| Target scheme | `github-repo`, value `^github\.com/[A-Za-z0-9-]+/[A-Za-z0-9._-]+$`, e.g. `github-repo:github.com/acme/repo-1` | + +## Configuration + +Plugin config (`plugins.

.config`, operator-only): + +| Key | Required | Meaning | +| --- | --- | --- | +| `token` | yes | GitHub token, or GitHub App installation token, with admin on the repositories; usually `${env:GITHUB_TOKEN}`. Never logged | +| `api_url` | no (`https://api.github.com`) | REST API base URL, for GitHub Enterprise Server (`https:///api/v3`). Must be `https`; `http` only for `localhost` (tests) | + +There's no action config: an action that sets any `config` key is rejected by +`ValidateAction`, pointing at `params.defaults`. + +### Token permissions + +The plugin reads and changes repository administration settings: + +- **Fine-grained token or GitHub App**: repository permission **Administration: read and + write** (collaborators, invitations and the web commit signoff setting), plus **Metadata: + read** (granted by default). +- **Classic token**: the `repo` scope, from a user with **admin** on the repositories. + +The plugin never removes the repository's owner. If the token's own user is a direct +collaborator on a repository, list it in `keep`, or it removes itself. + +## Rule parameters + +| Path | Type | Default | Meaning | +| --- | --- | --- | --- | +| `mode` | enum `dry-run`, `apply` | `dry-run` | `dry-run` reports what would change; `apply` changes it | +| `remediations.direct_collaborators.enabled` | boolean | `false` | Enforce direct collaborators | +| `remediations.direct_collaborators.keep` | string (max 1000), shown while `enabled` | `""` | Logins never removed (bots, break-glass accounts), separated by commas and/or spaces; case-insensitive, a leading `@` is ignored | +| `remediations.direct_collaborators.invitations` | boolean, shown while `enabled` | `true` | Also cancel pending direct invitations | +| `remediations.web_commit_signoff.enabled` | boolean | `false` | Enforce web commit signoff | +| `remediations.web_commit_signoff.value` | enum `required`, `not-required`, shown while `enabled` | `required` | What it should be: either direction can be enforced | + +Direct collaborators are enforced to **zero, except `keep`**: every user with direct access +(`GET /repos/{o}/{r}/collaborators?affiliation=direct`) not in `keep` is removed, and, with +`invitations`, every pending invitation not for a `keep` login is cancelled (invitations sent +to an email address can't be kept). Team access is untouched. An invalid login in `keep` fails +the effect with the field's error. + +## Behaviour + +| Transition | What the plugin does | +| --- | --- | +| `activated`, `updated`, `repeated`, `finished`, `redelivered` | Read the repository; compute the changes the enabled remediations need; in `apply` make them (collaborators, then invitations, then signoff), in `dry-run` don't (no `PATCH` or `DELETE` is sent) | +| `cleared`, `disabled`, `removed` (and `Clear`) | Nothing; `applied`, "nothing to undo" | +| `occurred` | `failed`: event rules aren't supported | + +`Reconcile` enforces again on every active or finished effect and reports the effects it +changed, that failed, or whose plan differs from the last one reported. + +Results: + +| Case | `status` | `message` | +| --- | --- | --- | +| Dry-run with changes | `applied` | `dry-run: would remove 3 direct collaborators (alice, bob, carol), cancel 1 invitation (dave), set web commit signoff to required` | +| Apply with changes | `applied` | `applied: removed 2 direct collaborators (alice, bob)` | +| Nothing to change | `applied` | `compliant: nothing to change` | +| No remediation enabled | `applied` | `no remediations enabled` | +| GitHub error | `failed` | `DELETE /repos/acme/repo-1/collaborators/carol: 403 Must have admin rights to Repository.; changed before the error: removed 2 direct collaborators (alice, bob)` | + +Apply stops at the first GitHub error; the changes made before it stay made and are listed. + +- `links`: the repository's access settings page only + (`https://github.com/{o}/{r}/settings/access`, rel `settings`). The API accepts `https` + links only, and the effect view already lists the subjects. +- `refs`: `{"last_plan": {...}, "last_applied": ""}`. `last_plan` holds `mode`, + `repository`, `remove_collaborators`, `cancel_invitations` (`id`, `login`), + `web_commit_signoff` and `kept`. A failed call sends only `last_plan`, so `last_applied` + stays the time of the last successful call. + +## Example agent config + +```yaml +daemon: true +api: + url: http://localhost:8080 +effector: + listen: 0.0.0.0:8443 + public_url: https://agent-github.example.test + +plugins: + github-settings: + type: effector + source: ghcr.io/compliance-framework/effector-github-settings: # or a local dist/plugin + config: + token: ${env:GITHUB_TOKEN} + # api_url: https://ghe.acme.example/api/v3 + actions: + fix-github-repo: + description: Enforce acme repository settings (dry-run until the operator unlocks it) + effect: remediate-apply + targets: + include: ["github-repo:github.com/acme/*"] + params: + defaults: + mode: dry-run + locked: [mode] +``` + +With `mode` locked, rules can choose the remediations but can't switch to `apply`; the +operator does that by changing `params.defaults.mode`, after reading the dry-run plans. + +A rule on evidence from the GitHub repositories plugin targets each failing repository with a +target expression over the subject's labels: + +```text +"organization" in subject.labels && "repository" in subject.labels + ? ["github-repo:github.com/" + subject.labels["organization"] + "/" + subject.labels["repository"]] + : [] +``` + +and sets, for example: + +```yaml +params: + remediations: + direct_collaborators: + enabled: true + keep: "acme-bot, break-glass" + web_commit_signoff: + enabled: true + value: required +``` diff --git a/go.mod b/go.mod index cb26695..c22d1c0 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,9 @@ replace github.com/compliance-framework/api => ../api require ( github.com/compliance-framework/agent v0.0.0-00010101000000-000000000000 github.com/compliance-framework/api v0.22.5 + github.com/hashicorp/go-plugin v1.8.0 github.com/stretchr/testify v1.12.1 + google.golang.org/grpc v1.85.0 google.golang.org/protobuf v1.36.12 ) @@ -32,7 +34,6 @@ require ( github.com/google/go-containerregistry v0.22.1 // indirect github.com/google/uuid v1.6.0 // indirect github.com/hashicorp/go-hclog v1.6.3 // indirect - github.com/hashicorp/go-plugin v1.8.0 // indirect github.com/hashicorp/yamux v0.1.2 // indirect github.com/lestrrat-go/blackmagic v1.0.4 // indirect github.com/lestrrat-go/dsig v1.4.0 // indirect @@ -63,5 +64,4 @@ require ( golang.org/x/sys v0.50.0 // indirect golang.org/x/text v0.44.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect - google.golang.org/grpc v1.85.0 // indirect ) diff --git a/internal/grpc_test.go b/internal/grpc_test.go new file mode 100644 index 0000000..96abd88 --- /dev/null +++ b/internal/grpc_test.go @@ -0,0 +1,76 @@ +package internal + +import ( + "context" + "testing" + "time" + + "github.com/compliance-framework/agent/effector" + "github.com/compliance-framework/agent/effector/proto" + "github.com/hashicorp/go-plugin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" +) + +// nopHelper is the agent side of EffectorHelper; the plugin doesn't call it. +type nopHelper struct{} + +func (nopHelper) ListEffects(context.Context, *proto.ListEffectsRequest) (*proto.ListEffectsResponse, error) { + return &proto.ListEffectsResponse{}, nil +} + +func (nopHelper) ReportStatus(context.Context, *proto.ReportStatusRequest) (*proto.ReportStatusResponse, error) { + return &proto.ReportStatusResponse{}, nil +} + +func (nopHelper) Observe(context.Context, *proto.ObserveRequest) (*proto.ObserveResponse, error) { + return nil, status.Error(codes.Unimplemented, "not used") +} + +func (nopHelper) GetContext(context.Context, *proto.GetContextRequest) (*proto.GetContextResponse, error) { + return nil, status.Error(codes.Unimplemented, "not used") +} + +// TestGRPCRoundTrip drives the plugin through the agent's go-plugin client, as the agent does. +func TestGRPCRoundTrip(t *testing.T) { + c, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + f := newFakeGitHub(t) + planRepo(f) + + client, _ := plugin.TestPluginGRPCConn(t, false, map[string]plugin.Plugin{ + effector.PluginName: &effector.EffectorGRPCPlugin{Impl: New()}, + }) + t.Cleanup(func() { _ = client.Close() }) + raw, err := client.Dispense(effector.PluginName) + require.NoError(t, err) + agent := raw.(*effector.GRPCClient) + + m, err := agent.Describe(c) + require.NoError(t, err) + assert.Equal(t, "github-settings", m.GetName()) + assert.Equal(t, paramsSchema, m.GetCapabilities()[0].GetParamsSchema()) + + cfg, err := structpb.NewStruct(map[string]any{"token": testToken, "api_url": f.url()}) + require.NoError(t, err) + _, err = agent.Configure(c, &proto.ConfigureRequest{Config: cfg}, nopHelper{}) + require.NoError(t, err) + + v, err := agent.ValidateAction(c, &proto.ValidateActionRequest{Action: "fix-github-repo", Effect: "remediate-apply"}) + require.NoError(t, err) + assert.Empty(t, v.GetErrors()) + + res, err := agent.Apply(c, request(t, effect(target1, TransitionActivated), enforceAll(ModeApply, "alice", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus(), res.GetMessage()) + assert.Equal(t, "applied: removed 3 direct collaborators (bob, carol, dependabot-ops), cancelled 3 invitations (dave, Dependabot-Ops, eve@example.com), set web commit signoff to required", res.GetMessage()) + assert.Equal(t, settingsV1, res.GetLinks()[0].GetHref()) + assert.Contains(t, res.GetRefs().AsMap(), "last_plan") + + res, err = agent.Clear(c, request(t, effect(target1, TransitionCleared), nil)) + require.NoError(t, err) + assert.Equal(t, "nothing to undo", res.GetMessage()) +} diff --git a/internal/plugin.go b/internal/plugin.go new file mode 100644 index 0000000..0a6805b --- /dev/null +++ b/internal/plugin.go @@ -0,0 +1,257 @@ +// Package internal implements the github-settings effector plugin: while an effect is active, +// it makes its target repository's settings match what the rule's parameters ask for. +package internal + +import ( + "context" + "encoding/json" + "fmt" + "reflect" + "strings" + "sync" + "time" + + "github.com/compliance-framework/agent/effector" + "github.com/compliance-framework/agent/effector/proto" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" +) + +const ( + pluginName = "github-settings" + effectType = "remediate-apply" + onClear = "none" +) + +const ( + msgNoneEnabled = "no remediations enabled" + msgNothingUndo = "nothing to undo" + msgEventRule = "event rules aren't supported: github-settings enforces state" +) + +// Plugin is the github-settings effector. +type Plugin struct { + mu sync.RWMutex + client *githubClient + + now func() time.Time +} + +var _ effector.Effector = (*Plugin)(nil) + +// New returns an unconfigured plugin. +func New() *Plugin { + return &Plugin{now: time.Now} +} + +// Describe returns the manifest: one remediate-apply capability on github-repo targets. +func (p *Plugin) Describe(context.Context) (*proto.Manifest, error) { + return &proto.Manifest{ + Name: pluginName, + Version: Version, + PluginConfigSchema: []byte(pluginConfigSchema), + Capabilities: []*proto.Capability{{ + Effect: effectType, + DefaultOnClear: onClear, + RuleKinds: []string{"state"}, + TargetSchemes: []*proto.TargetScheme{{ + Name: SchemeRepo, + ValuePattern: repoValuePattern, + Description: repoSchemeSummary, + Example: repoExample, + }}, + ActionConfigSchema: []byte(actionConfigSchema), + ParamsSchema: paramsSchema, + }}, + }, nil +} + +// Configure validates the plugin config. It doesn't call GitHub: a token's access is per +// repository, so it shows on each effect's result. +func (p *Plugin) Configure(_ context.Context, req *proto.ConfigureRequest, _ effector.Helper) (*proto.ConfigureResponse, error) { + cfg, err := ParsePluginConfig(req.GetConfig().AsMap()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + client, err := newGitHubClient(cfg) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + p.mu.Lock() + defer p.mu.Unlock() + p.client = client + return &proto.ConfigureResponse{}, nil +} + +// ValidateAction checks the effect and that the action sets no config (the plugin takes none). +func (p *Plugin) ValidateAction(_ context.Context, req *proto.ValidateActionRequest) (*proto.ValidateActionResponse, error) { + var errs []string + if e := req.GetEffect(); e != "" && e != effectType { + errs = append(errs, fmt.Sprintf("effect: %q is not supported (only %q)", e, effectType)) + } + errs = append(errs, ActionConfigErrors(req.GetConfig().AsMap())...) + return &proto.ValidateActionResponse{Errors: errs}, nil +} + +// Apply enforces the rule's parameters on the effect's repository (dry-run only reports). +func (p *Plugin) Apply(ctx context.Context, req *proto.EffectRequest) (*proto.Result, error) { + return p.handle(ctx, req, false).result, nil +} + +// Clear does nothing: a fix isn't undone when the evidence passes. +func (p *Plugin) Clear(ctx context.Context, req *proto.EffectRequest) (*proto.Result, error) { + return p.handle(ctx, req, true).result, nil +} + +// Reconcile enforces again on every active or finished effect, so drift (a collaborator +// re-added) is fixed between deliveries. It returns outcomes only for effects it changed, that +// failed, or whose plan differs from the one last reported (a dry-run that finds new drift). +func (p *Plugin) Reconcile(ctx context.Context, req *proto.ReconcileRequest) (*proto.ReconcileResponse, error) { + resp := &proto.ReconcileResponse{} + for _, er := range req.GetEffects() { + if ctx.Err() != nil { + break + } + eff, err := ParseEffect(er.GetEffectDocument()) + if err != nil || (eff.State != StateActive && eff.State != StateFinished) { + continue + } + o := p.enforce(ctx, er, eff) + if o.changed || o.result.GetStatus() == effector.StatusFailed || (o.plan != nil && planChanged(eff, o.plan)) { + resp.Outcomes = append(resp.Outcomes, &proto.ReconcileOutcome{EffectId: eff.ID, Result: o.result}) + } + } + return resp, nil +} + +// outcome is one call's result, plus what Reconcile needs to decide whether to report it. +type outcome struct { + result *proto.Result + plan *Plan + changed bool +} + +func (p *Plugin) handle(ctx context.Context, req *proto.EffectRequest, clear bool) outcome { + eff, err := ParseEffect(req.GetEffectDocument()) + if err != nil { + return outcome{result: failed(err.Error(), nil)} + } + switch t := eff.Transition; { + case clear, t == TransitionCleared, t == TransitionDisabled, t == TransitionRemoved: + res := &proto.Result{Status: effector.StatusApplied, Message: msgNothingUndo} + if repo, err := ParseTarget(eff.Target); err == nil { + res.Links = links(eff, repo, nil) + } + return outcome{result: res} + case t == TransitionActivated, t == TransitionUpdated, t == TransitionRepeated, + t == TransitionFinished, t == TransitionRedelivered, t == "": + return p.enforce(ctx, req, eff) + case t == TransitionOccurred: + return outcome{result: failed(msgEventRule, nil)} + default: + return outcome{result: failed(fmt.Sprintf("unknown transition %q", t), nil)} + } +} + +// enforce reads the repository, plans the changes the enabled remediations need, and makes +// them in apply mode. +func (p *Plugin) enforce(ctx context.Context, req *proto.EffectRequest, eff *Effect) outcome { + p.mu.RLock() + client := p.client + p.mu.RUnlock() + repo, err := ParseTarget(eff.Target) + if err != nil { + return outcome{result: failed(err.Error(), nil)} + } + lk := links(eff, repo, nil) + if client == nil { + return outcome{result: failed("plugin is not configured", lk)} + } + if errs := ActionConfigErrors(req.GetActionConfig().AsMap()); len(errs) > 0 { + return outcome{result: failed("invalid action config: "+strings.Join(errs, "; "), lk)} + } + params, keep, err := ParseParams(req) + if err != nil { + return outcome{result: failed(err.Error(), lk)} + } + if !params.anyEnabled() { + return outcome{result: &proto.Result{Status: effector.StatusApplied, Message: msgNoneEnabled, Links: lk}} + } + + st, err := read(ctx, client, repo, params) + if err != nil { + return outcome{result: failed(err.Error(), lk)} + } + lk = links(eff, repo, st.Repo) + plan := ComputePlan(repo, params, keep, st) + if params.Mode == ModeDryRun { + return outcome{result: p.applied(dryRunMessage(plan), lk, plan), plan: plan} + } + done, err := execute(ctx, client, repo, plan) + changed := !done.empty() + if err != nil { + res := failed(failedMessage(err, done), lk) + res.Refs = refs(plan, "") + return outcome{result: res, plan: plan, changed: changed} + } + return outcome{result: p.applied(appliedMessage(done), lk, plan), plan: plan, changed: changed} +} + +func (p *Plugin) applied(msg string, lk []*proto.Link, plan *Plan) *proto.Result { + return &proto.Result{ + Status: effector.StatusApplied, + Message: msg, + Links: lk, + Refs: refs(plan, p.now().UTC().Format(time.RFC3339)), + } +} + +func failed(msg string, lk []*proto.Link) *proto.Result { + return &proto.Result{Status: effector.StatusFailed, Message: msg, Links: lk} +} + +// refs are {"last_plan": {...}, "last_applied": ""}. A failed call sends only +// last_plan, so the API (which merges refs key by key) keeps the last successful time. +func refs(plan *Plan, appliedAt string) *structpb.Struct { + m := map[string]any{"last_plan": toJSONMap(plan)} + if appliedAt != "" { + m["last_applied"] = appliedAt + } + s, err := structpb.NewStruct(m) + if err != nil { + return nil + } + return s +} + +// planChanged reports whether plan differs from the last_plan the API sent back. +func planChanged(eff *Effect, plan *Plan) bool { + if eff.Applied == nil { + return true + } + return !reflect.DeepEqual(eff.Applied.Refs["last_plan"], toJSONMap(plan)) +} + +func toJSONMap(v any) map[string]any { + b, err := json.Marshal(v) + if err != nil { + return nil + } + var m map[string]any + if err := json.Unmarshal(b, &m); err != nil { + return nil + } + return m +} + +// links is the repository's access settings page. Subjects aren't linked: the effect view in +// CCF lists them already, and the API only accepts https links, which a CCF served over http +// (local setups) wouldn't give. +func links(_ *Effect, r Repo, repo *repository) []*proto.Link { + base := "https://github.com/" + r.FullName() + if repo != nil && strings.HasPrefix(repo.HTMLURL, "https://") { + base = strings.TrimSuffix(repo.HTMLURL, "/") + } + return []*proto.Link{{Rel: "settings", Href: base + "/settings/access", Title: r.FullName() + " access settings"}} +} diff --git a/internal/plugin_test.go b/internal/plugin_test.go new file mode 100644 index 0000000..2678ff1 --- /dev/null +++ b/internal/plugin_test.go @@ -0,0 +1,405 @@ +package internal + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/compliance-framework/agent/effector" + "github.com/compliance-framework/agent/effector/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" +) + +const ( + repo1 = "acme/repo-1" + target1 = "github-repo:github.com/acme/repo-1" + fixedNow = "2026-12-01T10:00:00Z" + settingsV1 = "https://github.com/acme/repo-1/settings/access" +) + +func newPlugin(t *testing.T, f *fakeGitHub) *Plugin { + t.Helper() + return newPluginWithToken(t, f, testToken) +} + +func newPluginWithToken(t *testing.T, f *fakeGitHub, token string) *Plugin { + t.Helper() + p := New() + now, _ := time.Parse(time.RFC3339, fixedNow) + p.now = func() time.Time { return now } + cfg, err := structpb.NewStruct(map[string]any{"token": token, "api_url": f.url()}) + require.NoError(t, err) + _, err = p.Configure(context.Background(), &proto.ConfigureRequest{Config: cfg}, nil) + require.NoError(t, err) + return p +} + +func effect(target, transition string) *Effect { + scheme, value, _ := strings.Cut(target, ":") + return &Effect{ + ID: "eff_7f3c", Generation: 1, Transition: transition, State: StateActive, + Rule: Rule{ID: "rul_19a2", Name: "No direct collaborators", Kind: "state"}, + Action: Action{RuleActionID: "act_55d1", EffectorAction: "fix-github-repo", Effect: effectType}, + Target: Target{Identity: target, Scheme: scheme, Value: value}, + Trigger: Trigger{Source: "evidence", Subjects: []Subject{ + {ID: "sub_1", Title: "repository_team_access: acme/repo-1", URL: "https://ccf.acme/evidence/sub_1"}, + }}, + } +} + +func request(t *testing.T, eff *Effect, params map[string]any) *proto.EffectRequest { + t.Helper() + doc, err := json.Marshal(eff) + require.NoError(t, err) + req := &proto.EffectRequest{Action: eff.Action.EffectorAction, EffectDocument: doc, OnClear: onClear} + if params != nil { + s, err := structpb.NewStruct(params) + require.NoError(t, err) + req.Params = s + } + return req +} + +// enforceAll enables both remediations, in mode, with keep and signoff value. +func enforceAll(mode, keep, signoff string) map[string]any { + return map[string]any{ + "mode": mode, + "remediations": map[string]any{ + "direct_collaborators": map[string]any{"enabled": true, "keep": keep, "invitations": true}, + "web_commit_signoff": map[string]any{"enabled": true, "value": signoff}, + }, + } +} + +func lastPlan(t *testing.T, res *proto.Result) map[string]any { + t.Helper() + require.NotNil(t, res.GetRefs()) + m, ok := res.GetRefs().AsMap()["last_plan"].(map[string]any) + require.True(t, ok, "refs.last_plan") + return m +} + +func TestDescribe(t *testing.T) { + m, err := New().Describe(context.Background()) + require.NoError(t, err) + assert.Equal(t, "github-settings", m.GetName()) + require.Len(t, m.GetCapabilities(), 1) + c := m.GetCapabilities()[0] + assert.Equal(t, "remediate-apply", c.GetEffect()) + assert.Equal(t, "none", c.GetDefaultOnClear()) + assert.Equal(t, []string{"state"}, c.GetRuleKinds()) + require.Len(t, c.GetTargetSchemes(), 1) + s := c.GetTargetSchemes()[0] + assert.Equal(t, "github-repo", s.GetName()) + assert.Equal(t, `^github\.com/[A-Za-z0-9-]+/[A-Za-z0-9._-]+$`, s.GetValuePattern()) + assert.Equal(t, paramsSchema, c.GetParamsSchema()) + for _, js := range [][]byte{m.GetPluginConfigSchema(), c.GetActionConfigSchema()} { + assert.True(t, json.Valid(js)) + } +} + +// Configure returns InvalidArgument for a bad plugin config (ParsePluginConfig's errors are +// tested in config_test.go), so the agent refuses the plugin at startup. +func TestConfigure(t *testing.T) { + for name, cfg := range map[string]map[string]any{ + "missing token": {}, + "plain http": {"token": "x", "api_url": "http://ghe.acme/api/v3"}, + } { + s, err := structpb.NewStruct(cfg) + require.NoError(t, err) + _, err = New().Configure(context.Background(), &proto.ConfigureRequest{Config: s}, nil) + require.Error(t, err, name) + assert.Equal(t, codes.InvalidArgument, status.Code(err), name) + } +} + +func TestValidateAction(t *testing.T) { + p := New() + v, err := p.ValidateAction(context.Background(), &proto.ValidateActionRequest{Action: "fix-github-repo", Effect: "remediate-apply"}) + require.NoError(t, err) + assert.Empty(t, v.GetErrors()) + + cfg, err := structpb.NewStruct(map[string]any{"keep": "alice"}) + require.NoError(t, err) + v, err = p.ValidateAction(context.Background(), &proto.ValidateActionRequest{Action: "fix-github-repo", Effect: "notify", Config: cfg}) + require.NoError(t, err) + require.Len(t, v.GetErrors(), 2) + assert.Contains(t, v.GetErrors()[0], `effect: "notify" is not supported`) + assert.Contains(t, v.GetErrors()[1], "keep: the github-settings plugin takes no action config") + assert.Contains(t, v.GetErrors()[1], "params.defaults") +} + +func TestDryRunListsWithoutWriting(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), enforceAll(ModeDryRun, "", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus(), res.GetMessage()) + assert.Equal(t, "dry-run: would remove 4 direct collaborators (Alice, bob, carol, dependabot-ops), cancel 3 invitations (dave, Dependabot-Ops, eve@example.com), set web commit signoff to required", res.GetMessage()) + assert.Empty(t, f.writes(), "dry-run never sends PATCH or DELETE") + assert.Equal(t, []string{"GET /repos/acme/repo-1", "GET /repos/acme/repo-1/collaborators", "GET /repos/acme/repo-1/invitations"}, f.recorded()) + + plan := lastPlan(t, res) + assert.Equal(t, "dry-run", plan["mode"]) + assert.Equal(t, repo1, plan["repository"]) + assert.Equal(t, []any{"Alice", "bob", "carol", "dependabot-ops"}, plan["remove_collaborators"]) + assert.Equal(t, []any{"acme"}, plan["kept"], "the owner is never removed") + assert.Equal(t, "required", plan["web_commit_signoff"]) + assert.Equal(t, fixedNow, res.GetRefs().AsMap()["last_applied"]) + + require.Len(t, res.GetLinks(), 1, "only https links: the settings page") + assert.Equal(t, &proto.Link{Rel: "settings", Href: settingsV1, Title: "acme/repo-1 access settings"}, res.GetLinks()[0]) + + before := f.repo(repo1) + assert.Len(t, before.collaborators, 5) + assert.Len(t, before.invitations, 3) + assert.False(t, before.signoff) +} + +func TestApplyRemovesAllButKeep(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), enforceAll(ModeApply, " ALICE, dependabot-OPS ", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus(), res.GetMessage()) + assert.Equal(t, "applied: removed 2 direct collaborators (bob, carol), cancelled 2 invitations (dave, eve@example.com), set web commit signoff to required", res.GetMessage()) + assert.Equal(t, []string{ + "DELETE /repos/acme/repo-1/collaborators/bob", + "DELETE /repos/acme/repo-1/collaborators/carol", + "DELETE /repos/acme/repo-1/invitations/7", + "DELETE /repos/acme/repo-1/invitations/3", + "PATCH /repos/acme/repo-1", + }, f.writes()) + + after := f.repo(repo1) + assert.ElementsMatch(t, []string{"Alice", "acme", "dependabot-ops"}, after.collaborators, "keep is case-insensitive") + assert.Equal(t, []fakeInvitation{{id: 9, login: "Dependabot-Ops"}}, after.invitations, "an invitation for a kept login stays") + assert.True(t, after.signoff) + assert.Equal(t, fixedNow, res.GetRefs().AsMap()["last_applied"]) + assert.Equal(t, "apply", lastPlan(t, res)["mode"]) + + // A repeat finds it compliant and changes nothing. + n := len(f.writes()) + res, err = p.Apply(testCtx(t), request(t, effect(target1, TransitionRepeated), enforceAll(ModeApply, "alice dependabot-ops", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus()) + assert.Equal(t, "compliant: nothing to change", res.GetMessage()) + assert.Len(t, f.writes(), n) +} + +func TestApplySignoffBothWays(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo(repo1, &fakeRepo{signoff: true}) + p := newPlugin(t, f) + onlySignoff := func(mode, value string) map[string]any { + return map[string]any{"mode": mode, "remediations": map[string]any{"web_commit_signoff": map[string]any{"enabled": true, "value": value}}} + } + + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), onlySignoff(ModeApply, SignoffNotRequired))) + require.NoError(t, err) + assert.Equal(t, "applied: set web commit signoff to not-required", res.GetMessage()) + assert.False(t, f.repo(repo1).signoff) + assert.Equal(t, []string{"GET /repos/acme/repo-1", "PATCH /repos/acme/repo-1"}, f.recorded(), "collaborators aren't read when not enforced") + + res, err = p.Apply(testCtx(t), request(t, effect(target1, TransitionUpdated), onlySignoff(ModeApply, SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, "applied: set web commit signoff to required", res.GetMessage()) + assert.True(t, f.repo(repo1).signoff) + + res, err = p.Apply(testCtx(t), request(t, effect(target1, TransitionRedelivered), onlySignoff(ModeDryRun, SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, "compliant: nothing to change", res.GetMessage()) +} + +func TestAlreadyCompliant(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo(repo1, &fakeRepo{collaborators: []string{"acme", "breakglass"}, signoff: true}) + p := newPlugin(t, f) + for _, mode := range []string{ModeDryRun, ModeApply} { + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), enforceAll(mode, "BreakGlass", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus()) + assert.Equal(t, "compliant: nothing to change", res.GetMessage(), mode) + } + assert.Empty(t, f.writes()) +} + +func TestGitHubErrorKeepsPartialChanges(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + f.failOn("DELETE /repos/acme/repo-1/collaborators/carol", 403, "Must have admin rights to Repository.") + p := newPlugin(t, f) + + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), enforceAll(ModeApply, "dependabot-ops", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusFailed, res.GetStatus()) + assert.Equal(t, "DELETE /repos/acme/repo-1/collaborators/carol: 403 Must have admin rights to Repository.; changed before the error: removed 2 direct collaborators (Alice, bob)", res.GetMessage()) + assert.ElementsMatch(t, []string{"carol", "acme", "dependabot-ops"}, f.repo(repo1).collaborators) + assert.False(t, f.repo(repo1).signoff, "stops at the first error") + refs := res.GetRefs().AsMap() + assert.Contains(t, refs, "last_plan") + assert.NotContains(t, refs, "last_applied", "a failure keeps the last successful time") + assert.Equal(t, settingsV1, res.GetLinks()[0].GetHref()) +} + +func TestGitHubNotFound(t *testing.T) { + f := newFakeGitHub(t) + p := newPlugin(t, f) + res, err := p.Apply(testCtx(t), request(t, effect("github-repo:github.com/acme/missing", TransitionActivated), enforceAll(ModeDryRun, "", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusFailed, res.GetStatus()) + assert.Equal(t, "GET /repos/acme/missing: 404 Not Found", res.GetMessage()) + assert.Equal(t, "https://github.com/acme/missing/settings/access", res.GetLinks()[0].GetHref()) +} + +func TestBadTokenIsNotLeaked(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPluginWithToken(t, f, "ghp_wrong-secret-value") + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), enforceAll(ModeDryRun, "", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusFailed, res.GetStatus()) + assert.Equal(t, "GET /repos/acme/repo-1: 401 Bad credentials", res.GetMessage()) + b, _ := json.Marshal(res.GetRefs().AsMap()) + assert.NotContains(t, res.String()+string(b), "wrong-secret") +} + +func TestInvalidParamsFail(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), enforceAll(ModeApply, "alice, bob/../x", SignoffRequired))) + require.NoError(t, err) + assert.Equal(t, effector.StatusFailed, res.GetStatus()) + assert.Equal(t, `invalid params: remediations.direct_collaborators.keep: "bob/../x" isn't a GitHub login`, res.GetMessage()) + assert.Empty(t, f.recorded()) +} + +func TestActionConfigAtApplyFails(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + req := request(t, effect(target1, TransitionActivated), enforceAll(ModeApply, "", SignoffRequired)) + req.ActionConfig, _ = structpb.NewStruct(map[string]any{"mode": "apply"}) + res, err := p.Apply(testCtx(t), req) + require.NoError(t, err) + assert.Equal(t, effector.StatusFailed, res.GetStatus()) + assert.Contains(t, res.GetMessage(), "invalid action config: mode: the github-settings plugin takes no action config") + assert.Empty(t, f.recorded()) +} + +func TestNoRemediationsEnabled(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + for _, params := range []map[string]any{nil, {"mode": "apply"}} { + res, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), params)) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus()) + assert.Equal(t, "no remediations enabled", res.GetMessage()) + } + assert.Empty(t, f.recorded()) +} + +func TestClearDoesNothing(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + params := enforceAll(ModeApply, "", SignoffRequired) + for _, tr := range []string{TransitionCleared, TransitionDisabled, TransitionRemoved} { + eff := effect(target1, tr) + eff.State = StateInactive + res, err := p.Clear(testCtx(t), request(t, eff, params)) + require.NoError(t, err) + assert.Equal(t, effector.StatusApplied, res.GetStatus()) + assert.Equal(t, "nothing to undo", res.GetMessage()) + assert.Equal(t, settingsV1, res.GetLinks()[0].GetHref()) + + res, err = p.Apply(testCtx(t), request(t, eff, params)) + require.NoError(t, err) + assert.Equal(t, "nothing to undo", res.GetMessage(), "Apply with a clearing transition") + } + assert.Empty(t, f.recorded()) +} + +func TestUnsupportedRequests(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + params := enforceAll(ModeApply, "", SignoffRequired) + + for name, tc := range map[string]struct { + eff *Effect + want string + }{ + "event rule": {effect(target1, TransitionOccurred), "event rules aren't supported"}, + "unknown": {effect(target1, "teleported"), `unknown transition "teleported"`}, + "wrong scheme": {effect("slack-channel:#alerts", TransitionActivated), `unsupported target scheme "slack-channel"`}, + "bad value": {effect("github-repo:gitlab.com/acme/x", TransitionActivated), "doesn't match"}, + "dot repo": {effect("github-repo:github.com/acme/..", TransitionActivated), "isn't a repository name"}, + } { + res, err := p.Apply(testCtx(t), request(t, tc.eff, params)) + require.NoError(t, err, name) + assert.Equal(t, effector.StatusFailed, res.GetStatus(), name) + assert.Contains(t, res.GetMessage(), tc.want, name) + } + res, err := p.Apply(testCtx(t), &proto.EffectRequest{EffectDocument: []byte("{")}) + require.NoError(t, err) + assert.Equal(t, effector.StatusFailed, res.GetStatus()) + + res, err = New().Apply(testCtx(t), request(t, effect(target1, TransitionActivated), params)) + require.NoError(t, err) + assert.Equal(t, "plugin is not configured", res.GetMessage()) + assert.Empty(t, f.recorded()) +} + +func TestReconcile(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + p := newPlugin(t, f) + params := enforceAll(ModeApply, "dependabot-ops", SignoffRequired) + + first, err := p.Apply(testCtx(t), request(t, effect(target1, TransitionActivated), params)) + require.NoError(t, err) + require.Equal(t, effector.StatusApplied, first.GetStatus(), first.GetMessage()) + + active := effect(target1, TransitionActivated) + active.Applied = &Applied{Generation: 1, Status: "applied", Refs: first.GetRefs().AsMap()} + inactive := effect(target1, TransitionCleared) + inactive.ID, inactive.State = "eff_old", StateInactive + reconcile := func() *proto.ReconcileResponse { + resp, err := p.Reconcile(testCtx(t), &proto.ReconcileRequest{Effects: []*proto.EffectRequest{ + request(t, active, params), request(t, inactive, params), + }}) + require.NoError(t, err) + return resp + } + + // Nothing drifted: no outcome (the compliant plan differs from the first one, which listed + // changes, so report it once, then stay quiet). + resp := reconcile() + require.Len(t, resp.GetOutcomes(), 1) + assert.Equal(t, "compliant: nothing to change", resp.GetOutcomes()[0].GetResult().GetMessage()) + active.Applied.Refs = resp.GetOutcomes()[0].GetResult().GetRefs().AsMap() + assert.Empty(t, reconcile().GetOutcomes()) + + // Someone re-adds a collaborator: reconcile removes it again. + f.mu.Lock() + f.repos[repo1].collaborators = append(f.repos[repo1].collaborators, "mallory") + f.mu.Unlock() + resp = reconcile() + require.Len(t, resp.GetOutcomes(), 1) + assert.Equal(t, "eff_7f3c", resp.GetOutcomes()[0].GetEffectId()) + assert.Equal(t, "applied: removed 1 direct collaborator (mallory)", resp.GetOutcomes()[0].GetResult().GetMessage()) + assert.NotContains(t, f.repo(repo1).collaborators, "mallory") +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..85d5bdf --- /dev/null +++ b/main.go @@ -0,0 +1,10 @@ +package main + +import ( + "github.com/compliance-framework/agent/effector" + "github.com/compliance-framework/effector-github-settings/internal" +) + +func main() { + effector.Serve(internal.New()) +} From d7b603cc1ec12f6efc1faf23b8bd1c86993eb2c4 Mon Sep 17 00:00:00 2001 From: "ccf-lisa[bot]" <286799724+ccf-lisa[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:58:36 -0300 Subject: [PATCH 2/4] docs: describe the release-please release flow in the README --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 81b5615..03ed6fc 100644 --- a/README.md +++ b/README.md @@ -31,9 +31,11 @@ make test # unit tests against a fake GitHub (httptest); never calls the real make lint # go vet and golangci-lint ``` -Releases are tags: `.github/workflows/release.yml` builds with goreleaser and publishes -`ghcr.io/compliance-framework/effector-github-settings:` (and `:latest` for tags that -aren't release candidates). +Releases go through release-please: merging its release PR tags `vX.Y.Z` and publishes the +GitHub release, then the shared release workflow builds it with goreleaser and publishes +`ghcr.io/compliance-framework/effector-github-settings:vX.Y.Z`, plus `:latest` for a final +release. Release candidates (`vX.Y.Z-rcN`, from the `cut-prerelease` workflow) never move +`:latest`. A PR labelled `preview` publishes `:pr-`. Until the agent and API releases that carry the effector runtime exist, `go.mod` points both modules at sibling checkouts (`../agent`, `../api`), so check those out next to this From 919e443f9724582eea6bd08020bd3c4be91a95ea Mon Sep 17 00:00:00 2001 From: "ccf-lisa[bot]" <286799724+ccf-lisa[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:49:43 -0300 Subject: [PATCH 3/4] docs: an App installation token expires after an hour The plugin reads token once at Configure. Document that an installation token needs external rotation and an agent restart, and prefer a fine-grained token. --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 03ed6fc..7907d9c 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ Plugin config (`plugins.

.config`, operator-only): | Key | Required | Meaning | | --- | --- | --- | -| `token` | yes | GitHub token, or GitHub App installation token, with admin on the repositories; usually `${env:GITHUB_TOKEN}`. Never logged | +| `token` | yes | GitHub token with admin on the repositories; usually `${env:GITHUB_TOKEN}`. Read once at start and never logged. See [token permissions](#token-permissions) for GitHub App installation tokens | | `api_url` | no (`https://api.github.com`) | REST API base URL, for GitHub Enterprise Server (`https:///api/v3`). Must be `https`; `http` only for `localhost` (tests) | There's no action config: an action that sets any `config` key is rejected by @@ -73,6 +73,12 @@ The plugin reads and changes repository administration settings: read** (granted by default). - **Classic token**: the `repo` scope, from a user with **admin** on the repositories. +The plugin reads `token` once, when the agent configures it, and can't refresh it. A GitHub App +**installation token expires after one hour**: with one, every effect fails with +`401 Bad credentials` an hour after start unless something outside the plugin mints a new +token and the agent restarts (which configures the plugin again). Prefer a fine-grained token +until the plugin takes App credentials and mints its own tokens. + The plugin never removes the repository's owner. If the token's own user is a direct collaborator on a repository, list it in `keep`, or it removes itself. From e7992bae08b42d085f623508ea8c81061124eff7 Mon Sep 17 00:00:00 2001 From: "ccf-lisa[bot]" <286799724+ccf-lisa[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:49:59 -0300 Subject: [PATCH 4/4] docs: a renamed or transferred repository fails, redirects aren't followed --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 7907d9c..c6109e6 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,12 @@ Results: Apply stops at the first GitHub error; the changes made before it stay made and are listed. +The plugin acts only on the repository the target names. GitHub redirects calls for a +renamed or transferred repository (301, 307) to its new location; the plugin doesn't follow +them and fails with `repository moved to …`, and it fails too when GitHub answers for a +repository whose `full_name` isn't the target's (case aside). Update the target, which the +action's target patterns must allow. + - `links`: the repository's access settings page only (`https://github.com/{o}/{r}/settings/access`, rel `settings`). The API accepts `https` links only, and the effect view already lists the subjects.