@@ -8,14 +8,17 @@ import (
88 "log/slog"
99 "net/http"
1010 "os"
11+ "sort"
1112 "strings"
13+ "sync"
1214 "time"
1315
1416 "cloud.google.com/go/compute/metadata"
1517 "github.com/coreos/go-oidc/v3/oidc"
1618 "golang.org/x/exp/slices"
1719 "golang.org/x/oauth2"
1820 "golang.org/x/oauth2/google"
21+ "golang.org/x/sync/errgroup"
1922 admin "google.golang.org/api/admin/directory/v1"
2023 "google.golang.org/api/impersonate"
2124 "google.golang.org/api/option"
@@ -27,6 +30,10 @@ import (
2730const (
2831 issuerURL = "https://accounts.google.com"
2932 wildcardDomainToAdminEmail = "*"
33+
34+ // defaultConcurrentGroupLookups is the limit used when Config.MaxConcurrentGroupLookups
35+ // is zero or negative.
36+ defaultConcurrentGroupLookups = 10
3037)
3138
3239// Config holds configuration options for Google logins.
@@ -61,6 +68,10 @@ type Config struct {
6168 // If this field is true, fetch direct group membership and transitive group membership
6269 FetchTransitiveGroupMembership bool `json:"fetchTransitiveGroupMembership"`
6370
71+ // MaxConcurrentGroupLookups limits concurrent Admin Directory API calls when resolving
72+ // transitive group membership. If zero or negative, the connector default limit applies.
73+ MaxConcurrentGroupLookups int `json:"maxConcurrentGroupLookups"`
74+
6475 // Optional value for the prompt parameter, defaults to consent when offline_access
6576 // scope is requested
6677 PromptType * string `json:"promptType"`
@@ -119,6 +130,11 @@ func (c *Config) Open(id string, logger *slog.Logger) (conn connector.Connector,
119130 }
120131
121132 clientID := c .ClientID
133+ maxConcurrent := c .MaxConcurrentGroupLookups
134+ if maxConcurrent <= 0 {
135+ maxConcurrent = defaultConcurrentGroupLookups
136+ }
137+
122138 return & googleConnector {
123139 redirectURI : c .RedirectURI ,
124140 oauth2Config : & oauth2.Config {
@@ -138,6 +154,7 @@ func (c *Config) Open(id string, logger *slog.Logger) (conn connector.Connector,
138154 serviceAccountFilePath : c .ServiceAccountFilePath ,
139155 domainToAdminEmail : c .DomainToAdminEmail ,
140156 fetchTransitiveGroupMembership : c .FetchTransitiveGroupMembership ,
157+ maxConcurrentGroupLookups : maxConcurrent ,
141158 adminSrv : adminSrv ,
142159 promptType : promptType ,
143160 }, nil
@@ -159,6 +176,7 @@ type googleConnector struct {
159176 serviceAccountFilePath string
160177 domainToAdminEmail map [string ]string
161178 fetchTransitiveGroupMembership bool
179+ maxConcurrentGroupLookups int
162180 adminSrv map [string ]* admin.Service
163181 promptType string
164182}
@@ -263,8 +281,7 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector
263281
264282 var groups []string
265283 if s .Groups && len (c .adminSrv ) > 0 {
266- checkedGroups := make (map [string ]struct {})
267- groups , err = c .getGroups (claims .Email , c .fetchTransitiveGroupMembership , checkedGroups )
284+ groups , err = c .getGroups (ctx , claims .Email , c .fetchTransitiveGroupMembership )
268285 if err != nil {
269286 return identity , fmt .Errorf ("google: could not retrieve groups: %v" , err )
270287 }
@@ -289,52 +306,107 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector
289306}
290307
291308// getGroups creates a connection to the admin directory service and lists
292- // all groups the user is a member of
293- func (c * googleConnector ) getGroups (email string , fetchTransitiveGroupMembership bool , checkedGroups map [string ]struct {}) ([]string , error ) {
294- var userGroups []string
295- var err error
296- groupsList := & admin.Groups {}
297- domain := c .extractDomainFromEmail (email )
298- adminSrv , err := c .findAdminService (domain )
309+ // all groups the user is a member of.
310+ func (c * googleConnector ) getGroups (ctx context.Context , email string , fetchTransitiveGroupMembership bool ) ([]string , error ) {
311+ directGroups , err := c .listGroupEmails (ctx , email )
299312 if err != nil {
300313 return nil , err
301314 }
302315
303- for {
304- groupsList , err = adminSrv .Groups .List ().
305- UserKey (email ).PageToken (groupsList .NextPageToken ).Do ()
306- if err != nil {
307- return nil , fmt .Errorf ("could not list groups: %v" , err )
316+ var seenMu sync.Mutex
317+ seen := make (map [string ]struct {})
318+ userGroups := make ([]string , 0 , len (directGroups ))
319+ addGroup := func (groupEmail string ) bool {
320+ seenMu .Lock ()
321+ defer seenMu .Unlock ()
322+ if _ , exists := seen [groupEmail ]; exists {
323+ return false
308324 }
325+ seen [groupEmail ] = struct {}{}
326+ // TODO (joelspeed): Make desired group key configurable
327+ userGroups = append (userGroups , groupEmail )
328+ return true
329+ }
309330
310- for _ , group := range groupsList .Groups {
311- if _ , exists := checkedGroups [group .Email ]; exists {
312- continue
313- }
331+ seeds := make ([]string , 0 , len (directGroups ))
332+ for _ , groupEmail := range directGroups {
333+ if addGroup (groupEmail ) {
334+ seeds = append (seeds , groupEmail )
335+ }
336+ }
337+
338+ if ! fetchTransitiveGroupMembership || len (seeds ) == 0 {
339+ sort .Strings (userGroups )
340+ return userGroups , nil
341+ }
314342
315- checkedGroups [group .Email ] = struct {}{}
316- // TODO (joelspeed): Make desired group key configurable
317- userGroups = append (userGroups , group .Email )
343+ apiSem := make (chan struct {}, c .maxConcurrentGroupLookups )
344+ g , gctx := errgroup .WithContext (ctx )
318345
319- if ! fetchTransitiveGroupMembership {
320- continue
346+ var enqueue func (string )
347+ enqueue = func (groupEmail string ) {
348+ g .Go (func () error {
349+ if err := gctx .Err (); err != nil {
350+ return err
351+ }
352+ select {
353+ case <- gctx .Done ():
354+ return gctx .Err ()
355+ case apiSem <- struct {}{}:
321356 }
357+ defer func () { <- apiSem }()
322358
323- // getGroups takes a user's email/alias as well as a group's email/alias
324- transitiveGroups , err := c .getGroups (group .Email , fetchTransitiveGroupMembership , checkedGroups )
359+ parentGroups , err := c .listGroupEmails (gctx , groupEmail )
325360 if err != nil {
326- return nil , fmt .Errorf ("could not list transitive groups: %v" , err )
361+ return fmt .Errorf ("could not list transitive groups: %w" , err )
362+ }
363+ for _ , parent := range parentGroups {
364+ if addGroup (parent ) {
365+ enqueue (parent )
366+ }
327367 }
368+ return nil
369+ })
370+ }
371+
372+ for _ , groupEmail := range seeds {
373+ enqueue (groupEmail )
374+ }
375+
376+ if err := g .Wait (); err != nil {
377+ return nil , err
378+ }
328379
329- userGroups = append (userGroups , transitiveGroups ... )
380+ sort .Strings (userGroups )
381+ return userGroups , nil
382+ }
383+
384+ func (c * googleConnector ) listGroupEmails (ctx context.Context , userKey string ) ([]string , error ) {
385+ domain := c .extractDomainFromEmail (userKey )
386+ adminSrv , err := c .findAdminService (domain )
387+ if err != nil {
388+ return nil , err
389+ }
390+
391+ groupEmails := []string {}
392+ groupsList := & admin.Groups {}
393+ for {
394+ groupsList , err = adminSrv .Groups .List ().
395+ UserKey (userKey ).PageToken (groupsList .NextPageToken ).Context (ctx ).Do ()
396+ if err != nil {
397+ return nil , fmt .Errorf ("could not list groups: %v" , err )
398+ }
399+
400+ for _ , group := range groupsList .Groups {
401+ groupEmails = append (groupEmails , group .Email )
330402 }
331403
332404 if groupsList .NextPageToken == "" {
333405 break
334406 }
335407 }
336408
337- return userGroups , nil
409+ return groupEmails , nil
338410}
339411
340412func (c * googleConnector ) findAdminService (domain string ) (* admin.Service , error ) {
0 commit comments