Skip to content

Commit

Permalink
Reuse existing user id if it exists
Browse files Browse the repository at this point in the history
We dont want to fully skip the user update if it exists as it may be for
a specific reason like updating groups and such, but if the entry does
not have a specific user id set by the user object and the user already
exists in the passwd file, we should reuse the userid as to not break
existing files that may have permissions linked to that user

This should fix:
 - users in config files appearing more than once, so their uid wont
   change
 - ssh keys added to users than are updated after the key creation
 - anything else adding a user to the passwd file and bumping the next
   uid free, as our calculation picks the latest free uid

Signed-off-by: Itxaka <[email protected]>
  • Loading branch information
Itxaka committed Apr 22, 2024
1 parent 5b137a7 commit fd9a122
Showing 1 changed file with 24 additions and 11 deletions.
35 changes: 24 additions & 11 deletions pkg/plugins/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ func createUser(fs vfs.FS, u schema.User, console Console) error {
gid = usedGids[len(usedGids)-1]
gid++
}

}

updateGroup := entities.Group{
Expand All @@ -112,20 +111,34 @@ func createUser(fs vfs.FS, u schema.User, console Console) error {
return errors.Wrap(err, "invalid uid defined")
}
} else {
// find an available uid if there are others already
all, _ := passwd.ParseFile(etcpasswd)
if len(all) != 0 {
usedUids := []int{}
for _, entry := range all {
uid, _ := strconv.Atoi(entry.Uid)
usedUids = append(usedUids, uid)
// Check if user is already in there to reuse the same UID as to not break existing permissions
existing := false
for name, values := range all {
if name == u.Name {
uid, err = strconv.Atoi(values.Uid)
if err != nil {
return errors.Wrap(err, "could not parse existing user id")
}
existing = true
break
}
}
sort.Ints(usedUids)
if len(usedUids) == 0 {
return errors.New("no new UID found")
// If it's not there, get a new UID
if !existing {
usedUids := []int{}
for _, entry := range all {
uid, _ := strconv.Atoi(entry.Uid)
usedUids = append(usedUids, uid)
}
sort.Ints(usedUids)
if len(usedUids) == 0 {
return errors.New("no new UID found")
}
uid = usedUids[len(usedUids)-1]
uid++
}
uid = usedUids[len(usedUids)-1]
uid++
}
}

Expand Down

0 comments on commit fd9a122

Please sign in to comment.