Skip to content
quarry Artifact [4daa8a67d3]
Login

Artifact [4daa8a67d3]

Artifact 4daa8a67d34c721833058cde7a1156ccb5e8b4939f352d54a21b97d8d766bf92:


package oltp

import (
	"sort"
	"testing"
	"time"
)

// A wrong password costs the same whatever the name is: an account with
// no verifier of its own (an unclaimed invite, an imported fossil user)
// must not answer faster than one that has, or the time says which
// names exist and how they came to be.
func TestAuthenticateCostDoesNotTellTheNameApart(t *testing.T) {
	db := testDB(t)
	if err := db.AddAccount("real", "right-password", false); err != nil {
		t.Fatal(err)
	}
	if err := db.AddAccount("invited", "placeholder", false); err != nil {
		t.Fatal(err)
	}
	if _, err := db.w.Exec(`UPDATE account SET pwhash = '' WHERE name = 'invited'`); err != nil {
		t.Fatal(err)
	}
	names := []string{"ghost", "real", "invited"}
	samples := map[string][]time.Duration{}
	for i := 0; i < 5; i++ {
		for _, name := range names {
			start := time.Now()
			if _, ok := db.Authenticate(name, "wrong-password"); ok {
				t.Fatalf("FAIL: %s signed in with a wrong password", name)
			}
			samples[name] = append(samples[name], time.Since(start))
		}
	}
	median := func(name string) time.Duration {
		d := samples[name]
		sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
		return d[len(d)/2]
	}
	base := median("ghost")
	for _, name := range names[1:] {
		if got := median(name); got < base/2 || got > base*2 {
			t.Errorf("FAIL: a wrong password for %q costs %v against %v for an unknown name", name, got, base)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}