Skip to content
This repository was archived by the owner on Feb 3, 2026. It is now read-only.
Merged
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
73 changes: 42 additions & 31 deletions pkg/github/enterpriseuserwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import (
"errors"
"fmt"
"net/http"
"slices"

"github.com/google/go-github/v67/github"

"github.com/abcxyz/pkg/logging"
"github.com/abcxyz/team-link/v2/pkg/groupsync"
Expand Down Expand Up @@ -94,10 +97,12 @@ func (w *EnterpriseUserWriter) SetMembers(ctx context.Context, _ string, members
if scimUser.Active != nil && !*scimUser.Active {
continue
}
// Deactivate user who is not in desiredUsersMap
// Deactivate user who is not in desiredUsersMap and remove any role grants.
if _, ok := desiredUsersMap[username]; !ok {
logger.InfoContext(ctx, "deactivating user", "user", username)
if _, _, err := w.scimClient.DeactivateUser(ctx, *scimUser.ID); err != nil {
scimUser.Active = github.Bool(false)
scimUser.Roles = nil
if _, _, err := w.scimClient.UpdateUser(ctx, *scimUser.ID, scimUser); err != nil {
merr = errors.Join(merr, fmt.Errorf("failed to deactivate %q: %w", username, err))
}
}
Expand All @@ -112,41 +117,47 @@ func (w *EnterpriseUserWriter) SetMembers(ctx context.Context, _ string, members
break
}

scimUser, ok := currentUsersMap[username]
desiredUser := desiredUsersMap[username]

// Create the user if not found in currentUsersMap.
currentUser, ok := currentUsersMap[username]
if !ok {
// Create user if not found in currentUsersMap
logger.InfoContext(ctx, "creating user", "user", username)
if _, _, err := w.scimClient.CreateUser(ctx, desiredUsersMap[username]); err != nil {
if _, _, err := w.scimClient.CreateUser(ctx, desiredUser); err != nil {
merr = errors.Join(merr, fmt.Errorf("failed to create %q: %w", username, err))
}
} else {
// Reactivate user if user status is unknown or deactivated.
if scimUser.Active == nil || !*scimUser.Active {
logger.InfoContext(ctx, "deactivating user before reactivating",
"user", username,
"active", scimUser.Active,
)
deactivated, _, err := w.scimClient.DeactivateUser(ctx, *scimUser.ID)
if err != nil {
merr = errors.Join(merr, fmt.Errorf("failed to deactivate %q: %w", username, err))
}
logger.InfoContext(ctx, "reactivating user",
"user", deactivated.UserName,
"active", deactivated.Active,
)
if _, _, err := w.scimClient.ReactivateUser(ctx, *scimUser.ID); err != nil {
merr = errors.Join(merr, fmt.Errorf("failed to reactivate %q: %w", username, err))
}
updated, _, err := w.scimClient.GetUser(ctx, *scimUser.ID)
if err != nil {
merr = errors.Join(merr, fmt.Errorf("after reactivation, failed to get %q: %w", username, err))
}
logger.InfoContext(ctx, "reactivated user",
"user", updated.UserName,
"active", updated.Active,
)
continue
}

// Update the user if fields we care about have changed.
desiredUser.ID = currentUser.ID
desiredUser.Active = github.Bool(true)
if entUserNeedsUpdate(currentUser, desiredUser) {
logger.InfoContext(ctx, "updating user",
"user", username,
"before", currentUser,
"after", desiredUser,
)
if _, _, err := w.scimClient.UpdateUser(ctx, *currentUser.ID, desiredUser); err != nil {
merr = errors.Join(merr, fmt.Errorf("failed to update %q: %w", username, err))
}
}
}
return merr
}

func entUserNeedsUpdate(have, want *SCIMUser) bool {
if have.GetActive() != want.GetActive() {
return true
}
return !slices.Equal(entRoleNames(have), entRoleNames(want))
}

func entRoleNames(user *SCIMUser) []string {
roleNames := make([]string, 0, len(user.Roles))
for _, role := range user.Roles {
roleNames = append(roleNames, role.Value)
}
slices.Sort(roleNames)
return roleNames
}
143 changes: 143 additions & 0 deletions pkg/github/enterpriseuserwriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func TestEnterpriseUserWriter_SetMembers(t *testing.T) {
wantUsersOnServer: map[string]*SCIMUser{
"scim-id-user.old": {
SCIMUserAttributes: github.SCIMUserAttributes{
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
ID: github.String("scim-id-user.old"),
UserName: "user.old",
Active: github.Bool(false),
Expand Down Expand Up @@ -147,6 +148,7 @@ func TestEnterpriseUserWriter_SetMembers(t *testing.T) {
wantUsersOnServer: map[string]*SCIMUser{
"scim-id-user.one": {
SCIMUserAttributes: github.SCIMUserAttributes{
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
ID: github.String("scim-id-user.one"),
UserName: "user.one",
Active: github.Bool(false),
Expand Down Expand Up @@ -181,6 +183,7 @@ func TestEnterpriseUserWriter_SetMembers(t *testing.T) {
wantUsersOnServer: map[string]*SCIMUser{
"scim-id-user.one": {
SCIMUserAttributes: github.SCIMUserAttributes{
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
ID: github.String("scim-id-user.one"),
UserName: "user.one",
Active: github.Bool(true),
Expand Down Expand Up @@ -255,6 +258,7 @@ func TestEnterpriseUserWriter_SetMembers(t *testing.T) {
wantUsersOnServer: map[string]*SCIMUser{
"scim-id-user.old": {
SCIMUserAttributes: github.SCIMUserAttributes{
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
ID: github.String("scim-id-user.old"),
UserName: "user.old",
Active: github.Bool(false),
Expand Down Expand Up @@ -292,6 +296,145 @@ func TestEnterpriseUserWriter_SetMembers(t *testing.T) {
},
},
},
{
name: "chaging roles",
initialUsers: map[string]*SCIMUser{
"scim-id-nochange": {
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-nochange"),
UserName: "nochange",
Active: github.Bool(true),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
},
},
"scim-id-toadd": {
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-toadd"),
UserName: "toadd",
Active: github.Bool(true),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
},
},
"scim-id-toremove": {
Roles: []*SCIMUserRole{
{Value: "role_xyz"},
},
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-toremove"),
UserName: "toremove",
Active: github.Bool(true),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
},
},
"scim-id-todisable": {
Roles: []*SCIMUserRole{
{Value: "role_xyz"},
},
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-todisable"),
UserName: "todisable",
Active: github.Bool(true),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
},
},
},
desiredMembers: []groupsync.Member{
&groupsync.UserMember{
Usr: &groupsync.User{
ID: "nochange",
Attributes: &SCIMUser{
SCIMUserAttributes: github.SCIMUserAttributes{
UserName: "nochange",
},
},
},
},
&groupsync.UserMember{
Usr: &groupsync.User{
ID: "toadd",
Attributes: &SCIMUser{
Roles: []*SCIMUserRole{
{Value: "role_to_add"},
},
SCIMUserAttributes: github.SCIMUserAttributes{
UserName: "toadd",
},
},
},
},
&groupsync.UserMember{
Usr: &groupsync.User{
ID: "toremove",
Attributes: &SCIMUser{
SCIMUserAttributes: github.SCIMUserAttributes{
UserName: "toremove",
},
},
},
},
&groupsync.UserMember{
Usr: &groupsync.User{
ID: "tocreate",
Attributes: &SCIMUser{
Roles: []*SCIMUserRole{
{Value: "role_to_create"},
},
SCIMUserAttributes: github.SCIMUserAttributes{
UserName: "tocreate",
},
},
},
},
},
wantUsersOnServer: map[string]*SCIMUser{
"scim-id-tocreate": {
Roles: []*SCIMUserRole{
{Value: "role_to_create"},
},
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-tocreate"),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
UserName: "tocreate",
Active: github.Bool(true),
},
},
"scim-id-nochange": {
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-nochange"),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
UserName: "nochange",
Active: github.Bool(true),
},
},
"scim-id-toadd": {
Roles: []*SCIMUserRole{
{Value: "role_to_add"},
},
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-toadd"),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
UserName: "toadd",
Active: github.Bool(true),
},
},
"scim-id-toremove": {
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-toremove"),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
UserName: "toremove",
Active: github.Bool(true),
},
},
"scim-id-todisable": {
SCIMUserAttributes: github.SCIMUserAttributes{
ID: github.String("scim-id-todisable"),
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
UserName: "todisable",
Active: github.Bool(false),
},
},
},
},
}

for _, tc := range cases {
Expand Down
13 changes: 11 additions & 2 deletions pkg/github/scim.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"io"
"net/http"
"net/url"
"slices"
"strconv"
"strings"

Expand Down Expand Up @@ -83,6 +84,10 @@ type scimPatchPayload struct {
Operations []scimPatchOp `json:"Operations"`
}

const (
scimV2UserSchema = "urn:ietf:params:scim:schemas:core:2.0:User"
)

// NewSCIMClient creates a new client for the GHES SCIM API.
func NewSCIMClient(httpClient *http.Client, baseURL string) (*SCIMClient, error) {
u, err := url.Parse(strings.TrimSuffix(baseURL, "/") + ghesSCIMURLPath)
Expand Down Expand Up @@ -126,7 +131,9 @@ func (c *SCIMClient) ListUsers(ctx context.Context) (map[string]*SCIMUser, error
func (c *SCIMClient) CreateUser(ctx context.Context, user *SCIMUser) (*SCIMUser, *github.Response, error) {
path := "Users"
// Schema for POST: https://datatracker.ietf.org/doc/html/rfc7644#section-3.3
user.Schemas = append(user.Schemas, "urn:ietf:params:scim:schemas:core:2.0:User")
if !slices.Contains(user.Schemas, scimV2UserSchema) {
user.Schemas = append(user.Schemas, scimV2UserSchema)
}
user.Active = github.Bool(true)
var createdUser SCIMUser
resp, err := c.do(ctx, http.MethodPost, c.baseURL.ResolveReference(&url.URL{Path: path}).String(), user, &createdUser)
Expand All @@ -151,7 +158,9 @@ func (c *SCIMClient) GetUser(ctx context.Context, scimID string) (*SCIMUser, *gi
func (c *SCIMClient) UpdateUser(ctx context.Context, scimID string, user *SCIMUser) (*SCIMUser, *github.Response, error) {
path := fmt.Sprintf("Users/%s", scimID)
// Schema for PUT: https://datatracker.ietf.org/doc/html/rfc7644#section-3.5.1
user.Schemas = append(user.Schemas, "urn:ietf:params:scim:schemas:core:2.0:User")
if !slices.Contains(user.Schemas, scimV2UserSchema) {
user.Schemas = append(user.Schemas, scimV2UserSchema)
}
var updatedUser SCIMUser
resp, err := c.do(ctx, http.MethodPut, c.baseURL.ResolveReference(&url.URL{Path: path}).String(), user, &updatedUser)
if err != nil {
Expand Down
Loading