Skip to content

chore: fix 30% startup time hit from userpassword #12769

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions coderd/userpassword/userpassword.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"golang.org/x/crypto/pbkdf2"
"golang.org/x/exp/slices"
"golang.org/x/xerrors"

"github.com/coder/coder/v2/coderd/util/lazy"
)

var (
Expand All @@ -38,8 +40,15 @@ var (
defaultSaltSize = 16

// The simulated hash is used when trying to simulate password checks for
// users that don't exist.
simulatedHash, _ = Hash("hunter2")
// users that don't exist. It's meant to preserve the timing of the hash
// comparison.
simulatedHash = lazy.New(func() string {
h, err := Hash("hunter2")
if err != nil {
panic(err)
}
return h
})
)

// Make password hashing much faster in tests.
Expand All @@ -65,7 +74,9 @@ func init() {
func Compare(hashed string, password string) (bool, error) {
// If the hased password provided is empty, simulate comparing a real hash.
if hashed == "" {
hashed = simulatedHash
// TODO: this seems ripe for creating a vulnerability where
// hunter2 can log into any account.
hashed = simulatedHash.Load()
}

if len(hashed) < hashLength {
Expand Down
28 changes: 28 additions & 0 deletions coderd/util/lazy/value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Package lazy provides a lazy value implementation.
// It's useful especially in global variable initialization to avoid
// slowing down the program startup time.
package lazy

import (
"sync"
"sync/atomic"
)

type Value[T any] struct {
once sync.Once
fn func() T
cached atomic.Pointer[T]
}

func (v *Value[T]) Load() T {
v.once.Do(func() {
vv := v.fn()
v.cached.Store(&vv)
})
return *v.cached.Load()
}

// New creates a new lazy value with the given load function.
func New[T any](fn func() T) *Value[T] {
return &Value[T]{fn: fn}
}
Loading