Skip to content
Draft
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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,8 @@ INPUT_TEAM-SLUG=remarkable
# (preferred) or inline JSON. team-map-file wins when both are set.
# INPUT_TEAM-MAP-FILE=.github/github-teams.json
# INPUT_TEAM-MAP={"engineering@remarkable.no":"engineering"}
# Optional: map a group to an enterprise team by its "ent:" slug,
# e.g. {"platform@remarkable.no":"ent:platform"}. Requires the app to
# also be installed on the enterprise with the "Enterprise teams" permission.
# INPUT_GITHUB-ENTERPRISE=remarkable
# INPUT_GITHUB-ENTERPRISE-INSTALLATION-ID=456
51 changes: 50 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,53 @@ Notes:
`team-map: '{"engineering@remarkable.no":"engineering"}'`. `team-map-file`
takes precedence when both are set.

##### Enterprise teams

To sync a group into an [enterprise team](https://docs.github.com/en/enterprise-cloud@latest/rest/enterprise-teams/enterprise-team-members)
instead of an org team, use the enterprise team's slug. GitHub gives every
enterprise team slug an `ent:` prefix, and that prefix is how this tool tells
it apart from an org team. Org team slugs can't contain a colon, so the two
never collide.

```json
{
"engineering@remarkable.no": "engineering",
"platform@remarkable.no": "ent:platform"
}
```

The enterprise team endpoints only accept a token for an installation of the
app on the **enterprise**. The org installation can't call them. To set this up:

1. Change the app's visibility to `internal`. Apps with enterprise
permissions must be `internal` or `public` to be installed on an enterprise,
and the default `Only on this account` (private) blocks that. `internal`
still limits installs to your own enterprise. The app can stay owned by the
org.
1. Add the enterprise permission `Enterprise teams: Read and write`. The org
installation then has to accept the updated permissions.
1. As an enterprise owner, install the app on the enterprise via
`https://github.com/apps/<app-name>/installations/new` and note the
enterprise installation ID. The enterprise installation only receives the
enterprise permissions, and the org installation only receives the org
permissions.
1. Set `github-enterprise` (the enterprise slug) and
`github-enterprise-installation-id`. The same `github-app-id` and
`github-private-key` are used for both installations.

```yaml
with:
# ...the usual inputs...
github-enterprise: 'remarkable'
github-enterprise-installation-id: 67890
team-map-file: .github/github-teams.json
```

Enterprise teams follow the same rules as org teams: `add-users`/`remove-users`
gating, `max-remove-users`, the empty-group guard, `ignored-users` and
`dry-run`. When `add-users` is off, only users who are already members of (or
invited to) `github-org` are added.

Add a dependabot configuration to always get updates!

```yaml
Expand Down Expand Up @@ -233,6 +280,8 @@ them as `INPUT_<NAME>` environment variables (upper-cased input name).
| `ignored-users` | Comma separated list of user ids to totally ignore always, useful for owners of an org you don't want accidentally removed | `owner1,owner2` | `null` |
| `sync-team` | Set to TRUE to ensure every org member is added to the team named in `team-slug` | `TRUE` | `false` |
| `team-slug` | Slug of the team every org member should be added to, e.g. to grant PR rights to shared repos | `remarkable` | `null` |
| `team-map` | Inline JSON mapping a Google Workspace group email to a GitHub team slug; members of each group are synced into the mapped team | `{"eng@x":"eng"}` | `null` |
| `team-map` | Inline JSON mapping a Google Workspace group email to a GitHub team slug (use the `ent:`-prefixed slug for an enterprise team); members of each group are synced into the mapped team | `{"eng@x":"eng"}` | `null` |
| `team-map-file` | Path to a JSON file with the same group-to-team mapping as `team-map` (preferred for maintainability; wins if both are set) | `.github/teams.json` | `null` |
| `github-enterprise` | Enterprise slug that owns the `ent:` teams in the team map (required only if you map an enterprise team) | `remarkable` | `null` |
| `github-enterprise-installation-id` | Installation ID of the GitHub App on the enterprise (required only if you map an enterprise team) | `67890` | `null` |
| `debug` | Set to TRUE to enable debug level logging | `TRUE` | `false` |
8 changes: 7 additions & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,17 @@ inputs:
description: 'Slug of the team that every org member should be added to (e.g. remarkable)'
required: false
team-map:
description: 'Inline JSON object mapping a Google Workspace group email to a GitHub team slug, e.g. {"engineering@remarkable.no":"engineering"}. Members of each group are synced into the mapped team. Prefer team-map-file for maintainability. team-map-file takes precedence when both are set.'
description: 'Inline JSON object mapping a Google Workspace group email to a GitHub team slug, e.g. {"engineering@remarkable.no":"engineering"}. Use an enterprise team slug (GitHub prefixes these with "ent:", e.g. "ent:platform") to target an enterprise team (requires github-enterprise and github-enterprise-installation-id). Members of each group are synced into the mapped team. Prefer team-map-file for maintainability. team-map-file takes precedence when both are set.'
required: false
team-map-file:
description: 'Path to a JSON file mapping Google Workspace group emails to GitHub team slugs. Members of each group are synced into the mapped team.'
required: false
github-enterprise:
description: 'Enterprise slug owning the enterprise teams referenced in the team map by their "ent:" slug (e.g. {"platform@remarkable.no":"ent:platform"}). Required only when mapping enterprise teams.'
required: false
github-enterprise-installation-id:
description: 'Installation ID of the same GitHub App installed on the enterprise, with the "Enterprise teams" read/write permission. Required only when mapping enterprise teams.'
required: false
debug:
description: 'Set to TRUE to enable debug level logging'
required: false
Expand Down
61 changes: 59 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,19 @@ type Config struct {
SyncTeam bool
// TeamMap maps a Google Workspace group email (lower-cased) to the GitHub
// team slug whose membership should mirror that group. Empty when unset.
// Values starting with "ent:" (GitHub's enterprise team slug prefix) refer
// to enterprise teams; see ParseTeamRef.
TeamMap map[string]string
IgnoredUsers []string

// GitHubEnterprise is the enterprise slug owning any enterprise teams in
// TeamMap. GitHubEnterpriseInstallationID is the installation of the same
// GitHub App on that enterprise, which is distinct from the org
// installation. Both are required only when TeamMap references an
// enterprise team.
GitHubEnterprise string
GitHubEnterpriseInstallationID int64

GoogleEmailAddress string
GoogleCredentials GoogleCredentials
// GoogleCredentialsJSON retains the decoded credentials bytes for callers
Expand Down Expand Up @@ -109,9 +119,56 @@ func Load(src InputSource) (*Config, error) {
}
c.TeamMap = teamMap

c.GitHubEnterprise = strings.TrimSpace(src.GetInput("github-enterprise"))
if raw := strings.TrimSpace(src.GetInput("github-enterprise-installation-id")); raw != "" {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return nil, fmt.Errorf("github-enterprise-installation-id must be a number: %w", err)
}
c.GitHubEnterpriseInstallationID = id
}
if c.HasEnterpriseTeams() {
if c.GitHubEnterprise == "" {
return nil, fmt.Errorf("team map references enterprise teams but github-enterprise is not set")
}
if c.GitHubEnterpriseInstallationID == 0 {
return nil, fmt.Errorf("team map references enterprise teams but github-enterprise-installation-id is not set")
}
}

return c, nil
}

// EnterpriseTeamPrefix is the prefix GitHub gives every enterprise team slug.
// Team map values starting with it (e.g. "ent:platform") are enterprise teams;
// org team slugs can't contain a colon, so the two never collide.
const EnterpriseTeamPrefix = "ent:"

// TeamRef identifies a team targeted by the team map.
type TeamRef struct {
// Enterprise is true for enterprise teams, false for org teams.
Enterprise bool
// Slug is the team slug as GitHub knows it, including the "ent:" prefix
// for enterprise teams.
Slug string
}

// ParseTeamRef classifies a team map value. Values starting with "ent:" are
// enterprise team slugs; anything else is an org team slug.
func ParseTeamRef(value string) TeamRef {
return TeamRef{Enterprise: strings.HasPrefix(value, EnterpriseTeamPrefix), Slug: value}
}

// HasEnterpriseTeams reports whether any team map entry targets an enterprise team.
func (c *Config) HasEnterpriseTeams() bool {
for _, team := range c.TeamMap {
if ParseTeamRef(team).Enterprise {
return true
}
}
return false
}

// loadTeamMap resolves the group-to-team mapping from either a JSON file
// (team-map-file, preferred for maintainability) or inline JSON (team-map).
// The file takes precedence when both are set. Keys (group emails) are
Expand All @@ -131,14 +188,14 @@ func loadTeamMap(path, inline string) (map[string]string, error) {

var parsed map[string]string
if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
return nil, fmt.Errorf("team map is not valid JSON (expected {\"group@domain\":\"team-slug\"}): %w", err)
return nil, fmt.Errorf("team map is not valid JSON (expected {\"group@domain\":\"team-slug\"} or {\"group@domain\":\"ent:enterprise-team-slug\"}): %w", err)
}

out := make(map[string]string, len(parsed))
for group, slug := range parsed {
g := strings.TrimSpace(strings.ToLower(group))
s := strings.TrimSpace(slug)
if g == "" || s == "" {
if g == "" || s == "" || s == EnterpriseTeamPrefix {
continue
}
out[g] = s
Expand Down
69 changes: 69 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,72 @@ func TestTeamMapFileInvalidJSON(t *testing.T) {
t.Error("expected error for invalid JSON in team-map-file")
}
}

func TestTeamMapEnterpriseTeams(t *testing.T) {
inputs := validInputs()
inputs["github-enterprise"] = "acme"
inputs["github-enterprise-installation-id"] = "789"
inputs["team-map"] = `{"a@x":"ent:platform","b@x":" ent:infra ","d@x":"ent:","e@x":"eng"}`
cfg, err := Load(inputs)
if err != nil {
t.Fatal(err)
}
want := map[string]string{
"a@x": "ent:platform",
"b@x": "ent:infra",
"e@x": "eng",
}
if !reflect.DeepEqual(cfg.TeamMap, want) {
t.Errorf("TeamMap = %v, want %v", cfg.TeamMap, want)
}
if cfg.GitHubEnterprise != "acme" || cfg.GitHubEnterpriseInstallationID != 789 {
t.Errorf("enterprise = %q/%d, want acme/789", cfg.GitHubEnterprise, cfg.GitHubEnterpriseInstallationID)
}
if !cfg.HasEnterpriseTeams() {
t.Error("HasEnterpriseTeams should be true")
}
}

func TestParseTeamRef(t *testing.T) {
cases := map[string]TeamRef{
"eng": {Slug: "eng"},
"ent:platform": {Enterprise: true, Slug: "ent:platform"},
}
for in, want := range cases {
if got := ParseTeamRef(in); got != want {
t.Errorf("ParseTeamRef(%q) = %+v, want %+v", in, got, want)
}
}
}

func TestEnterpriseTeamsRequireEnterpriseConfig(t *testing.T) {
inputs := validInputs()
inputs["team-map"] = `{"a@x":"ent:platform"}`
if _, err := Load(inputs); err == nil {
t.Error("expected error when github-enterprise is missing")
}
inputs["github-enterprise"] = "acme"
if _, err := Load(inputs); err == nil {
t.Error("expected error when github-enterprise-installation-id is missing")
}
inputs["github-enterprise-installation-id"] = "nope"
if _, err := Load(inputs); err == nil {
t.Error("expected error for non-numeric github-enterprise-installation-id")
}
inputs["github-enterprise-installation-id"] = "789"
if _, err := Load(inputs); err != nil {
t.Errorf("unexpected error: %v", err)
}
}

func TestOrgOnlyTeamMapNeedsNoEnterpriseConfig(t *testing.T) {
inputs := validInputs()
inputs["team-map"] = `{"a@x":"eng"}`
cfg, err := Load(inputs)
if err != nil {
t.Fatal(err)
}
if cfg.HasEnterpriseTeams() {
t.Error("HasEnterpriseTeams should be false")
}
}
82 changes: 78 additions & 4 deletions internal/githuborg/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,21 @@ type api interface {
RemoveTeamMembership(ctx context.Context, org, slug, username string) error
}

// enterpriseAPI is the subset of the enterprise teams REST API used to sync
// enterprise team membership. It must be backed by a GitHub App installation on
// the enterprise (not the org), with the "Enterprise teams" permission.
type enterpriseAPI interface {
ListEnterpriseTeamMembers(ctx context.Context, enterprise, team string) ([]string, error)
AddEnterpriseTeamMember(ctx context.Context, enterprise, team, username string) error
RemoveEnterpriseTeamMember(ctx context.Context, enterprise, team, username string) error
}

// Service applies membership changes against a GitHub organisation.
type Service struct {
cfg *config.Config
api api
// ent is nil unless the team map references enterprise teams.
ent enterpriseAPI
}

// New builds a Service authenticated as the configured GitHub App installation.
Expand All @@ -50,7 +61,62 @@ func New(cfg *config.Config) (*Service, error) {
if err != nil {
return nil, fmt.Errorf("creating github client: %w", err)
}
return &Service{cfg: cfg, api: restAPI{client: client}}, nil
s := &Service{cfg: cfg, api: restAPI{client: client}}

if cfg.HasEnterpriseTeams() {
// Enterprise team endpoints need a token for the app's enterprise
// installation; the org installation token is rejected.
entTransport, err := newAppTransport(
http.DefaultTransport,
cfg.GitHubAppID,
cfg.GitHubEnterpriseInstallationID,
[]byte(cfg.GitHubPrivateKey),
)
if err != nil {
return nil, fmt.Errorf("creating github enterprise app transport: %w", err)
}
entClient, err := github.NewClient(github.WithHTTPClient(&http.Client{Transport: entTransport}))
if err != nil {
return nil, fmt.Errorf("creating github enterprise client: %w", err)
}
s.ent = restAPI{client: entClient}
}
return s, nil
}

// teamOps abstracts list/add/remove for a single team so SyncTeamMap can treat
// org teams and enterprise teams uniformly.
type teamOps struct {
list func(ctx context.Context) ([]string, error)
add func(ctx context.Context, username string) error
remove func(ctx context.Context, username string) error
}

// teamOpsFor resolves a team map value (see config.ParseTeamRef) to the API
// calls that manage that team.
func (s *Service) teamOpsFor(team string) (teamOps, error) {
ref := config.ParseTeamRef(team)
if !ref.Enterprise {
org := s.cfg.GitHubOrg
return teamOps{
list: func(ctx context.Context) ([]string, error) { return s.api.ListTeamMembers(ctx, org, ref.Slug) },
add: func(ctx context.Context, u string) error { return s.api.AddTeamMembership(ctx, org, ref.Slug, u) },
remove: func(ctx context.Context, u string) error { return s.api.RemoveTeamMembership(ctx, org, ref.Slug, u) },
}, nil
}
if s.ent == nil || s.cfg.GitHubEnterprise == "" {
return teamOps{}, fmt.Errorf("team %s is an enterprise team but github-enterprise / github-enterprise-installation-id are not configured", team)
}
ent := s.cfg.GitHubEnterprise
return teamOps{
list: func(ctx context.Context) ([]string, error) {
return s.ent.ListEnterpriseTeamMembers(ctx, ent, ref.Slug)
},
add: func(ctx context.Context, u string) error { return s.ent.AddEnterpriseTeamMember(ctx, ent, ref.Slug, u) },
remove: func(ctx context.Context, u string) error {
return s.ent.RemoveEnterpriseTeamMember(ctx, ent, ref.Slug, u)
},
}, nil
}

func (s *Service) isIgnored(user string) bool {
Expand Down Expand Up @@ -171,6 +237,10 @@ func (s *Service) SyncTeamMembers(ctx context.Context) error {
// can't invite people to the org as a side effect. It returns true when any
// team differed from its group (regardless of whether changes were applied) so
// callers can surface a mismatch exit code.
//
// Keys of desired are team map values: an org team slug, or an "ent:"-prefixed
// enterprise team slug in cfg.GitHubEnterprise. Both
// kinds go through the same add/remove gates and safety guards.
func (s *Service) SyncTeamMap(ctx context.Context, desired map[string]set.Set) (bool, error) {
slugs := make([]string, 0, len(desired))
for slug := range desired {
Expand All @@ -195,7 +265,11 @@ func (s *Service) SyncTeamMap(ctx context.Context, desired map[string]set.Set) (
drift := false
for _, slug := range slugs {
want := desired[slug]
currentRaw, err := s.api.ListTeamMembers(ctx, s.cfg.GitHubOrg, slug)
ops, err := s.teamOpsFor(slug)
if err != nil {
return drift, err
}
currentRaw, err := ops.list(ctx)
if err != nil {
return drift, fmt.Errorf("listing members of team %s: %w", slug, err)
}
Expand Down Expand Up @@ -227,7 +301,7 @@ func (s *Service) SyncTeamMap(ctx context.Context, desired map[string]set.Set) (
}
// Mirror SyncTeamMembers: log and continue past per-user failures
// (e.g. SAML SSO validation errors) rather than aborting.
if err := s.api.AddTeamMembership(ctx, s.cfg.GitHubOrg, slug, user); err != nil {
if err := ops.add(ctx, user); err != nil {
slog.Warn("skipping team add", "user", user, "team", slug, "err", err)
}
}
Expand Down Expand Up @@ -265,7 +339,7 @@ func (s *Service) SyncTeamMap(ctx context.Context, desired map[string]set.Set) (
slog.Info("dry run: skipping team remove", "user", user, "team", slug)
continue
}
if err := s.api.RemoveTeamMembership(ctx, s.cfg.GitHubOrg, slug, user); err != nil {
if err := ops.remove(ctx, user); err != nil {
slog.Warn("skipping team remove", "user", user, "team", slug, "err", err)
}
}
Expand Down
Loading