Skip to content
Closed
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
2 changes: 1 addition & 1 deletion config_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {}
}
],
Expand Down
3 changes: 2 additions & 1 deletion docs/connector.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/docs-info.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: The customer-facing docs/connector.mdx section "Optimize sync for large organizations" (around lines 494-504) was not updated. It still says repository access data "is equivalent" and does not mention that, with this option on, grants always create a direct collaborator and revokes leave team/org access in place. Please add the same note there (D1/BP3).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a direct-only grant and revoke note to the Optimize sync section in docs/connector.mdx in commit 7d9ce4c.


2. **For each item in the list above:**
- **How does a user create or look up that credential or info?**
Expand Down
4 changes: 3 additions & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
104 changes: 73 additions & 31 deletions pkg/connector/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: With the flag on, the GrantReplaced annotation is dropped even for users who are already direct collaborators. Example: a direct admin user is granted pull. AddCollaborator downgrades them, but C1 keeps the stale admin/maintain/push grants until the next sync. The PR description says this is deliberate. Still, a direct-only lookup (e.g. ListCollaborators with Affiliation: "direct" filtered to the login, or the sync's direct-collaborator source) would keep the replaced-grant signal without reintroducing the team-access short-circuit.

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),
})
}
}

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion (medium confidence): GitHub documents DELETE /repos/{owner}/{repo}/collaborators/{username} as returning 204, 403, or 422. A 404 is not its "not a collaborator" answer; GitHub uses 404 to hide permission failures. Treating any 404 as already revoked can report a revoke as successful when the token could not perform it. The new test only passes because the mock invents a 404 for non-collaborators. Consider removing the 404 carve-out, or documenting the vendor's 404 semantics on this call and checking IsCollaborator/direct membership before reporting success.

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 {
Expand Down
75 changes: 75 additions & 0 deletions pkg/connector/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
57 changes: 56 additions & 1 deletion test/mocks/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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{},
}
}

Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
Loading