diff --git a/config_schema.json b/config_schema.json index a52e1a8e..529028a3 100644 --- a/config_schema.json +++ b/config_schema.json @@ -178,7 +178,7 @@ { "name": "direct-collaborators-only", "displayName": "Optimize sync for large organizations", - "description": "Reduces API calls by using grant expansion for team-based repo access and skipping per-team detail fetches. Recommended for large orgs.", + "description": "Reduces API calls by using grant expansion for team-based repo access and skipping per-team detail fetches. Recommended for large orgs. With this option on, repository grants create a direct collaborator record and repository revokes remove only that record. Access through teams is separate and is not changed.", "boolField": {} } ], diff --git a/docs/connector.mdx b/docs/connector.mdx index 44b9279a..df4f5388 100644 --- a/docs/connector.mdx +++ b/docs/connector.mdx @@ -500,8 +500,9 @@ Enabling **Optimize sync for large organizations** (env var: `BATON_DIRECT_COLLA - **Direct collaborators only.** GitHub is asked only for users with direct repository access. Team-based access is reconstructed from team membership, which the connector already syncs separately. - **Skips per-team detail calls.** The `members_count` and `repos_count` profile fields are not synced for team resources. +- **Direct-only grant and revoke.** Repository grants always create a direct collaborator record. Repository revokes remove only that record. Access through teams or organization base permissions is not changed. -**Enable this option if** your GitHub organization has thousands of repositories or thousands of members and you want faster syncs and fewer API calls. Repository access data in C1 is equivalent — only the way grants are sourced (direct vs. team-expanded) differs. +**Enable this option if** your GitHub organization has thousands of repositories or thousands of members and you want faster syncs and fewer API calls. Repository access data in C1 is equivalent for sync — only the way grants are sourced (direct vs. team-expanded) differs. ## Troubleshooting diff --git a/docs/docs-info.md b/docs/docs-info.md index 05b4d086..b3ab3cee 100644 --- a/docs/docs-info.md +++ b/docs/docs-info.md @@ -73,7 +73,7 @@ `--sync-secrets` — sync fine-grained personal access tokens as API keys `--sync-last-activity` — emit the audit-log usage event feed. Hidden from `--help` and from the GUI config here, because it only applies to GitHub Enterprise audit-log access; `baton-github-enterprise` sets it directly instead of going through this CLI layer `--omit-archived-repositories` — skip archived repositories - `--direct-collaborators-only` — reduce API calls on large organizations + `--direct-collaborators-only` — reduce API calls on large organizations. With this option on, repository grants create a direct collaborator record, and repository revokes remove only that record. Access through teams is separate and is not changed 2. **For each item in the list above:** - **How does a user create or look up that credential or info?** diff --git a/pkg/config/config.go b/pkg/config/config.go index ecfb0d51..945d9af1 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -88,7 +88,9 @@ var ( field.WithDisplayName("Optimize sync for large organizations"), field.WithDescription( "Reduces API calls by using grant expansion for team-based repo access "+ - "and skipping per-team detail fetches. Recommended for large orgs.", + "and skipping per-team detail fetches. Recommended for large orgs. "+ + "With this option on, repository grants create a direct collaborator record "+ + "and repository revokes remove only that record. Access through teams is separate and is not changed.", ), ) orgField = field.StringField( diff --git a/pkg/connector/repository.go b/pkg/connector/repository.go index 84182754..2ba7ebb1 100644 --- a/pkg/connector/repository.go +++ b/pkg/connector/repository.go @@ -428,40 +428,15 @@ func (o *repositoryResourceType) Grant(ctx context.Context, principal *v2.Resour return nil, wrapGitHubError(err, resp, "github-connector: failed to get user") } - collaborator, resp, err := o.client.Repositories.IsCollaborator(ctx, repo.GetOwner().GetLogin(), repo.GetName(), user.GetLogin()) - if err != nil { - return nil, wrapGitHubError(err, resp, "github-connector: failed to check if user is a collaborator") - } - var replacedGrantID string - if collaborator { - permLevel, resp, err := o.client.Repositories.GetPermissionLevel(ctx, repo.GetOwner().GetLogin(), repo.GetName(), user.GetLogin()) + if !o.directCollaboratorsOnly { + var alreadyGranted bool + replacedGrantID, alreadyGranted, err = o.existingUserGrant(ctx, principal, en, repo, user.GetLogin(), permission) if err != nil { - return nil, wrapGitHubError(err, resp, "github-connector: failed to get user's repository permission") - } - - prevPermission := roleNameToRepoPermission(permLevel.GetRoleName()) - if prevPermission == "" { - // Custom repository role: fall back to the coarse permission (read/write/admin). - prevPermission = roleNameToRepoPermission(permLevel.GetPermission()) + return nil, err } - - switch prevPermission { - case permission: + if alreadyGranted { return annotations.New(&v2.GrantAlreadyExists{}), nil - case "": - l.Warn( - "github-connectorv2: unrecognized existing repository role, granting without GrantReplaced annotation", - zap.String("role_name", permLevel.GetRoleName()), - zap.String("permission", permLevel.GetPermission()), - ) - default: - // AddCollaborator overwrites the user's existing role, so report the - // old role's grant as replaced. GitHub permissions are cumulative; - // grants for other implied flags are reconciled at the next sync. - replacedGrantID = grant.NewGrantID(principal, &v2.Entitlement{ - Id: entitlement.NewEntitlementID(en.Resource, prevPermission), - }) } } @@ -504,6 +479,68 @@ func (o *repositoryResourceType) Grant(ctx context.Context, principal *v2.Resour return nil, nil } +func (o *repositoryResourceType) existingUserGrant( + ctx context.Context, + principal *v2.Resource, + en *v2.Entitlement, + repo *github.Repository, + login string, + permission string, +) (string, bool, error) { + l := ctxzap.Extract(ctx) + + var replacedGrantID string + collaborator, resp, err := o.client.Repositories.IsCollaborator(ctx, repo.GetOwner().GetLogin(), repo.GetName(), login) + if err != nil { + return "", false, wrapGitHubError(err, resp, "github-connector: failed to check if user is a collaborator") + } + + if collaborator { + permLevel, resp, err := o.client.Repositories.GetPermissionLevel(ctx, repo.GetOwner().GetLogin(), repo.GetName(), login) + if err != nil { + return "", false, wrapGitHubError(err, resp, "github-connector: failed to get user's repository permission") + } + + prevPermission := roleNameToRepoPermission(permLevel.GetRoleName()) + if prevPermission == "" { + // Custom repository role: fall back to the coarse permission (read/write/admin). + prevPermission = roleNameToRepoPermission(permLevel.GetPermission()) + } + + switch prevPermission { + case permission: + return "", true, nil + case "": + l.Warn( + "github-connectorv2: unrecognized existing repository role, granting without GrantReplaced annotation", + zap.String("role_name", permLevel.GetRoleName()), + zap.String("permission", permLevel.GetPermission()), + ) + default: + // AddCollaborator overwrites the user's existing role, so report the + // old role's grant as replaced. GitHub permissions are cumulative; + // grants for other implied flags are reconciled at the next sync. + replacedGrantID = grant.NewGrantID(principal, &v2.Entitlement{ + Id: entitlement.NewEntitlementID(en.Resource, prevPermission), + }) + } + } + + return replacedGrantID, false, nil +} + +func (o *repositoryResourceType) warnIfAccessRemains(ctx context.Context, repo *github.Repository, login string) { + hasAccess, _, err := o.client.Repositories.IsCollaborator(ctx, repo.GetOwner().GetLogin(), repo.GetName(), login) + if err != nil || !hasAccess { + return + } + ctxzap.Extract(ctx).Warn( + "github-connectorv2: user still has repository access through a team or organization permission after direct collaborator removal", + zap.String("repository", repo.GetFullName()), + zap.String("user", login), + ) +} + func (o *repositoryResourceType) Revoke(ctx context.Context, grant *v2.Grant) (annotations.Annotations, error) { l := ctxzap.Extract(ctx) @@ -535,9 +572,14 @@ func (o *repositoryResourceType) Revoke(ctx context.Context, grant *v2.Grant) (a } resp, er := o.client.Repositories.RemoveCollaborator(ctx, repo.GetOwner().GetLogin(), repo.GetName(), user.GetLogin()) - if er != nil { + alreadyRevoked := o.directCollaboratorsOnly && resp != nil && resp.StatusCode == http.StatusNotFound + if er != nil && !alreadyRevoked { return nil, wrapGitHubError(er, resp, "github-connector: failed to remove user from repository") } + + if o.directCollaboratorsOnly { + o.warnIfAccessRemains(ctx, repo, user.GetLogin()) + } case resourceTypeTeam.Id: team, resp, err := o.client.Teams.GetTeamByID(ctx, org.GetID(), principalID) //nolint:staticcheck,nolintlint // TODO: migrate to GetTeamBySlug if err != nil { diff --git a/pkg/connector/repository_test.go b/pkg/connector/repository_test.go index 18460ee6..339f4d8f 100644 --- a/pkg/connector/repository_test.go +++ b/pkg/connector/repository_test.go @@ -221,3 +221,78 @@ func TestOrgBasePermissionToRepoPermissions(t *testing.T) { }) } } + +func TestRepositoryGrantRevokeDirectCollaborators(t *testing.T) { + ctx := context.Background() + + const ( + repoID = int64(34) + userID = int64(56) + ) + + setup := func(t *testing.T, directOnly bool) (*mocks.MockGitHub, *repositoryResourceType, *v2.Resource, *v2.Resource, *v2.Entitlement) { + t.Helper() + mgh := mocks.NewMockGitHub() + githubOrganization, githubRepository, _, githubUser, _, _ := mgh.Seed() + + githubClient := newTestGitHubClient(t, mgh.Server()) + builder := RepositoryBuilder(githubClient, newOrgNameCache(githubClient), false, directOnly) + + organization, err := organizationResource(ctx, githubOrganization, nil, false) + require.NoError(t, err) + repository, err := repositoryResource(ctx, githubRepository, organization.Id) + require.NoError(t, err) + user, err := userResource(ctx, githubUser, *githubUser.Email, nil) + require.NoError(t, err) + en := &v2.Entitlement{ + Id: entitlement2.NewEntitlementID(repository, repoPermissionPush), + Resource: repository, + } + return mgh, builder, repository, user, en + } + + hasGrantAlreadyExists := func(t *testing.T, annos annotations.Annotations) bool { + t.Helper() + found, err := annos.Pick(&v2.GrantAlreadyExists{}) + require.NoError(t, err) + return found + } + + t.Run("grant with flag on adds collaborator despite effective team access", func(t *testing.T) { + mgh, builder, _, user, en := setup(t, true) + mgh.SetRepositoryRole(repoID, userID, "write") + + annos, err := builder.Grant(ctx, user, en) + require.NoError(t, err) + require.False(t, hasGrantAlreadyExists(t, annos)) + require.Equal(t, []string{repoPermissionPush}, mgh.AddedCollaboratorPermissions(repoID)) + }) + + t.Run("grant with flag off reports existing permission", func(t *testing.T) { + mgh, builder, _, user, en := setup(t, false) + mgh.SetRepositoryRole(repoID, userID, "write") + + annos, err := builder.Grant(ctx, user, en) + require.NoError(t, err) + require.True(t, hasGrantAlreadyExists(t, annos)) + require.Empty(t, mgh.AddedCollaboratorPermissions(repoID)) + }) + + t.Run("revoke with flag on treats non-direct user as already revoked", func(t *testing.T) { + _, builder, _, user, en := setup(t, true) + + annos, err := builder.Revoke(ctx, &v2.Grant{Entitlement: en, Principal: user}) + require.NoError(t, err) + require.Empty(t, annos) + }) + + t.Run("revoke with flag on succeeds when team access remains", func(t *testing.T) { + mgh, builder, _, user, en := setup(t, true) + mgh.AddRepositoryCollaborator(repoID, userID) + mgh.SetRepositoryRole(repoID, userID, "write") + + annos, err := builder.Revoke(ctx, &v2.Grant{Entitlement: en, Principal: user}) + require.NoError(t, err) + require.Empty(t, annos) + }) +} diff --git a/test/mocks/github.go b/test/mocks/github.go index 5757536d..a2351e77 100644 --- a/test/mocks/github.go +++ b/test/mocks/github.go @@ -24,6 +24,8 @@ type MockGitHub struct { users map[int64]github.User orgRoles map[int64]mapset.Set[int64] // Maps role ID to set of user IDs SimulateOrgRolePermErr bool // Simulate permission error for org roles + repositoryRoles map[int64]map[int64]string // Effective repository role by repository ID and user ID + addedCollaborators map[int64][]string // Permissions requested through AddCollaborator by repository ID } func NewMockGitHub() *MockGitHub { @@ -36,6 +38,8 @@ func NewMockGitHub() *MockGitHub { teams: map[int64]github.Team{}, users: map[int64]github.User{}, orgRoles: map[int64]mapset.Set[int64]{}, + repositoryRoles: map[int64]map[int64]string{}, + addedCollaborators: map[int64][]string{}, } } @@ -460,15 +464,40 @@ func (mgh MockGitHub) getRepositoryCollaborator( w http.ResponseWriter, variables map[string]string, ) { + repoID, _ := getCrossTableId(w, variables, "repo") + userID, _ := getUserId(w, variables) + if _, ok := mgh.repositoryRoles[repoID][userID]; ok { + w.WriteHeader(http.StatusNoContent) + return + } user := mgh.getUserFromCrossTable( w, variables, mgh.repositoryMemberships, - "repository_id", + "repo", ) + if user == nil { + return + } _, _ = w.Write(mock.MustMarshal(user)) } +func (mgh MockGitHub) getRepositoryPermissionLevel( + w http.ResponseWriter, + variables map[string]string, +) { + repoID, _ := getCrossTableId(w, variables, "repo") + userID, _ := getUserId(w, variables) + role, ok := mgh.repositoryRoles[repoID][userID] + if !ok { + role = "none" + } + _, _ = w.Write(mock.MustMarshal(github.RepositoryPermissionLevel{ + Permission: &role, + RoleName: &role, + })) +} + func (mgh MockGitHub) addMembership( w http.ResponseWriter, variables map[string]string, @@ -485,6 +514,8 @@ func (mgh MockGitHub) addRepositoryCollaborator( w http.ResponseWriter, variables map[string]string, ) { + repoID, _ := getCrossTableId(w, variables, "repo") + mgh.addedCollaborators[repoID] = append(mgh.addedCollaborators[repoID], variables["permission"]) mgh.addUserToCrossTable( w, variables, @@ -509,12 +540,20 @@ func (mgh MockGitHub) removeRepositoryCollaborator( w http.ResponseWriter, variables map[string]string, ) { + repoID, _ := getCrossTableId(w, variables, "repo") + userID, _ := getUserId(w, variables) + memberships, ok := mgh.repositoryMemberships[repoID] + if !ok || !memberships.Contains(userID) { + w.WriteHeader(http.StatusNotFound) + return + } mgh.removeUserFromCrossTable( w, variables, mgh.repositoryMemberships, "repo", ) + w.WriteHeader(http.StatusNoContent) } type OrganizationRole struct { @@ -749,6 +788,7 @@ func (mgh MockGitHub) Server() *http.Client { mock.GetOrgsMembershipsByOrgByUsername: mgh.getMembership, mock.GetReposCollaboratorsByOwnerByRepo: mgh.getRepositoryCollaborators, mock.GetReposCollaboratorsByOwnerByRepoByUsername: mgh.getRepositoryCollaborator, + mock.GetReposCollaboratorsPermissionByOwnerByRepoByUsername: mgh.getRepositoryPermissionLevel, mock.GetReposTeamsByOwnerByRepo: mgh.getRepositoryTeams, mock.PostOrgsInvitationsByOrg: mgh.addUser, mock.PutReposCollaboratorsByOwnerByRepoByUsername: mgh.addRepositoryCollaborator, @@ -804,6 +844,21 @@ func (mgh *MockGitHub) AddRepositoryCollaborator(repoID int64, userID int64) { mgh.repositoryMemberships[repoID].Add(userID) } +// SetRepositoryRole sets the effective role a user has on a repository, such as +// access inherited from a team, for testing purposes. +func (mgh *MockGitHub) SetRepositoryRole(repoID int64, userID int64, role string) { + if _, ok := mgh.repositoryRoles[repoID]; !ok { + mgh.repositoryRoles[repoID] = map[int64]string{} + } + mgh.repositoryRoles[repoID][userID] = role +} + +// AddedCollaboratorPermissions returns the permissions requested through +// AddCollaborator calls for a repository. +func (mgh *MockGitHub) AddedCollaboratorPermissions(repoID int64) []string { + return mgh.addedCollaborators[repoID] +} + // AddMembership adds a user to a team for testing purposes. func (mgh *MockGitHub) AddMembership(teamID int64, userID int64) { if _, ok := mgh.teamMemberships[teamID]; !ok {