18858: Adds first/last name updates, with tests.
[arvados.git] / tools / sync-users / sync-users.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bytes"
9         "encoding/csv"
10         "encoding/json"
11         "flag"
12         "fmt"
13         "io"
14         "log"
15         "net/url"
16         "os"
17         "regexp"
18         "strconv"
19         "strings"
20
21         "git.arvados.org/arvados.git/lib/cmd"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23 )
24
25 var version = "dev"
26
27 type resourceList interface {
28         Len() int
29         GetItems() []interface{}
30 }
31
32 // UserList implements resourceList interface
33 type UserList struct {
34         arvados.UserList
35 }
36
37 // Len returns the amount of items this list holds
38 func (l UserList) Len() int {
39         return len(l.Items)
40 }
41
42 // GetItems returns the list of items
43 func (l UserList) GetItems() (out []interface{}) {
44         for _, item := range l.Items {
45                 out = append(out, item)
46         }
47         return
48 }
49
50 func main() {
51         cfg, err := GetConfig()
52         if err != nil {
53                 log.Fatalf("%v", err)
54         }
55
56         if err := doMain(&cfg); err != nil {
57                 log.Fatalf("%v", err)
58         }
59 }
60
61 type ConfigParams struct {
62         CaseInsensitive    bool
63         Client             *arvados.Client
64         ClusterID          string
65         CurrentUser        arvados.User
66         DeactivateUnlisted bool
67         Path               string
68         UserID             string
69         SysUserUUID        string
70         AnonUserUUID       string
71         Verbose            bool
72 }
73
74 func ParseFlags(cfg *ConfigParams) error {
75         // Acceptable attributes to identify a user on the CSV file
76         userIDOpts := map[string]bool{
77                 "email":    true, // default
78                 "username": true,
79         }
80
81         flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
82         flags.Usage = func() {
83                 usageStr := `Synchronize remote users into Arvados from a CSV format file with 5 columns:
84   * 1st: User Identifier (email or username)
85   * 2nd: First name
86   * 3rd: Last name
87   * 4th: Active status (0 or 1)
88   * 5th: Admin status (0 or 1)`
89                 fmt.Fprintf(flags.Output(), "%s\n\n", usageStr)
90                 fmt.Fprintf(flags.Output(), "Usage:\n%s [OPTIONS] <input-file.csv>\n\n", os.Args[0])
91                 fmt.Fprintf(flags.Output(), "Options:\n")
92                 flags.PrintDefaults()
93         }
94
95         caseInsensitive := flags.Bool(
96                 "case-insensitive",
97                 false,
98                 "Performs case insensitive matching on user IDs. Always ON when using 'email' user IDs.")
99         deactivateUnlisted := flags.Bool(
100                 "deactivate-unlisted",
101                 false,
102                 "Deactivate users that are not in the input file.")
103         userID := flags.String(
104                 "user-id",
105                 "email",
106                 "Attribute by which every user is identified. Valid values are: email and username.")
107         verbose := flags.Bool(
108                 "verbose",
109                 false,
110                 "Log informational messages.")
111         getVersion := flags.Bool(
112                 "version",
113                 false,
114                 "Print version information and exit.")
115
116         if ok, code := cmd.ParseFlags(flags, os.Args[0], os.Args[1:], "input-file.csv", os.Stderr); !ok {
117                 os.Exit(code)
118         } else if *getVersion {
119                 fmt.Printf("%s %s\n", os.Args[0], version)
120                 os.Exit(0)
121         }
122
123         // Input file as a required positional argument
124         if flags.NArg() == 0 {
125                 return fmt.Errorf("please provide a path to an input file")
126         }
127         srcPath := &os.Args[flags.NFlag()+1]
128
129         // Validations
130         if *srcPath == "" {
131                 return fmt.Errorf("input file path invalid")
132         }
133         if !userIDOpts[*userID] {
134                 var options []string
135                 for opt := range userIDOpts {
136                         options = append(options, opt)
137                 }
138                 return fmt.Errorf("user ID must be one of: %s", strings.Join(options, ", "))
139         }
140         if *userID == "email" {
141                 // Always do case-insensitive email addresses matching
142                 *caseInsensitive = true
143         }
144
145         cfg.CaseInsensitive = *caseInsensitive
146         cfg.DeactivateUnlisted = *deactivateUnlisted
147         cfg.Path = *srcPath
148         cfg.UserID = *userID
149         cfg.Verbose = *verbose
150
151         return nil
152 }
153
154 // GetConfig sets up a ConfigParams struct
155 func GetConfig() (cfg ConfigParams, err error) {
156         err = ParseFlags(&cfg)
157         if err != nil {
158                 return
159         }
160
161         cfg.Client = arvados.NewClientFromEnv()
162
163         // Check current user permissions
164         u, err := cfg.Client.CurrentUser()
165         if err != nil {
166                 return cfg, fmt.Errorf("error getting the current user: %s", err)
167         }
168         if !u.IsAdmin {
169                 return cfg, fmt.Errorf("current user %q is not an admin user", u.UUID)
170         }
171         if cfg.Verbose {
172                 log.Printf("Running as admin user %q (%s)", u.Email, u.UUID)
173         }
174         cfg.CurrentUser = u
175
176         var ac struct {
177                 ClusterID string
178                 Login     struct {
179                         LoginCluster string
180                 }
181         }
182         err = cfg.Client.RequestAndDecode(&ac, "GET", "arvados/v1/config", nil, nil)
183         if err != nil {
184                 return cfg, fmt.Errorf("error getting the exported config: %s", err)
185         }
186         if ac.Login.LoginCluster != "" && ac.Login.LoginCluster != ac.ClusterID {
187                 return cfg, fmt.Errorf("cannot run on a cluster other than the login cluster")
188         }
189         cfg.SysUserUUID = ac.ClusterID + "-tpzed-000000000000000"
190         cfg.AnonUserUUID = ac.ClusterID + "-tpzed-anonymouspublic"
191         cfg.ClusterID = ac.ClusterID
192
193         return cfg, nil
194 }
195
196 // GetUserID returns the correct user id value depending on the selector
197 func GetUserID(u arvados.User, idSelector string) (string, error) {
198         switch idSelector {
199         case "email":
200                 return u.Email, nil
201         case "username":
202                 return u.Username, nil
203         default:
204                 return "", fmt.Errorf("cannot identify user by %q selector", idSelector)
205         }
206 }
207
208 func doMain(cfg *ConfigParams) error {
209         // Try opening the input file early, just in case there's a problem.
210         f, err := os.Open(cfg.Path)
211         if err != nil {
212                 return fmt.Errorf("error opening input file: %s", err)
213         }
214         defer f.Close()
215
216         iCaseLog := ""
217         if cfg.UserID == "username" && cfg.CaseInsensitive {
218                 iCaseLog = " - username matching requested to be case-insensitive"
219         }
220         log.Printf("%s %s started. Using %q as users id%s", os.Args[0], version, cfg.UserID, iCaseLog)
221
222         allUsers := make(map[string]arvados.User)
223         userIDToUUID := make(map[string]string) // Index by email or username
224         dupedEmails := make(map[string][]arvados.User)
225         processedUsers := make(map[string]bool)
226         results, err := GetAll(cfg.Client, "users", arvados.ResourceListParams{}, &UserList{})
227         if err != nil {
228                 return fmt.Errorf("error getting all users: %s", err)
229         }
230         log.Printf("Found %d users in cluster %q", len(results), cfg.ClusterID)
231         localUserUuidRegex := regexp.MustCompile(fmt.Sprintf("^%s-tpzed-[0-9a-z]{15}$", cfg.ClusterID))
232         for _, item := range results {
233                 u := item.(arvados.User)
234
235                 // Remote user check
236                 if !localUserUuidRegex.MatchString(u.UUID) {
237                         if cfg.Verbose {
238                                 log.Printf("Remote user %q (%s) won't be considered for processing", u.Email, u.UUID)
239                         }
240                         continue
241                 }
242
243                 // Duplicated user id check
244                 uID, err := GetUserID(u, cfg.UserID)
245                 if err != nil {
246                         return err
247                 }
248                 if uID == "" {
249                         return fmt.Errorf("%s is empty for user with uuid %q", cfg.UserID, u.UUID)
250                 }
251                 if cfg.CaseInsensitive {
252                         uID = strings.ToLower(uID)
253                 }
254                 if alreadySeenUUID, found := userIDToUUID[uID]; found {
255                         if cfg.UserID == "username" && uID != "" {
256                                 return fmt.Errorf("case insensitive collision for username %q between %q and %q", uID, u.UUID, alreadySeenUUID)
257                         } else if cfg.UserID == "email" && uID != "" {
258                                 log.Printf("Duplicated email %q found in user %s - ignoring", uID, u.UUID)
259                                 if len(dupedEmails[uID]) == 0 {
260                                         dupedEmails[uID] = []arvados.User{allUsers[alreadySeenUUID]}
261                                 }
262                                 dupedEmails[uID] = append(dupedEmails[uID], u)
263                                 delete(allUsers, alreadySeenUUID) // Skip even the first occurrence,
264                                 // for security purposes.
265                                 continue
266                         }
267                 }
268                 if cfg.Verbose {
269                         log.Printf("Seen user %q (%s)", uID, u.UUID)
270                 }
271                 userIDToUUID[uID] = u.UUID
272                 allUsers[u.UUID] = u
273                 processedUsers[u.UUID] = false
274         }
275
276         loadedRecords, err := LoadInputFile(f)
277         if err != nil {
278                 return fmt.Errorf("reading input file %q: %s", cfg.Path, err)
279         }
280         log.Printf("Loaded %d records from input file", len(loadedRecords))
281
282         updatesSucceeded := map[string]bool{}
283         updatesFailed := map[string]bool{}
284         updatesSkipped := map[string]bool{}
285
286         for _, record := range loadedRecords {
287                 if cfg.CaseInsensitive {
288                         record.UserID = strings.ToLower(record.UserID)
289                 }
290                 recordUUID := userIDToUUID[record.UserID]
291                 processedUsers[recordUUID] = true
292                 if cfg.UserID == "email" && record.UserID == cfg.CurrentUser.Email {
293                         updatesSkipped[recordUUID] = true
294                         log.Printf("Skipping current user %q (%s) from processing", record.UserID, cfg.CurrentUser.UUID)
295                         continue
296                 }
297                 if updated, err := ProcessRecord(cfg, record, userIDToUUID, allUsers); err != nil {
298                         log.Printf("error processing record %q: %s", record.UserID, err)
299                         updatesFailed[recordUUID] = true
300                 } else if updated {
301                         updatesSucceeded[recordUUID] = true
302                 }
303         }
304
305         if cfg.DeactivateUnlisted {
306                 for userUUID, user := range allUsers {
307                         if shouldSkip(cfg, user) {
308                                 updatesSkipped[userUUID] = true
309                                 log.Printf("Skipping unlisted user %q (%s) from deactivating", user.Email, user.UUID)
310                                 continue
311                         }
312                         if !processedUsers[userUUID] && allUsers[userUUID].IsActive {
313                                 if cfg.Verbose {
314                                         log.Printf("Deactivating unlisted user %q (%s)", user.Username, user.UUID)
315                                 }
316                                 var updatedUser arvados.User
317                                 if err := UnsetupUser(cfg.Client, user.UUID, &updatedUser); err != nil {
318                                         log.Printf("error deactivating unlisted user %q: %s", user.UUID, err)
319                                         updatesFailed[userUUID] = true
320                                 } else {
321                                         allUsers[userUUID] = updatedUser
322                                         updatesSucceeded[userUUID] = true
323                                 }
324                         }
325                 }
326         }
327
328         log.Printf("User update successes: %d, skips: %d, failures: %d", len(updatesSucceeded), len(updatesSkipped), len(updatesFailed))
329
330         // Report duplicated emails detection
331         if len(dupedEmails) > 0 {
332                 emails := make([]string, len(dupedEmails))
333                 i := 0
334                 for e := range dupedEmails {
335                         emails[i] = e
336                         i++
337                 }
338                 return fmt.Errorf("skipped %d duplicated email address(es) in the cluster's local user list: %v", len(dupedEmails), emails)
339         }
340
341         return nil
342 }
343
344 func shouldSkip(cfg *ConfigParams, user arvados.User) bool {
345         switch user.UUID {
346         case cfg.SysUserUUID, cfg.AnonUserUUID:
347                 return true
348         case cfg.CurrentUser.UUID:
349                 return true
350         }
351         return false
352 }
353
354 type userRecord struct {
355         UserID    string
356         FirstName string
357         LastName  string
358         Active    bool
359         Admin     bool
360 }
361
362 func needsUpdating(user arvados.User, record userRecord) bool {
363         userData := userRecord{"", user.FirstName, user.LastName, user.IsActive, user.IsAdmin}
364         recordData := userRecord{"", record.FirstName, record.LastName, record.Active, record.Admin}
365         return userData != recordData
366 }
367
368 // ProcessRecord creates or updates a user based on the given record
369 func ProcessRecord(cfg *ConfigParams, record userRecord, userIDToUUID map[string]string, allUsers map[string]arvados.User) (bool, error) {
370         if cfg.Verbose {
371                 log.Printf("Processing record for user %q", record.UserID)
372         }
373
374         wantedActiveStatus := strconv.FormatBool(record.Active)
375         wantedAdminStatus := strconv.FormatBool(record.Active && record.Admin)
376         createRequired := false
377         updateRequired := false
378         // Check if user exists, set its active & admin status.
379         var user arvados.User
380         recordUUID := userIDToUUID[record.UserID]
381         user, found := allUsers[recordUUID]
382         if !found {
383                 if cfg.Verbose {
384                         log.Printf("User %q does not exist, creating", record.UserID)
385                 }
386                 createRequired = true
387                 err := CreateUser(cfg.Client, &user, map[string]string{
388                         cfg.UserID:   record.UserID,
389                         "first_name": record.FirstName,
390                         "last_name":  record.LastName,
391                         "is_active":  wantedActiveStatus,
392                         "is_admin":   wantedAdminStatus,
393                 })
394                 if err != nil {
395                         return false, fmt.Errorf("error creating user %q: %s", record.UserID, err)
396                 }
397         } else if needsUpdating(user, record) {
398                 updateRequired = true
399                 if record.Active {
400                         if !user.IsActive && cfg.Verbose {
401                                 log.Printf("User %q (%s) is inactive, activating", record.UserID, user.UUID)
402                         }
403                         // Here we assume the 'setup' is done elsewhere if needed.
404                         err := UpdateUser(cfg.Client, user.UUID, &user, map[string]string{
405                                 "first_name": record.FirstName,
406                                 "last_name":  record.LastName,
407                                 "is_active":  wantedActiveStatus,
408                                 "is_admin":   wantedAdminStatus,
409                         })
410                         if err != nil {
411                                 return false, fmt.Errorf("error updating user %q: %s", record.UserID, err)
412                         }
413                 } else {
414                         fnChanged := user.FirstName != record.FirstName
415                         lnChanged := user.LastName != record.LastName
416                         if fnChanged || lnChanged {
417                                 err := UpdateUser(cfg.Client, user.UUID, &user, map[string]string{
418                                         "first_name": record.FirstName,
419                                         "last_name":  record.LastName,
420                                 })
421                                 if err != nil {
422                                         return false, fmt.Errorf("error updating user %q: %s", record.UserID, err)
423                                 }
424                         }
425                         if user.IsActive {
426                                 if cfg.Verbose {
427                                         log.Printf("User %q is active, deactivating", record.UserID)
428                                 }
429                                 err := UnsetupUser(cfg.Client, user.UUID, &user)
430                                 if err != nil {
431                                         return false, fmt.Errorf("error deactivating user %q: %s", record.UserID, err)
432                                 }
433                         }
434                 }
435         }
436         allUsers[record.UserID] = user
437         if createRequired {
438                 log.Printf("Created user %q", record.UserID)
439         }
440         if updateRequired {
441                 log.Printf("Updated user %q", record.UserID)
442         }
443
444         return createRequired || updateRequired, nil
445 }
446
447 // LoadInputFile reads the input file and returns a list of user records
448 func LoadInputFile(f *os.File) (loadedRecords []userRecord, err error) {
449         lineNo := 0
450         csvReader := csv.NewReader(f)
451         loadedRecords = make([]userRecord, 0)
452
453         for {
454                 record, e := csvReader.Read()
455                 if e == io.EOF {
456                         break
457                 }
458                 lineNo++
459                 if e != nil {
460                         err = fmt.Errorf("parsing error at line %d: %s", lineNo, e)
461                         return
462                 }
463                 if len(record) != 5 {
464                         err = fmt.Errorf("parsing error at line %d: expected 5 fields, found %d", lineNo, len(record))
465                         return
466                 }
467                 userID := strings.ToLower(strings.TrimSpace(record[0]))
468                 firstName := strings.TrimSpace(record[1])
469                 lastName := strings.TrimSpace(record[2])
470                 active := strings.TrimSpace(record[3])
471                 admin := strings.TrimSpace(record[4])
472                 if userID == "" || firstName == "" || lastName == "" || active == "" || admin == "" {
473                         err = fmt.Errorf("parsing error at line %d: fields cannot be empty", lineNo)
474                         return
475                 }
476                 activeBool, err := strconv.ParseBool(active)
477                 if err != nil {
478                         return nil, fmt.Errorf("parsing error at line %d: active status not recognized", lineNo)
479                 }
480                 adminBool, err := strconv.ParseBool(admin)
481                 if err != nil {
482                         return nil, fmt.Errorf("parsing error at line %d: admin status not recognized", lineNo)
483                 }
484                 loadedRecords = append(loadedRecords, userRecord{
485                         UserID:    userID,
486                         FirstName: firstName,
487                         LastName:  lastName,
488                         Active:    activeBool,
489                         Admin:     adminBool,
490                 })
491         }
492         return loadedRecords, nil
493 }
494
495 // GetAll adds all objects of type 'resource' to the 'allItems' list
496 func GetAll(c *arvados.Client, res string, params arvados.ResourceListParams, page resourceList) (allItems []interface{}, err error) {
497         // Use the maximum page size the server allows
498         limit := 1<<31 - 1
499         params.Limit = &limit
500         params.Offset = 0
501         params.Order = "uuid"
502         for {
503                 if err = GetResourceList(c, &page, res, params); err != nil {
504                         return allItems, err
505                 }
506                 // Have we finished paging?
507                 if page.Len() == 0 {
508                         break
509                 }
510                 allItems = append(allItems, page.GetItems()...)
511                 params.Offset += page.Len()
512         }
513         return allItems, nil
514 }
515
516 func jsonReader(rscName string, ob interface{}) io.Reader {
517         j, err := json.Marshal(ob)
518         if err != nil {
519                 panic(err)
520         }
521         v := url.Values{}
522         v[rscName] = []string{string(j)}
523         return bytes.NewBufferString(v.Encode())
524 }
525
526 // GetResourceList fetches res list using params
527 func GetResourceList(c *arvados.Client, dst *resourceList, res string, params interface{}) error {
528         return c.RequestAndDecode(dst, "GET", "/arvados/v1/"+res, nil, params)
529 }
530
531 // CreateUser creates a user with userData parameters, assigns it to dst
532 func CreateUser(c *arvados.Client, dst *arvados.User, userData map[string]string) error {
533         return c.RequestAndDecode(dst, "POST", "/arvados/v1/users", jsonReader("user", userData), nil)
534 }
535
536 // UpdateUser updates a user with userData parameters
537 func UpdateUser(c *arvados.Client, userUUID string, dst *arvados.User, userData map[string]string) error {
538         return c.RequestAndDecode(&dst, "PUT", "/arvados/v1/users/"+userUUID, jsonReader("user", userData), nil)
539 }
540
541 // UnsetupUser deactivates a user
542 func UnsetupUser(c *arvados.Client, userUUID string, dst *arvados.User) error {
543         return c.RequestAndDecode(&dst, "POST", "/arvados/v1/users/"+userUUID+"/unsetup", nil, nil)
544 }