Skip to content

a2fa list results in random number of records listed #4

@adrian-green

Description

@adrian-green

Steps to reproduce

Run with argument "list" multiple times

Expected behaviour

All records displayed

Actual behaviour

Random records displayed
image

Environment info

linux Ubuntu / Windows 11

Proposed fix: (confirmed to work locally)
Alter cmd/commands/list.go listAccounts

When the append(result, otpView{...}) line of code is run concurrently from multiple goroutines, they all try to write to the result slice at the same time which results in some writes being lost.
Solution: synchronize access to the result slice by wrapping the section in a mutex

example:

var wg sync.WaitGroup
var mu sync.Mutex
for _, account := range accounts {
	wg.Add(1)
	go func(account models.Account) {
		defer wg.Done()
		code, err := account.OTP()
		if err != nil {
			log.Printf("%s %s generate code error%s\n", account.AccountName, account.Username, err)
		} else {
			mu.Lock() // start critical section
			result = append(result, otpView{
				accountName: account.AccountName,
				userName:    account.Username,
				code:        code,
			})
			mu.Unlock() // end critical section
		}
	}(account)
}...`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions