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
194 changes: 189 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,191 @@
# 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 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-<number>`.

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.<p>.config`, operator-only):

| Key | Required | Meaning |
| --- | --- | --- |
| `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://<host>/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 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.

## 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.

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.
- `refs`: `{"last_plan": {...}, "last_applied": "<RFC 3339>"}`. `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:<version> # 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
```
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand All @@ -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
Expand Down Expand Up @@ -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
)
76 changes: 76 additions & 0 deletions internal/grpc_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
Loading
Loading